From ad1ec3669de3a0657d5a49e274b42ad18cf457be Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 17 Nov 2010 14:43:18 +0100 Subject: [PATCH 01/81] functor operator applying to population in parallel --- eo/CMakeLists.txt | 6 ++++++ eo/doc/index.h | 4 ++-- eo/src/apply.h | 2 ++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/eo/CMakeLists.txt b/eo/CMakeLists.txt index eea4df29..07becc2b 100644 --- a/eo/CMakeLists.txt +++ b/eo/CMakeLists.txt @@ -44,6 +44,12 @@ ENABLE_LANGUAGE(C) ### 2) Include required modules / configuration files ##################################################################################### +FIND_PACKAGE(OpenMP REQUIRED) +IF(OPENMP_FOUND) + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_CXX_FLAGS}") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_C_FLAGS}") +ENDIF() + INCLUDE(CMakeBackwardCompatibilityCXX) INCLUDE(FindDoxygen) diff --git a/eo/doc/index.h b/eo/doc/index.h index 7d7921fe..2fad16e2 100644 --- a/eo/doc/index.h +++ b/eo/doc/index.h @@ -51,9 +51,9 @@ with a member like: operator()(eoPop). Once called on a given population, i search for the optimum of a given problem. Generally, operators are instanciated once and then binded in an algorithm by reference. -Thus, you can easily build you own algorithm by trying several combination of operators. +Thus, you can easily build your own algorithm by trying several combination of operators. -For an more detailled introduction to the design of %EO you can look at the +For a more detailled introduction to the design of %EO you can look at the slides from a talk at EA 2001 or at the corresponding article in Lecture Notes In Computer Science, 2310, Selected Papers from the 5th European Conference on Artificial Evolution: - http://portal.acm.org/citation.cfm?id=727742 diff --git a/eo/src/apply.h b/eo/src/apply.h index 0eb3484e..049983fe 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -37,8 +37,10 @@ template void apply(eoUF& _proc, std::vector& _pop) { +#pragma omp parallel for default(none) shared(_proc, _pop) for (unsigned i = 0; i < _pop.size(); ++i) { +#pragma omp critical _proc(_pop[i]); } } From ebaf81ae8d6a5cd944cbd6630369e62b3a4609d4 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 17 Nov 2010 17:27:55 +0100 Subject: [PATCH 02/81] added a apply.h variant for parallel execution --- eo/src/apply.h | 2 -- eo/src/omp_apply.h | 51 +++++++++++++++++++++++++++++++++++ eo/test/CMakeLists.txt | 1 + eo/test/t-openmp.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 eo/src/omp_apply.h create mode 100644 eo/test/t-openmp.cpp diff --git a/eo/src/apply.h b/eo/src/apply.h index 049983fe..0eb3484e 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -37,10 +37,8 @@ template void apply(eoUF& _proc, std::vector& _pop) { -#pragma omp parallel for default(none) shared(_proc, _pop) for (unsigned i = 0; i < _pop.size(); ++i) { -#pragma omp critical _proc(_pop[i]); } } diff --git a/eo/src/omp_apply.h b/eo/src/omp_apply.h new file mode 100644 index 00000000..bbdc4065 --- /dev/null +++ b/eo/src/omp_apply.h @@ -0,0 +1,51 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoApply.h +// (c) Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _omp_apply_h +#define _omp_apply_h + +#include +#include + +/** + Applies a unary function to a std::vector of things. + + This is a variant of apply which is called in parallel + thanks to OpenMP. + + @ingroup Utilities +*/ +template +void omp_apply(eoUF& _proc, std::vector& _pop) +{ +#pragma omp parallel for default(none) shared(_proc, _pop) + for (unsigned i = 0; i < _pop.size(); ++i) + { + //#pragma omp critical + _proc(_pop[i]); + } +} + +#endif diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index 4f194681..fe28b21f 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -65,6 +65,7 @@ SET (TEST_LIST t-eoExtendedVelocity t-eoLogger t-eoIQRStat + t-openmp ) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp new file mode 100644 index 00000000..d098ac35 --- /dev/null +++ b/eo/test/t-openmp.cpp @@ -0,0 +1,61 @@ +//----------------------------------------------------------------------------- +// t-openmp.cpp +//----------------------------------------------------------------------------- + +#include +#include + +#include +#include + +#include +#include + +#include + +#include "real_value.h" + +//----------------------------------------------------------------------------- + +typedef eoReal< eoMinimizingFitness > EOT; + +//----------------------------------------------------------------------------- + +int main(int ac, char** av) +{ + eoParserLogger parser(ac, av); + eoState state; + + eoRealInitBounded& init = make_genotype( parser, state, EOT() ); + eoPop< EOT >& pop = make_pop( parser, state, init ); + eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); + eoEvalFuncCounter eval( mainEval ); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + make_help(parser); + make_verbose(parser); + + double ts1 = omp_get_wtime(); + apply< EOT >( eval, pop ); + //sleep(1); + double ts2 = omp_get_wtime(); + + eoPop< EOT >& pop2 = make_pop( parser, state, init ); + + double tp1 = omp_get_wtime(); + omp_apply< EOT >( eval, pop2 ); + //sleep(1); + double tp2 = omp_get_wtime(); + + eo::log << "Ts = " << ts2 - ts1 << std::endl; + eo::log << "Tp = " << tp2 - tp1 << std::endl; + + return 0; +} + +//----------------------------------------------------------------------------- From 790153f6aa9cbb0381941f352ecc3c8f845abbde Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Fri, 19 Nov 2010 11:48:42 +0100 Subject: [PATCH 03/81] openmp test updated --- eo/test/t-openmp.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index d098ac35..0e5f7238 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -28,6 +28,7 @@ int main(int ac, char** av) eoRealInitBounded& init = make_genotype( parser, state, EOT() ); eoPop< EOT >& pop = make_pop( parser, state, init ); + eoPop< EOT >& pop2 = make_pop( parser, state, init ); eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); eoEvalFuncCounter eval( mainEval ); @@ -45,8 +46,6 @@ int main(int ac, char** av) //sleep(1); double ts2 = omp_get_wtime(); - eoPop< EOT >& pop2 = make_pop( parser, state, init ); - double tp1 = omp_get_wtime(); omp_apply< EOT >( eval, pop2 ); //sleep(1); From 6625cd247bb2015dbffd58af59a9224d90e6dc5c Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 20 Nov 2010 01:01:45 +0100 Subject: [PATCH 04/81] openmp testing up-to-date --- eo/test/CMakeLists.txt | 12 ++++++ eo/test/boxplot.py | 10 +++++ eo/test/t-openmp.cpp | 89 ++++++++++++++++++++++++++++++++++-------- 3 files changed, 95 insertions(+), 16 deletions(-) create mode 100755 eo/test/boxplot.py diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index fe28b21f..8d7956ba 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -93,6 +93,18 @@ ELSEIF(ENABLE_CMAKE_TESTING) INSTALL(TARGETS ${test} RUNTIME DESTINATION share/eo/test COMPONENT test) ENDFOREACH (test) + SET(RESOURCES + boxplot.py + ) + + FOREACH(file ${RESOURCES}) + EXECUTE_PROCESS( + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/${file} + ${CMAKE_CURRENT_BINARY_DIR}/${file} + ) + ENDFOREACH(file) + ENDIF(ENABLE_MINIMAL_CMAKE_TESTING) ###################################################################################### diff --git a/eo/test/boxplot.py b/eo/test/boxplot.py new file mode 100755 index 00000000..0590e4e9 --- /dev/null +++ b/eo/test/boxplot.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python + +from pylab import * +import sys + +DEFAULT_RESULTS_NAME = 'results.txt' + +if __name__ == '__main__': + boxplot( [ [ float(value) for value in line.split() ] for line in open( DEFAULT_RESULTS_NAME if len(sys.argv) < 2 else sys.argv[1] ).readlines() ] ) + show() diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 0e5f7238..4ccc54ad 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -2,6 +2,10 @@ // t-openmp.cpp //----------------------------------------------------------------------------- +#include +#include +#include + #include #include @@ -24,13 +28,21 @@ typedef eoReal< eoMinimizingFitness > EOT; int main(int ac, char** av) { eoParserLogger parser(ac, av); - eoState state; - eoRealInitBounded& init = make_genotype( parser, state, EOT() ); - eoPop< EOT >& pop = make_pop( parser, state, init ); - eoPop< EOT >& pop2 = make_pop( parser, state, init ); - eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); - eoEvalFuncCounter eval( mainEval ); + unsigned int popMin = parser.getORcreateParam((unsigned int)1, "popMin", "Population Min", 'p', "Evolution Engine").value(); + unsigned int popMax = parser.getORcreateParam((unsigned int)100, "popMax", "Population Max", 'P', "Evolution Engine").value(); + + unsigned int dimMin = parser.getORcreateParam((unsigned int)1, "dimMin", "Dimension Min", 'd', "Evolution Engine").value(); + unsigned int dimMax = parser.getORcreateParam((unsigned int)100, "dimMax", "Dimension Max", 'D', "Evolution Engine").value(); + + unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value(); + + std::string resultsFileName = parser.getORcreateParam(std::string("results.txt"), "resultsFileName", "Results file name", 0, "Evolution Engine").value(); + + double threshold = parser.getORcreateParam((double)3.0, "threshold", "Threshold of max speedup", 0, "Evolution Engine").value(); + + uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); + if (seedParam == 0) { seedParam = time(0); } if (parser.userNeedsHelp()) { @@ -41,18 +53,63 @@ int main(int ac, char** av) make_help(parser); make_verbose(parser); - double ts1 = omp_get_wtime(); - apply< EOT >( eval, pop ); - //sleep(1); - double ts2 = omp_get_wtime(); + rng.reseed( seedParam ); - double tp1 = omp_get_wtime(); - omp_apply< EOT >( eval, pop2 ); - //sleep(1); - double tp2 = omp_get_wtime(); + eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); + eoEvalFuncCounter eval( mainEval ); - eo::log << "Ts = " << ts2 - ts1 << std::endl; - eo::log << "Tp = " << tp2 - tp1 << std::endl; + eoUniformGenerator< double > gen(-5, 5); + + std::ostringstream ss; + ss << resultsFileName << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-t" << threshold << "-s" << seedParam; + std::ofstream resultsFile( ss.str().c_str() ); + + for ( size_t p = popMin; p <= popMax; ++p ) + { + for ( size_t d = dimMin; d <= dimMax; ++d ) + { + eo::log << eo::logging << p << 'x' << d << std::endl; + + for ( size_t r = 0; r < nRun; ++r ) + { + eoInitFixedLength< EOT > init( d, gen ); + + double Ts; + double Tp; + + // sequential scope + { + eoPop< EOT > pop( p, init ); + double t1 = omp_get_wtime(); + apply< EOT >(eval, pop); + double t2 = omp_get_wtime(); + Ts = t2 - t1; + } + + // parallel scope + { + eoPop< EOT > pop( p, init ); + double t1 = omp_get_wtime(); + omp_apply< EOT >(eval, pop); + double t2 = omp_get_wtime(); + Tp = t2 - t1; + } + + if ( ( Ts / Tp ) > threshold ) { continue; } + + resultsFile << Ts / Tp << ' '; + + eo::log << eo::debug; + eo::log << "Ts = " << Ts << std::endl; + eo::log << "Tp = " << Tp << std::endl; + eo::log << "S_p = " << Ts / Tp << std::endl; + } // end of runs + + resultsFile << std::endl; + + } // end of dimension + + } // end of population return 0; } From eb9937ee0c668d515ce88512cd146dcf5d079062 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 20 Nov 2010 01:57:30 +0100 Subject: [PATCH 05/81] added stepping parameters --- eo/test/boxplot.py | 3 ++- eo/test/t-openmp.cpp | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/eo/test/boxplot.py b/eo/test/boxplot.py index 0590e4e9..581fef0c 100755 --- a/eo/test/boxplot.py +++ b/eo/test/boxplot.py @@ -7,4 +7,5 @@ DEFAULT_RESULTS_NAME = 'results.txt' if __name__ == '__main__': boxplot( [ [ float(value) for value in line.split() ] for line in open( DEFAULT_RESULTS_NAME if len(sys.argv) < 2 else sys.argv[1] ).readlines() ] ) - show() + #show() + savefig( sys.argv[1] + ".png" ) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 4ccc54ad..89082b8d 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -30,9 +30,11 @@ int main(int ac, char** av) eoParserLogger parser(ac, av); unsigned int popMin = parser.getORcreateParam((unsigned int)1, "popMin", "Population Min", 'p', "Evolution Engine").value(); + unsigned int popStep = parser.getORcreateParam((unsigned int)1, "popStep", "Population Step", 0, "Evolution Engine").value(); unsigned int popMax = parser.getORcreateParam((unsigned int)100, "popMax", "Population Max", 'P', "Evolution Engine").value(); unsigned int dimMin = parser.getORcreateParam((unsigned int)1, "dimMin", "Dimension Min", 'd', "Evolution Engine").value(); + unsigned int dimStep = parser.getORcreateParam((unsigned int)1, "dimStep", "Dimension Step", 0, "Evolution Engine").value(); unsigned int dimMax = parser.getORcreateParam((unsigned int)100, "dimMax", "Dimension Max", 'D', "Evolution Engine").value(); unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value(); @@ -64,9 +66,9 @@ int main(int ac, char** av) ss << resultsFileName << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-t" << threshold << "-s" << seedParam; std::ofstream resultsFile( ss.str().c_str() ); - for ( size_t p = popMin; p <= popMax; ++p ) + for ( size_t p = popMin; p <= popMax; p += popStep ) { - for ( size_t d = dimMin; d <= dimMax; ++d ) + for ( size_t d = dimMin; d <= dimMax; d += dimStep ) { eo::log << eo::logging << p << 'x' << d << std::endl; From cb8e6ab1c3eee099f073f719dc59d45220e5dafa Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 14:07:47 +0100 Subject: [PATCH 06/81] added efficienty computation --- eo/test/boxplot.py | 15 +++++++++------ eo/test/t-openmp.cpp | 27 ++++++++++++++++++++------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/eo/test/boxplot.py b/eo/test/boxplot.py index 581fef0c..2b5141af 100755 --- a/eo/test/boxplot.py +++ b/eo/test/boxplot.py @@ -1,11 +1,14 @@ #!/usr/bin/env python -from pylab import * +import pylab import sys -DEFAULT_RESULTS_NAME = 'results.txt' - if __name__ == '__main__': - boxplot( [ [ float(value) for value in line.split() ] for line in open( DEFAULT_RESULTS_NAME if len(sys.argv) < 2 else sys.argv[1] ).readlines() ] ) - #show() - savefig( sys.argv[1] + ".png" ) + if len(sys.argv) < 3: + print 'Usage: boxplot.py [Results files, ...] [output file in .png]' + sys.exit() + + for i in range(1, len(sys.argv) - 1): + pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) + + pylab.savefig( sys.argv[ len(sys.argv) - 1 ] ) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 89082b8d..c4b88570 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -39,10 +39,11 @@ int main(int ac, char** av) unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value(); - std::string resultsFileName = parser.getORcreateParam(std::string("results.txt"), "resultsFileName", "Results file name", 0, "Evolution Engine").value(); - double threshold = parser.getORcreateParam((double)3.0, "threshold", "Threshold of max speedup", 0, "Evolution Engine").value(); + std::string speedupFileName = parser.getORcreateParam(std::string("speedup"), "speedupFileName", "Speedup file name", 0, "Results").value(); + std::string efficiencyFileName = parser.getORcreateParam(std::string("efficiency"), "efficiencyFileName", "Efficiency file name", 0, "Results").value(); + uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); if (seedParam == 0) { seedParam = time(0); } @@ -62,9 +63,18 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); - std::ostringstream ss; - ss << resultsFileName << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-t" << threshold << "-s" << seedParam; - std::ofstream resultsFile( ss.str().c_str() ); + std::ostringstream params; + params << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-t" << threshold << "-s" << seedParam; + std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); + std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); + + size_t nbtask = 1; +#pragma omp parallel + { + nbtask = omp_get_num_threads(); + } + + eo::log << eo::logging << "Nb task: " << nbtask << std::endl; for ( size_t p = popMin; p <= popMax; p += popStep ) { @@ -99,15 +109,18 @@ int main(int ac, char** av) if ( ( Ts / Tp ) > threshold ) { continue; } - resultsFile << Ts / Tp << ' '; + speedupFile << Ts / Tp << ' '; + efficiencyFile << Ts / ( nbtask * Tp ); eo::log << eo::debug; eo::log << "Ts = " << Ts << std::endl; eo::log << "Tp = " << Tp << std::endl; eo::log << "S_p = " << Ts / Tp << std::endl; + eo::log << "E_p = " << Ts / ( nbtask * Tp ) << std::endl; } // end of runs - resultsFile << std::endl; + speedupFile << std::endl; + efficiencyFile << std::endl; } // end of dimension From 78b4da4c319754fe4c9447168ec1621646adc1a4 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 14:47:55 +0100 Subject: [PATCH 07/81] remove threshold parameter and move from static schedule to dynamic --- eo/src/omp_apply.h | 2 +- eo/test/t-openmp.cpp | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/eo/src/omp_apply.h b/eo/src/omp_apply.h index bbdc4065..b899b5e1 100644 --- a/eo/src/omp_apply.h +++ b/eo/src/omp_apply.h @@ -40,7 +40,7 @@ template void omp_apply(eoUF& _proc, std::vector& _pop) { -#pragma omp parallel for default(none) shared(_proc, _pop) +#pragma omp parallel for default(none) shared(_proc, _pop) schedule(dynamic) for (unsigned i = 0; i < _pop.size(); ++i) { //#pragma omp critical diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index c4b88570..7cf7ac8e 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -39,8 +39,6 @@ int main(int ac, char** av) unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value(); - double threshold = parser.getORcreateParam((double)3.0, "threshold", "Threshold of max speedup", 0, "Evolution Engine").value(); - std::string speedupFileName = parser.getORcreateParam(std::string("speedup"), "speedupFileName", "Speedup file name", 0, "Results").value(); std::string efficiencyFileName = parser.getORcreateParam(std::string("efficiency"), "efficiencyFileName", "Efficiency file name", 0, "Results").value(); @@ -64,7 +62,7 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); std::ostringstream params; - params << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-t" << threshold << "-s" << seedParam; + params << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); @@ -107,10 +105,10 @@ int main(int ac, char** av) Tp = t2 - t1; } - if ( ( Ts / Tp ) > threshold ) { continue; } + if ( ( Ts / Tp ) > nbtask ) { continue; } speedupFile << Ts / Tp << ' '; - efficiencyFile << Ts / ( nbtask * Tp ); + efficiencyFile << Ts / ( nbtask * Tp ) << ' '; eo::log << eo::debug; eo::log << "Ts = " << Ts << std::endl; From c9843c3cfadb45654d9c4940ecd996b2a3b1c9ed Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 17:33:11 +0100 Subject: [PATCH 08/81] removed omp_apply.h and added to apply.h, added dynamicity computation --- eo/src/apply.h | 31 +++++++++++++++++++++++++++ eo/src/omp_apply.h | 51 -------------------------------------------- eo/test/t-openmp.cpp | 32 ++++++++++++++++++++++----- 3 files changed, 58 insertions(+), 56 deletions(-) delete mode 100644 eo/src/omp_apply.h diff --git a/eo/src/apply.h b/eo/src/apply.h index 0eb3484e..2cd977b0 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -43,4 +43,35 @@ void apply(eoUF& _proc, std::vector& _pop) } } +/** + This is a variant of apply which is called in parallel + thanks to OpenMP. + + @ingroup Utilities +*/ +template +void omp_apply(eoUF& _proc, std::vector& _pop) +{ +#pragma omp parallel for default(none) shared(_proc, _pop) + for (unsigned i = 0; i < _pop.size(); ++i) + { + _proc(_pop[i]); + } +} + +/** + And now we are using the dynamic scheduling. + + @ingroup Utilities +*/ +template +void omp_dynamic_apply(eoUF& _proc, std::vector& _pop) +{ +#pragma omp parallel for default(none) shared(_proc, _pop) schedule(dynamic) + for (unsigned i = 0; i < _pop.size(); ++i) + { + _proc(_pop[i]); + } +} + #endif diff --git a/eo/src/omp_apply.h b/eo/src/omp_apply.h deleted file mode 100644 index b899b5e1..00000000 --- a/eo/src/omp_apply.h +++ /dev/null @@ -1,51 +0,0 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoApply.h -// (c) Maarten Keijzer 2000 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - 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 - mak@dhi.dk - */ -//----------------------------------------------------------------------------- - -#ifndef _omp_apply_h -#define _omp_apply_h - -#include -#include - -/** - Applies a unary function to a std::vector of things. - - This is a variant of apply which is called in parallel - thanks to OpenMP. - - @ingroup Utilities -*/ -template -void omp_apply(eoUF& _proc, std::vector& _pop) -{ -#pragma omp parallel for default(none) shared(_proc, _pop) schedule(dynamic) - for (unsigned i = 0; i < _pop.size(); ++i) - { - //#pragma omp critical - _proc(_pop[i]); - } -} - -#endif diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 7cf7ac8e..c4e3ac03 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -41,6 +41,7 @@ int main(int ac, char** av) std::string speedupFileName = parser.getORcreateParam(std::string("speedup"), "speedupFileName", "Speedup file name", 0, "Results").value(); std::string efficiencyFileName = parser.getORcreateParam(std::string("efficiency"), "efficiencyFileName", "Efficiency file name", 0, "Results").value(); + std::string dynamicityFileName = parser.getORcreateParam(std::string("dynamicity"), "dynamicityFileName", "Dynamicity file name", 0, "Results").value(); uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); if (seedParam == 0) { seedParam = time(0); } @@ -65,6 +66,7 @@ int main(int ac, char** av) params << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); + std::ofstream dynamicityFile( std::string( dynamicityFileName + params.str() ).c_str() ); size_t nbtask = 1; #pragma omp parallel @@ -86,6 +88,7 @@ int main(int ac, char** av) double Ts; double Tp; + double Tpd; // sequential scope { @@ -105,20 +108,39 @@ int main(int ac, char** av) Tp = t2 - t1; } - if ( ( Ts / Tp ) > nbtask ) { continue; } + // parallel scope dynamic + { + eoPop< EOT > pop( p, init ); + double t1 = omp_get_wtime(); + omp_dynamic_apply< EOT >(eval, pop); + double t2 = omp_get_wtime(); + Tpd = t2 - t1; + } - speedupFile << Ts / Tp << ' '; - efficiencyFile << Ts / ( nbtask * Tp ) << ' '; + double speedup = Ts / Tp; + + if ( speedup > nbtask ) { continue; } + + double efficiency = speedup / nbtask; + + double dynamicity = Tp / Tpd; + + speedupFile << speedup << ' '; + efficiencyFile << efficiency << ' '; + dynamicityFile << dynamicity << ' '; eo::log << eo::debug; eo::log << "Ts = " << Ts << std::endl; eo::log << "Tp = " << Tp << std::endl; - eo::log << "S_p = " << Ts / Tp << std::endl; - eo::log << "E_p = " << Ts / ( nbtask * Tp ) << std::endl; + eo::log << "Tpd = " << Tpd << std::endl; + eo::log << "S_p = " << speedup << std::endl; + eo::log << "E_p = " << efficiency << std::endl; + eo::log << "D_p = " << dynamicity << std::endl; } // end of runs speedupFile << std::endl; efficiencyFile << std::endl; + dynamicityFile << std::endl; } // end of dimension From 849a5ec670cd0707abc7b4ca90592444d07b559d Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 17:35:06 +0100 Subject: [PATCH 09/81] created two boxplot script files one to generate image the other to display with matplotlab --- eo/test/CMakeLists.txt | 1 + eo/test/boxplot.py | 8 ++++---- eo/test/boxplot_to_png.py | 14 ++++++++++++++ eo/test/t-openmp.cpp | 1 - 4 files changed, 19 insertions(+), 5 deletions(-) create mode 100755 eo/test/boxplot_to_png.py diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index 8d7956ba..07dbee08 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -95,6 +95,7 @@ ELSEIF(ENABLE_CMAKE_TESTING) SET(RESOURCES boxplot.py + boxplot_to_png.py ) FOREACH(file ${RESOURCES}) diff --git a/eo/test/boxplot.py b/eo/test/boxplot.py index 2b5141af..39a65944 100755 --- a/eo/test/boxplot.py +++ b/eo/test/boxplot.py @@ -4,11 +4,11 @@ import pylab import sys if __name__ == '__main__': - if len(sys.argv) < 3: - print 'Usage: boxplot.py [Results files, ...] [output file in .png]' + if len(sys.argv) < 2: + print 'Usage: boxplot.py [Results files, ...]' sys.exit() - for i in range(1, len(sys.argv) - 1): + for i in range(1, len(sys.argv)): pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) - pylab.savefig( sys.argv[ len(sys.argv) - 1 ] ) + pylab.show() diff --git a/eo/test/boxplot_to_png.py b/eo/test/boxplot_to_png.py new file mode 100755 index 00000000..2b5141af --- /dev/null +++ b/eo/test/boxplot_to_png.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +import pylab +import sys + +if __name__ == '__main__': + if len(sys.argv) < 3: + print 'Usage: boxplot.py [Results files, ...] [output file in .png]' + sys.exit() + + for i in range(1, len(sys.argv) - 1): + pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) + + pylab.savefig( sys.argv[ len(sys.argv) - 1 ] ) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index c4e3ac03..f1ddffe8 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -13,7 +13,6 @@ #include #include -#include #include From 50d91c3ab6bf4aecc88834d3e74e47b7c2e19064 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 17:37:44 +0100 Subject: [PATCH 10/81] added popStep and dimStep value on the result filename --- eo/test/t-openmp.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index f1ddffe8..d7a418a5 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -62,7 +62,9 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); std::ostringstream params; - params << "-p" << popMin << "-P" << popMax << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; + params << "--popStep" << popStep << "-p" << popMin << "-P" << popMax + << "--dimStep" << dimStep << "-d" << dimMin << "-D" << dimMax + << "-r" << nRun << "-s" << seedParam; std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); std::ofstream dynamicityFile( std::string( dynamicityFileName + params.str() ).c_str() ); From bb0efdc0671f7bcff39d4b7326f9240ba2ce35f3 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 17:43:52 +0100 Subject: [PATCH 11/81] popStep and dimStep replaced by pS and dS on the results filename --- eo/test/t-openmp.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index d7a418a5..31aeeca0 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -62,8 +62,8 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); std::ostringstream params; - params << "--popStep" << popStep << "-p" << popMin << "-P" << popMax - << "--dimStep" << dimStep << "-d" << dimMin << "-D" << dimMax + params << "--pS" << popStep << "-p" << popMin << "-P" << popMax + << "--dS" << dimStep << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); From 4059e16b1e9db445872bd11cf2e2d62b5d5a4bcc Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 18:08:58 +0100 Subject: [PATCH 12/81] updated to D_p = T_Dp / T_p and avoid all D_p higher than the number of tasks used --- eo/test/t-openmp.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 31aeeca0..8b09bfad 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -124,19 +124,24 @@ int main(int ac, char** av) double efficiency = speedup / nbtask; - double dynamicity = Tp / Tpd; - speedupFile << speedup << ' '; efficiencyFile << efficiency << ' '; - dynamicityFile << dynamicity << ' '; eo::log << eo::debug; eo::log << "Ts = " << Ts << std::endl; eo::log << "Tp = " << Tp << std::endl; - eo::log << "Tpd = " << Tpd << std::endl; eo::log << "S_p = " << speedup << std::endl; eo::log << "E_p = " << efficiency << std::endl; + + double dynamicity = Tpd / Tp; + + if ( dynamicity > nbtask ) { continue; } + + eo::log << "Tpd = " << Tpd << std::endl; eo::log << "D_p = " << dynamicity << std::endl; + + dynamicityFile << dynamicity << ' '; + } // end of runs speedupFile << std::endl; From cfac1f8a7ea396fb4b2d64055763ec6ec5917633 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 18:20:38 +0100 Subject: [PATCH 13/81] remode two - on results filename --- eo/test/t-openmp.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 8b09bfad..97d5f969 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -62,8 +62,8 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); std::ostringstream params; - params << "--pS" << popStep << "-p" << popMin << "-P" << popMax - << "--dS" << dimStep << "-d" << dimMin << "-D" << dimMax + params << "-pS" << popStep << "-p" << popMin << "-P" << popMax + << "-dS" << dimStep << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); From 4a8efc6ca6ca90a7c97b36216d151ea0b84cf930 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Mon, 22 Nov 2010 19:16:09 +0100 Subject: [PATCH 14/81] updated Dp = Tp / TDp --- eo/test/t-openmp.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 97d5f969..932da257 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -133,7 +133,7 @@ int main(int ac, char** av) eo::log << "S_p = " << speedup << std::endl; eo::log << "E_p = " << efficiency << std::endl; - double dynamicity = Tpd / Tp; + double dynamicity = Tp / Tpd; if ( dynamicity > nbtask ) { continue; } From 69434a5bc2f1b7b10dbd46c7c7ca38d7da81230c Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 27 Nov 2010 16:19:51 +0100 Subject: [PATCH 15/81] added prefix parameter on t-openmp --- eo/test/t-openmp.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 932da257..cb21f445 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -38,6 +38,8 @@ int main(int ac, char** av) unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value(); + std::string fileNamesPrefix = parser.getORcreateParam(std::string("notitle"), "fileNamesPrefix", "Prefix of all results files name", 'H', "Results").value(); + std::string speedupFileName = parser.getORcreateParam(std::string("speedup"), "speedupFileName", "Speedup file name", 0, "Results").value(); std::string efficiencyFileName = parser.getORcreateParam(std::string("efficiency"), "efficiencyFileName", "Efficiency file name", 0, "Results").value(); std::string dynamicityFileName = parser.getORcreateParam(std::string("dynamicity"), "dynamicityFileName", "Dynamicity file name", 0, "Results").value(); @@ -65,9 +67,9 @@ int main(int ac, char** av) params << "-pS" << popStep << "-p" << popMin << "-P" << popMax << "-dS" << dimStep << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; - std::ofstream speedupFile( std::string( speedupFileName + params.str() ).c_str() ); - std::ofstream efficiencyFile( std::string( efficiencyFileName + params.str() ).c_str() ); - std::ofstream dynamicityFile( std::string( dynamicityFileName + params.str() ).c_str() ); + std::ofstream speedupFile( std::string( fileNamesPrefix + "_" + speedupFileName + params.str() ).c_str() ); + std::ofstream efficiencyFile( std::string( fileNamesPrefix + "_" + efficiencyFileName + params.str() ).c_str() ); + std::ofstream dynamicityFile( std::string( fileNamesPrefix + "_" + dynamicityFileName + params.str() ).c_str() ); size_t nbtask = 1; #pragma omp parallel From 2141719076021c89407a7b3520312d61c1fe6316 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 27 Nov 2010 21:24:07 +0100 Subject: [PATCH 16/81] added t-openmp.py --- eo/test/CMakeLists.txt | 2 + eo/test/boxplot.py | 1 + eo/test/boxplot_to_pdf.py | 15 +++++++ eo/test/boxplot_to_png.py | 5 ++- eo/test/t-openmp.cpp | 8 ++-- eo/test/t-openmp.py | 91 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 116 insertions(+), 6 deletions(-) create mode 100755 eo/test/boxplot_to_pdf.py create mode 100755 eo/test/t-openmp.py diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index 07dbee08..22006350 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -96,6 +96,8 @@ ELSEIF(ENABLE_CMAKE_TESTING) SET(RESOURCES boxplot.py boxplot_to_png.py + boxplot_to_pdf.py + t-openmp.py ) FOREACH(file ${RESOURCES}) diff --git a/eo/test/boxplot.py b/eo/test/boxplot.py index 39a65944..bf6e84b5 100755 --- a/eo/test/boxplot.py +++ b/eo/test/boxplot.py @@ -11,4 +11,5 @@ if __name__ == '__main__': for i in range(1, len(sys.argv)): pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) + pylab.xlabel('iterations') pylab.show() diff --git a/eo/test/boxplot_to_pdf.py b/eo/test/boxplot_to_pdf.py new file mode 100755 index 00000000..f29edeb2 --- /dev/null +++ b/eo/test/boxplot_to_pdf.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python + +import pylab +import sys + +if __name__ == '__main__': + if len(sys.argv) < 3: + print 'Usage: boxplot_to_pdf.py [Results files, ...] [output file in .pdf]' + sys.exit() + + for i in range(1, len(sys.argv) - 1): + pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) + + pylab.xlabel('iterations') + pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='pdf', transparent=True ) diff --git a/eo/test/boxplot_to_png.py b/eo/test/boxplot_to_png.py index 2b5141af..17fb35bc 100755 --- a/eo/test/boxplot_to_png.py +++ b/eo/test/boxplot_to_png.py @@ -5,10 +5,11 @@ import sys if __name__ == '__main__': if len(sys.argv) < 3: - print 'Usage: boxplot.py [Results files, ...] [output file in .png]' + print 'Usage: boxplot_to_png.py [Results files, ...] [output file in .png]' sys.exit() for i in range(1, len(sys.argv) - 1): pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) - pylab.savefig( sys.argv[ len(sys.argv) - 1 ] ) + pylab.xlabel('iterations') + pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='png', transparent=True, papertype='a0' ) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index cb21f445..297662b6 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -38,7 +38,7 @@ int main(int ac, char** av) unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value(); - std::string fileNamesPrefix = parser.getORcreateParam(std::string("notitle"), "fileNamesPrefix", "Prefix of all results files name", 'H', "Results").value(); + std::string fileNamesPrefix = parser.getORcreateParam(std::string(""), "fileNamesPrefix", "Prefix of all results files name", 'H', "Results").value(); std::string speedupFileName = parser.getORcreateParam(std::string("speedup"), "speedupFileName", "Speedup file name", 0, "Results").value(); std::string efficiencyFileName = parser.getORcreateParam(std::string("efficiency"), "efficiencyFileName", "Efficiency file name", 0, "Results").value(); @@ -67,9 +67,9 @@ int main(int ac, char** av) params << "-pS" << popStep << "-p" << popMin << "-P" << popMax << "-dS" << dimStep << "-d" << dimMin << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; - std::ofstream speedupFile( std::string( fileNamesPrefix + "_" + speedupFileName + params.str() ).c_str() ); - std::ofstream efficiencyFile( std::string( fileNamesPrefix + "_" + efficiencyFileName + params.str() ).c_str() ); - std::ofstream dynamicityFile( std::string( fileNamesPrefix + "_" + dynamicityFileName + params.str() ).c_str() ); + std::ofstream speedupFile( std::string( fileNamesPrefix + speedupFileName + params.str() ).c_str() ); + std::ofstream efficiencyFile( std::string( fileNamesPrefix + efficiencyFileName + params.str() ).c_str() ); + std::ofstream dynamicityFile( std::string( fileNamesPrefix + dynamicityFileName + params.str() ).c_str() ); size_t nbtask = 1; #pragma omp parallel diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py new file mode 100755 index 00000000..3982d682 --- /dev/null +++ b/eo/test/t-openmp.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python + +import pylab +import optparse, logging, sys, os +from datetime import datetime + +LEVELS = {'debug': logging.DEBUG, + 'info': logging.INFO, + 'warning': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL} + +LOG_DEFAULT_FILENAME='notitle.log' + +OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s' + +def parser(parser=optparse.OptionParser()): + # general parameters + parser.add_option('-v', '--verbose', choices=LEVELS.keys(), default='warning', help='set a verbose level') + parser.add_option('-f', '--file', help='give an input project filename', default='') + parser.add_option('-o', '--output', help='give an output filename for logging', default=LOG_DEFAULT_FILENAME) + # general parameters ends + + parser.add_option('-p', '--popMin', default=1) + parser.add_option('', '--popStep', default=1) + parser.add_option('-P', '--popMax', default=100) + parser.add_option('-d', '--dimMin', default=1) + parser.add_option('', '--dimStep', default=1) + parser.add_option('-D', '--dimMax', default=100) + parser.add_option('-r', '--nRun', default=100) + parser.add_option('-s', '--seed', default=-1) + + topic = str(datetime.today()) + for char in [' ', ':', '-', '.']: topic = topic.replace(char, '_') + parser.add_option('-t', '--topic', default='openmp_' + topic + '/') + + options, args = parser.parse_args() + + logger(options.verbose, options.output) + + return options + +def logger(level_name, filename=LOG_DEFAULT_FILENAME): + logging.basicConfig( + level=logging.DEBUG, + format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', + filename=filename, filemode='a' + ) + + console = logging.StreamHandler() + console.setLevel(LEVELS.get(level_name, logging.NOTSET)) + console.setFormatter(logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')) + logging.getLogger('').addHandler(console) + +options = parser() + +def execute_openmp( p, ps, P, d, ds, D, r, s, v=options.verbose ): + cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, options.topic) + logging.debug( cmd ) + #os.system( cmd ) + +def main(): + # creates first the new topic repository + #os.mkdir( options.topic ) + + # (1) EA in time O(1) + + # (1.1) speedup measure Sp, Ep for P & D + + # (1.1.1) measure for all combinaisons of P n D + execute_openmp( 1, 10, 100, 1, 10, 100, 100, options.seed ) + + # (1.1.1) measure for all combinaisons of P n D + execute_openmp( 1, 10, 100, 1, 10, 100, 100, options.seed ) + + + # pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) + + # pylab.xlabel('iterations') + # pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='pdf', transparent=True ) + + # (2) EA in time O(1) + + +# when executed, just run main(): +if __name__ == '__main__': + logging.debug('### plotting started ###') + + main() + + logging.debug('### plotting ended ###') From 9dcbb94ffbce37cec79e3eb1d0efc192ed7f332a Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 27 Nov 2010 21:27:41 +0100 Subject: [PATCH 17/81] changed output results name --- eo/test/t-openmp.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 297662b6..db6b4cfc 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -64,8 +64,8 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); std::ostringstream params; - params << "-pS" << popStep << "-p" << popMin << "-P" << popMax - << "-dS" << dimStep << "-d" << dimMin << "-D" << dimMax + params << "-p" << popMin << "-pS" << popStep << "-P" << popMax + << "-d" << dimMin << "-dS" << dimStep << "-D" << dimMax << "-r" << nRun << "-s" << seedParam; std::ofstream speedupFile( std::string( fileNamesPrefix + speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( fileNamesPrefix + efficiencyFileName + params.str() ).c_str() ); From 20fd5b206f446cd69c2df729bac5c158e847d2d1 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 27 Nov 2010 23:07:11 +0100 Subject: [PATCH 18/81] t-openmp.py released --- eo/test/t-openmp.cpp | 6 ++-- eo/test/t-openmp.py | 69 +++++++++++++++++++++++++++----------------- 2 files changed, 46 insertions(+), 29 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index db6b4cfc..4771c541 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -64,9 +64,9 @@ int main(int ac, char** av) eoUniformGenerator< double > gen(-5, 5); std::ostringstream params; - params << "-p" << popMin << "-pS" << popStep << "-P" << popMax - << "-d" << dimMin << "-dS" << dimStep << "-D" << dimMax - << "-r" << nRun << "-s" << seedParam; + params << "_p" << popMin << "_pS" << popStep << "_P" << popMax + << "_d" << dimMin << "_dS" << dimStep << "_D" << dimMax + << "_r" << nRun << "_s" << seedParam; std::ofstream speedupFile( std::string( fileNamesPrefix + speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( fileNamesPrefix + efficiencyFileName + params.str() ).c_str() ); std::ofstream dynamicityFile( std::string( fileNamesPrefix + dynamicityFileName + params.str() ).c_str() ); diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 3982d682..2b7c6842 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -14,25 +14,21 @@ LOG_DEFAULT_FILENAME='notitle.log' OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s' +RESULT_FILE_FORMAT='%s%s_p%d_pS%d_P%d_d%d_dS%d_D%d_r%d_s%d' + def parser(parser=optparse.OptionParser()): # general parameters - parser.add_option('-v', '--verbose', choices=LEVELS.keys(), default='warning', help='set a verbose level') + parser.add_option('-v', '--verbose', choices=LEVELS.keys(), default='info', help='set a verbose level') parser.add_option('-f', '--file', help='give an input project filename', default='') parser.add_option('-o', '--output', help='give an output filename for logging', default=LOG_DEFAULT_FILENAME) # general parameters ends - parser.add_option('-p', '--popMin', default=1) - parser.add_option('', '--popStep', default=1) - parser.add_option('-P', '--popMax', default=100) - parser.add_option('-d', '--dimMin', default=1) - parser.add_option('', '--dimStep', default=1) - parser.add_option('-D', '--dimMax', default=100) parser.add_option('-r', '--nRun', default=100) - parser.add_option('-s', '--seed', default=-1) + parser.add_option('-s', '--seed', default=1) topic = str(datetime.today()) for char in [' ', ':', '-', '.']: topic = topic.replace(char, '_') - parser.add_option('-t', '--topic', default='openmp_' + topic + '/') + parser.add_option('-t', '--topic', default='openmp_measures_' + topic + '/') options, args = parser.parse_args() @@ -54,33 +50,54 @@ def logger(level_name, filename=LOG_DEFAULT_FILENAME): options = parser() -def execute_openmp( p, ps, P, d, ds, D, r, s, v=options.verbose ): - cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, options.topic) +def get_boxplot_data( filename ): + try: + f = open( filename ) + return [ [ float(value) for value in line.split() ] for line in f.readlines() ] + except: + raise ValueError('got an issue during the reading of file %s' % filename) + +def non_zero( value ): return value if value > 0 else 1 + +def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='logging' ): + pwd = options.topic + name + '_' + cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd) logging.debug( cmd ) - #os.system( cmd ) + os.system( cmd ) + + for cur in ['speedup', 'efficiency', 'dynamicity']: + filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s) + pylab.boxplot( get_boxplot_data( filename ) ) + iters = ( non_zero( P - p ) / ps ) * ( non_zero( D - d ) / ds ) + pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) + pylab.ylabel('%s - %s' % (cur, name)) + pylab.savefig( filename + '.pdf', format='pdf' ) + pylab.savefig( filename + '.png', format='png' ) + pylab.cla() + pylab.clf() def main(): - # creates first the new topic repository - #os.mkdir( options.topic ) + logging.info('creates first the new topic repository %s', options.topic) + os.mkdir( options.topic ) - # (1) EA in time O(1) + logging.info('do all tests with r = %d and a common seed value = %d' % (options.nRun, options.seed)) - # (1.1) speedup measure Sp, Ep for P & D + logging.info('EA in time O(1) and O(n) - speedup measure Sp, Ep and Dp for P & D') - # (1.1.1) measure for all combinaisons of P n D - execute_openmp( 1, 10, 100, 1, 10, 100, 100, options.seed ) + logging.info('(1) measure for all combinaisons of P n D') + do_measure( '1', 1, 10, 101, 1, 10, 101 ) - # (1.1.1) measure for all combinaisons of P n D - execute_openmp( 1, 10, 100, 1, 10, 100, 100, options.seed ) + logging.info('(2) measure for P \in [1, 100[ with D fixed to 1000') + do_measure( '2', 1, 1, 101, 1000, 1, 1000 ) + logging.info('(3) measure for P \in [1, 1000[ with ps = 10 and D fixed to 1000') + do_measure( '3', 1, 10, 1001, 1000, 1, 1000 ) - # pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) - - # pylab.xlabel('iterations') - # pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='pdf', transparent=True ) - - # (2) EA in time O(1) + logging.info('(4) measure for D \in [1, 100[ with P fixed to 1000') + do_measure( '4', 1000, 1, 1000, 1, 1, 101 ) + logging.info('(5) measure for D \in [1, 1000[ with ds = 10 and P fixed to 1000') + do_measure( '5', 1000, 1, 1000, 1, 10, 1001 ) # when executed, just run main(): if __name__ == '__main__': From 6907b262e1d96f0513c7eae2f0787b0228ac3a85 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 27 Nov 2010 23:22:54 +0100 Subject: [PATCH 19/81] onlyexec and onlyprint parameters added on openmp script --- eo/test/t-openmp.py | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 2b7c6842..aa3af686 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -23,12 +23,15 @@ def parser(parser=optparse.OptionParser()): parser.add_option('-o', '--output', help='give an output filename for logging', default=LOG_DEFAULT_FILENAME) # general parameters ends - parser.add_option('-r', '--nRun', default=100) - parser.add_option('-s', '--seed', default=1) + parser.add_option('-r', '--nRun', default=100, help='how many times you would compute each iteration ?') + parser.add_option('-s', '--seed', default=1, help='give here a seed value') topic = str(datetime.today()) for char in [' ', ':', '-', '.']: topic = topic.replace(char, '_') - parser.add_option('-t', '--topic', default='openmp_measures_' + topic + '/') + parser.add_option('-t', '--topic', default='openmp_measures_' + topic + '/', help='give here a topic name used to create the folder') + + parser.add_option('-E', '--onlyexecute', action='store_true', dest='onlyexecute', default=False, help='used this option if you only want to execute measures without generating images') + parser.add_option('-X', '--onlyprint', action='store_true', dest='onlyprint', default=False, help='used this option if you only want to generate images without executing measures, dont forget to set the good path in using --topic with a "/" at the end') options, args = parser.parse_args() @@ -63,22 +66,25 @@ def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='log pwd = options.topic + name + '_' cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd) logging.debug( cmd ) - os.system( cmd ) + if not options.onlyprint: + os.system( cmd ) - for cur in ['speedup', 'efficiency', 'dynamicity']: - filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s) - pylab.boxplot( get_boxplot_data( filename ) ) - iters = ( non_zero( P - p ) / ps ) * ( non_zero( D - d ) / ds ) - pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) - pylab.ylabel('%s - %s' % (cur, name)) - pylab.savefig( filename + '.pdf', format='pdf' ) - pylab.savefig( filename + '.png', format='png' ) - pylab.cla() - pylab.clf() + if not options.onlyexecute: + for cur in ['speedup', 'efficiency', 'dynamicity']: + filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s) + pylab.boxplot( get_boxplot_data( filename ) ) + iters = ( non_zero( P - p ) / ps ) * ( non_zero( D - d ) / ds ) + pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) + pylab.ylabel('%s - %s' % (cur, name)) + pylab.savefig( filename + '.pdf', format='pdf' ) + pylab.savefig( filename + '.png', format='png' ) + pylab.cla() + pylab.clf() def main(): - logging.info('creates first the new topic repository %s', options.topic) - os.mkdir( options.topic ) + if not options.onlyprint: + logging.info('creates first the new topic repository %s', options.topic) + os.mkdir( options.topic ) logging.info('do all tests with r = %d and a common seed value = %d' % (options.nRun, options.seed)) From bb2934fd09d9baeae476804599f4cc871d40c028 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sat, 27 Nov 2010 23:26:16 +0100 Subject: [PATCH 20/81] onlyexec and onlyprint parameters added on openmp script --- eo/test/t-openmp.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index aa3af686..54338a44 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -1,6 +1,5 @@ #!/usr/bin/env python -import pylab import optparse, logging, sys, os from datetime import datetime @@ -53,6 +52,9 @@ def logger(level_name, filename=LOG_DEFAULT_FILENAME): options = parser() +if not options.onlyexecute: + import pylab + def get_boxplot_data( filename ): try: f = open( filename ) From 1aa9db18f3c13a70bfd0a67050946de6ae152bdd Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 00:12:08 +0100 Subject: [PATCH 21/81] added n processus and fixed bound parameters --- eo/test/t-openmp.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 54338a44..2f7ac80f 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -24,6 +24,8 @@ def parser(parser=optparse.OptionParser()): parser.add_option('-r', '--nRun', default=100, help='how many times you would compute each iteration ?') parser.add_option('-s', '--seed', default=1, help='give here a seed value') + parser.add_option('-n', '--nProc', default=1, help='give a number of processus, this value is multiplied by the measures bounds') + parser.add_option('-F', '--fixedBound', default=1000, help='give the fixed bound value common for all measures') topic = str(datetime.today()) for char in [' ', ':', '-', '.']: topic = topic.replace(char, '_') @@ -92,20 +94,23 @@ def main(): logging.info('EA in time O(1) and O(n) - speedup measure Sp, Ep and Dp for P & D') + n = options.nProc + F = options.fixedBound + logging.info('(1) measure for all combinaisons of P n D') - do_measure( '1', 1, 10, 101, 1, 10, 101 ) + do_measure( '1', 1*n, 10*n, 101*n, 1*n, 10*n, 101*n ) - logging.info('(2) measure for P \in [1, 100[ with D fixed to 1000') - do_measure( '2', 1, 1, 101, 1000, 1, 1000 ) + logging.info('(2) measure for P \in [%d, %d[ with D fixed to %d' % (1*n, 101*n, F)) + do_measure( '2', 1*n, 1*n, 101*n, F, 1, F ) - logging.info('(3) measure for P \in [1, 1000[ with ps = 10 and D fixed to 1000') - do_measure( '3', 1, 10, 1001, 1000, 1, 1000 ) + logging.info('(3) measure for P \in [%d, %d[ with ps = %d and D fixed to %d' % (1*n, 1001*n, 10*n, F)) + do_measure( '3', 1*n, 10*n, 1001*n, F, 1, F ) - logging.info('(4) measure for D \in [1, 100[ with P fixed to 1000') - do_measure( '4', 1000, 1, 1000, 1, 1, 101 ) + logging.info('(4) measure for D \in [%d, %d[ with P fixed to %d' % (1*n, 101*n, F)) + do_measure( '4', F, 1, F, 1*n, 1*n, 101*n ) - logging.info('(5) measure for D \in [1, 1000[ with ds = 10 and P fixed to 1000') - do_measure( '5', 1000, 1, 1000, 1, 10, 1001 ) + logging.info('(5) measure for D \in [%d, %d[ with ds = %d and P fixed to %d' % (1*n, 1001*n, 10*n, F)) + do_measure( '5', F, 1, F, 1*n, 10*n, 1001*n ) # when executed, just run main(): if __name__ == '__main__': From c7a34a6a5ef2b857361c59914700430c20060cea Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 00:19:46 +0100 Subject: [PATCH 22/81] added n processus and fixed bound parameters --- eo/test/t-openmp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 2f7ac80f..330fe666 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -94,7 +94,7 @@ def main(): logging.info('EA in time O(1) and O(n) - speedup measure Sp, Ep and Dp for P & D') - n = options.nProc + n = int(options.nProc) F = options.fixedBound logging.info('(1) measure for all combinaisons of P n D') From d6b566b538651508b8ac4ea1edc3c967af80a68e Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 03:24:02 +0100 Subject: [PATCH 23/81] added variable time measure --- eo/test/t-openmp.cpp | 141 ++++++++++++++++++++++++++----------------- 1 file changed, 86 insertions(+), 55 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 4771c541..10c73ce0 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -24,6 +24,66 @@ typedef eoReal< eoMinimizingFitness > EOT; //----------------------------------------------------------------------------- +double variable_time_function(const std::vector&) +{ + ::srand( ::time( NULL ) ); + ::usleep( 10 * ( rand() / RAND_MAX ) ); + return 0.0; +} + +double measure_apply( size_t p, + void (*fct)(eoUF&, std::vector&), + eoInitFixedLength< EOT >& init, + eoEvalFuncCounter< EOT >& eval ) +{ + eoPop< EOT > pop( p, init ); + double t1 = omp_get_wtime(); + fct( eval, pop ); + double t2 = omp_get_wtime(); + return t2 - t1; +} + +void measure( size_t p, + eoInitFixedLength< EOT >& init, + eoEvalFuncCounter< EOT >& eval, + std::ofstream& speedupFile, + std::ofstream& efficiencyFile, + std::ofstream& dynamicityFile, + size_t nbtask ) +{ + // sequential scope + double Ts = measure_apply( p, apply< EOT >, init, eval ); + // parallel scope + double Tp = measure_apply( p, omp_apply< EOT >, init, eval ); + // parallel scope dynamic + double Tpd = measure_apply( p, omp_dynamic_apply< EOT >, init, eval ); + + double speedup = Ts / Tp; + + if ( speedup > nbtask ) { return; } + + double efficiency = speedup / nbtask; + + speedupFile << speedup << ' '; + efficiencyFile << efficiency << ' '; + + eo::log << eo::debug; + eo::log << "Ts = " << Ts << std::endl; + eo::log << "Tp = " << Tp << std::endl; + eo::log << "S_p = " << speedup << std::endl; + eo::log << "E_p = " << efficiency << std::endl; + + double dynamicity = Tp / Tpd; + + if ( dynamicity > nbtask ) { return; } + + eo::log << "Tpd = " << Tpd << std::endl; + eo::log << "D_p = " << dynamicity << std::endl; + + dynamicityFile << dynamicity << ' '; +} + + int main(int ac, char** av) { eoParserLogger parser(ac, av); @@ -47,6 +107,9 @@ int main(int ac, char** av) uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); if (seedParam == 0) { seedParam = time(0); } + unsigned int measureConstTime = parser.getORcreateParam((unsigned int)1, "measureConstTime", "Toggle measure of constant time", 'm', "Results").value(); + unsigned int measureVarTime = parser.getORcreateParam((unsigned int)1, "measureVarTime", "Toggle measure of variable time", 'M', "Results").value(); + if (parser.userNeedsHelp()) { parser.printHelp(std::cout); @@ -59,7 +122,10 @@ int main(int ac, char** av) rng.reseed( seedParam ); eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); - eoEvalFuncCounter eval( mainEval ); + eoEvalFuncCounter< EOT > eval( mainEval ); + + eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval_variable( variable_time_function ); + eoEvalFuncCounter< EOT > eval_variable( mainEval_variable ); eoUniformGenerator< double > gen(-5, 5); @@ -67,10 +133,15 @@ int main(int ac, char** av) params << "_p" << popMin << "_pS" << popStep << "_P" << popMax << "_d" << dimMin << "_dS" << dimStep << "_D" << dimMax << "_r" << nRun << "_s" << seedParam; + std::ofstream speedupFile( std::string( fileNamesPrefix + speedupFileName + params.str() ).c_str() ); std::ofstream efficiencyFile( std::string( fileNamesPrefix + efficiencyFileName + params.str() ).c_str() ); std::ofstream dynamicityFile( std::string( fileNamesPrefix + dynamicityFileName + params.str() ).c_str() ); + std::ofstream speedupFile_variable( std::string( fileNamesPrefix + "variable_" + speedupFileName + params.str() ).c_str() ); + std::ofstream efficiencyFile_variable( std::string( fileNamesPrefix + "variable_" + efficiencyFileName + params.str() ).c_str() ); + std::ofstream dynamicityFile_variable( std::string( fileNamesPrefix + "variable_" + dynamicityFileName + params.str() ).c_str() ); + size_t nbtask = 1; #pragma omp parallel { @@ -89,67 +160,27 @@ int main(int ac, char** av) { eoInitFixedLength< EOT > init( d, gen ); - double Ts; - double Tp; - double Tpd; - - // sequential scope - { - eoPop< EOT > pop( p, init ); - double t1 = omp_get_wtime(); - apply< EOT >(eval, pop); - double t2 = omp_get_wtime(); - Ts = t2 - t1; - } - - // parallel scope - { - eoPop< EOT > pop( p, init ); - double t1 = omp_get_wtime(); - omp_apply< EOT >(eval, pop); - double t2 = omp_get_wtime(); - Tp = t2 - t1; - } - - // parallel scope dynamic - { - eoPop< EOT > pop( p, init ); - double t1 = omp_get_wtime(); - omp_dynamic_apply< EOT >(eval, pop); - double t2 = omp_get_wtime(); - Tpd = t2 - t1; - } - - double speedup = Ts / Tp; - - if ( speedup > nbtask ) { continue; } - - double efficiency = speedup / nbtask; - - speedupFile << speedup << ' '; - efficiencyFile << efficiency << ' '; - - eo::log << eo::debug; - eo::log << "Ts = " << Ts << std::endl; - eo::log << "Tp = " << Tp << std::endl; - eo::log << "S_p = " << speedup << std::endl; - eo::log << "E_p = " << efficiency << std::endl; - - double dynamicity = Tp / Tpd; - - if ( dynamicity > nbtask ) { continue; } - - eo::log << "Tpd = " << Tpd << std::endl; - eo::log << "D_p = " << dynamicity << std::endl; - - dynamicityFile << dynamicity << ' '; + // for constant time measure + if ( measureConstTime == 1 ) + { + measure( p, init, eval, speedupFile, efficiencyFile, dynamicityFile, nbtask ); + } + // for variable time measure + if ( measureVarTime == 1 ) + { + measure( p, init, eval_variable, speedupFile_variable, efficiencyFile_variable, dynamicityFile_variable, nbtask ); + } } // end of runs speedupFile << std::endl; efficiencyFile << std::endl; dynamicityFile << std::endl; + speedupFile_variable << std::endl; + efficiencyFile_variable << std::endl; + dynamicityFile_variable << std::endl; + } // end of dimension } // end of population From 13bb5efa43c31de2818c85845e255d6e3c12acd6 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 03:32:53 +0100 Subject: [PATCH 24/81] added variable time measure --- eo/test/t-openmp.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 330fe666..0fb091f5 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -11,7 +11,7 @@ LEVELS = {'debug': logging.DEBUG, LOG_DEFAULT_FILENAME='notitle.log' -OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s' +OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s -m=%d -M=%d' RESULT_FILE_FORMAT='%s%s_p%d_pS%d_P%d_d%d_dS%d_D%d_r%d_s%d' @@ -34,6 +34,9 @@ def parser(parser=optparse.OptionParser()): parser.add_option('-E', '--onlyexecute', action='store_true', dest='onlyexecute', default=False, help='used this option if you only want to execute measures without generating images') parser.add_option('-X', '--onlyprint', action='store_true', dest='onlyprint', default=False, help='used this option if you only want to generate images without executing measures, dont forget to set the good path in using --topic with a "/" at the end') + parser.add_option('-m', '--measureConstTime', default=1, help='Toggle measure of constant time') + parser.add_option('-M', '--measureVarTime', default=1, help='Toggle measure of variable time') + options, args = parser.parse_args() logger(options.verbose, options.output) @@ -68,7 +71,7 @@ def non_zero( value ): return value if value > 0 else 1 def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='logging' ): pwd = options.topic + name + '_' - cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd) + cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd, options.measureConstTime, options.measureVarTime) logging.debug( cmd ) if not options.onlyprint: os.system( cmd ) From a7024e784c7520fce4ea901e6ea3bf8f54010bfd Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 03:35:21 +0100 Subject: [PATCH 25/81] added variable time measure --- eo/test/t-openmp.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 0fb091f5..c9f104be 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -71,7 +71,8 @@ def non_zero( value ): return value if value > 0 else 1 def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='logging' ): pwd = options.topic + name + '_' - cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd, options.measureConstTime, options.measureVarTime) + cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd, + int(options.measureConstTime), int(options.measureVarTime)) logging.debug( cmd ) if not options.onlyprint: os.system( cmd ) From 61ab540d8a96d32f0c9a76b02daf8e822cdf7907 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 03:41:09 +0100 Subject: [PATCH 26/81] update --- eo/test/t-openmp.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 10c73ce0..54d2e710 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -173,13 +173,19 @@ int main(int ac, char** av) } } // end of runs - speedupFile << std::endl; - efficiencyFile << std::endl; - dynamicityFile << std::endl; + if ( measureConstTime == 1 ) + { + speedupFile << std::endl; + efficiencyFile << std::endl; + dynamicityFile << std::endl; + } - speedupFile_variable << std::endl; - efficiencyFile_variable << std::endl; - dynamicityFile_variable << std::endl; + if ( measureVarTime == 1 ) + { + speedupFile_variable << std::endl; + efficiencyFile_variable << std::endl; + dynamicityFile_variable << std::endl; + } } // end of dimension From e3c3d156283a462eb8fa4cb4c7ec1f4e999ef527 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 13:36:25 +0100 Subject: [PATCH 27/81] using rdtsc for rng seed with mersenne twister --- eo/test/t-openmp.cpp | 6 ++++-- eo/test/t-openmp.py | 32 +++++++++++++++++++------------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 54d2e710..69e9022e 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -24,10 +24,12 @@ typedef eoReal< eoMinimizingFitness > EOT; //----------------------------------------------------------------------------- +inline uint32_t get_rdtsc() { __asm__ ("xor %eax, %eax; cpuid; rdtsc"); } + double variable_time_function(const std::vector&) { - ::srand( ::time( NULL ) ); - ::usleep( 10 * ( rand() / RAND_MAX ) ); + eoRng myrng( get_rdtsc() ); + ::usleep( myrng.random( 10 ) ); return 0.0; } diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index c9f104be..1b166ae6 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -67,27 +67,33 @@ def get_boxplot_data( filename ): except: raise ValueError('got an issue during the reading of file %s' % filename) -def non_zero( value ): return value if value > 0 else 1 - def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='logging' ): pwd = options.topic + name + '_' cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd, - int(options.measureConstTime), int(options.measureVarTime)) + int(options.measureConstTime), + int(options.measureVarTime)) logging.debug( cmd ) if not options.onlyprint: os.system( cmd ) if not options.onlyexecute: - for cur in ['speedup', 'efficiency', 'dynamicity']: - filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s) - pylab.boxplot( get_boxplot_data( filename ) ) - iters = ( non_zero( P - p ) / ps ) * ( non_zero( D - d ) / ds ) - pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) - pylab.ylabel('%s - %s' % (cur, name)) - pylab.savefig( filename + '.pdf', format='pdf' ) - pylab.savefig( filename + '.png', format='png' ) - pylab.cla() - pylab.clf() + def generate( filenames ): + for cur in filenames: + filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s) + pylab.boxplot( get_boxplot_data( filename ) ) + nonzero = lambda x: x if x > 0 else 1 + iters = ( nonzero( P - p ) / ps ) * ( nonzero( D - d ) / ds ) + pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) + pylab.ylabel('%s - %s' % (cur, name)) + pylab.savefig( filename + '.pdf', format='pdf' ) + pylab.savefig( filename + '.png', format='png' ) + pylab.cla() + pylab.clf() + + if int(options.measureConstTime) == 1: + generate( ['speedup', 'efficiency', 'dynamicity'] ) + if int(options.measureVarTime) == 1: + generate( ['variable_speedup', 'variable_efficiency', 'variable_dynamicity'] ) def main(): if not options.onlyprint: From 16a77fadd956d24acda56f77de477e8f4568fcde Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 28 Nov 2010 14:21:26 +0100 Subject: [PATCH 28/81] now we can select which measures we want --- eo/test/t-openmp.cpp | 4 +-- eo/test/t-openmp.py | 59 +++++++++++++++++++++++++------------------- 2 files changed, 35 insertions(+), 28 deletions(-) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 69e9022e..325cb653 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -109,8 +109,8 @@ int main(int ac, char** av) uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); if (seedParam == 0) { seedParam = time(0); } - unsigned int measureConstTime = parser.getORcreateParam((unsigned int)1, "measureConstTime", "Toggle measure of constant time", 'm', "Results").value(); - unsigned int measureVarTime = parser.getORcreateParam((unsigned int)1, "measureVarTime", "Toggle measure of variable time", 'M', "Results").value(); + unsigned int measureConstTime = parser.getORcreateParam((unsigned int)1, "measureConstTime", "Toggle measure of constant time", 'C', "Results").value(); + unsigned int measureVarTime = parser.getORcreateParam((unsigned int)1, "measureVarTime", "Toggle measure of variable time", 'V', "Results").value(); if (parser.userNeedsHelp()) { diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index 1b166ae6..ab43bb93 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -11,8 +11,6 @@ LEVELS = {'debug': logging.DEBUG, LOG_DEFAULT_FILENAME='notitle.log' -OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s -m=%d -M=%d' - RESULT_FILE_FORMAT='%s%s_p%d_pS%d_P%d_d%d_dS%d_D%d_r%d_s%d' def parser(parser=optparse.OptionParser()): @@ -22,20 +20,22 @@ def parser(parser=optparse.OptionParser()): parser.add_option('-o', '--output', help='give an output filename for logging', default=LOG_DEFAULT_FILENAME) # general parameters ends - parser.add_option('-r', '--nRun', default=100, help='how many times you would compute each iteration ?') - parser.add_option('-s', '--seed', default=1, help='give here a seed value') - parser.add_option('-n', '--nProc', default=1, help='give a number of processus, this value is multiplied by the measures bounds') - parser.add_option('-F', '--fixedBound', default=1000, help='give the fixed bound value common for all measures') + parser.add_option('-r', '--nRun', type='int', default=100, help='how many times you would compute each iteration ?') + parser.add_option('-s', '--seed', type='int', default=1, help='give here a seed value') + parser.add_option('-n', '--nProc', type='int', default=1, help='give a number of processus, this value is multiplied by the measures bounds') + parser.add_option('-F', '--fixedBound', type='int', default=1000, help='give the fixed bound value common for all measures') topic = str(datetime.today()) for char in [' ', ':', '-', '.']: topic = topic.replace(char, '_') parser.add_option('-t', '--topic', default='openmp_measures_' + topic + '/', help='give here a topic name used to create the folder') - parser.add_option('-E', '--onlyexecute', action='store_true', dest='onlyexecute', default=False, help='used this option if you only want to execute measures without generating images') - parser.add_option('-X', '--onlyprint', action='store_true', dest='onlyprint', default=False, help='used this option if you only want to generate images without executing measures, dont forget to set the good path in using --topic with a "/" at the end') + parser.add_option('-E', '--onlyexecute', action='store_true', default=False, help='used this option if you only want to execute measures without generating images') + parser.add_option('-X', '--onlyprint', action='store_true', default=False, help='used this option if you only want to generate images without executing measures, dont forget to set the good path in using --topic with a "/" at the end') - parser.add_option('-m', '--measureConstTime', default=1, help='Toggle measure of constant time') - parser.add_option('-M', '--measureVarTime', default=1, help='Toggle measure of variable time') + parser.add_option('-C', '--onlyConstTime', action='store_true', default=False, help='only measures constant time problem') + parser.add_option('-V', '--onlyVarTime', action='store_true', default=False, help='only measures variable time problem') + + parser.add_option('-m', '--measure', action='append', type='int', help='select all measure you want to produce, by default all are produced') options, args = parser.parse_args() @@ -68,11 +68,13 @@ def get_boxplot_data( filename ): raise ValueError('got an issue during the reading of file %s' % filename) def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='logging' ): + OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s -C=%d -V=%d' + pwd = options.topic + name + '_' cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd, - int(options.measureConstTime), - int(options.measureVarTime)) - logging.debug( cmd ) + 0 if options.onlyVarTime else 1, + 0 if options.onlyConstTime else 1) + logging.info( cmd ) if not options.onlyprint: os.system( cmd ) @@ -90,9 +92,9 @@ def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='log pylab.cla() pylab.clf() - if int(options.measureConstTime) == 1: + if not options.onlyVarTime: generate( ['speedup', 'efficiency', 'dynamicity'] ) - if int(options.measureVarTime) == 1: + if not options.onlyConstTime: generate( ['variable_speedup', 'variable_efficiency', 'variable_dynamicity'] ) def main(): @@ -104,23 +106,28 @@ def main(): logging.info('EA in time O(1) and O(n) - speedup measure Sp, Ep and Dp for P & D') - n = int(options.nProc) + n = options.nProc F = options.fixedBound - logging.info('(1) measure for all combinaisons of P n D') - do_measure( '1', 1*n, 10*n, 101*n, 1*n, 10*n, 101*n ) + if options.measure is None or 1 in options.measure: + logging.info('(1) measure for all combinaisons of P n D') + do_measure( '1', 1*n, 10*n, 101*n, 1*n, 10*n, 101*n ) - logging.info('(2) measure for P \in [%d, %d[ with D fixed to %d' % (1*n, 101*n, F)) - do_measure( '2', 1*n, 1*n, 101*n, F, 1, F ) + if options.measure is None or 2 in options.measure: + logging.info('(2) measure for P \in [%d, %d[ with D fixed to %d' % (1*n, 101*n, F)) + do_measure( '2', 1*n, 1*n, 101*n, F, 1, F ) - logging.info('(3) measure for P \in [%d, %d[ with ps = %d and D fixed to %d' % (1*n, 1001*n, 10*n, F)) - do_measure( '3', 1*n, 10*n, 1001*n, F, 1, F ) + if options.measure is None or 3 in options.measure: + logging.info('(3) measure for P \in [%d, %d[ with ps = %d and D fixed to %d' % (1*n, 1001*n, 10*n, F)) + do_measure( '3', 1*n, 10*n, 1001*n, F, 1, F ) - logging.info('(4) measure for D \in [%d, %d[ with P fixed to %d' % (1*n, 101*n, F)) - do_measure( '4', F, 1, F, 1*n, 1*n, 101*n ) + if options.measure is None or 4 in options.measure: + logging.info('(4) measure for D \in [%d, %d[ with P fixed to %d' % (1*n, 101*n, F)) + do_measure( '4', F, 1, F, 1*n, 1*n, 101*n ) - logging.info('(5) measure for D \in [%d, %d[ with ds = %d and P fixed to %d' % (1*n, 1001*n, 10*n, F)) - do_measure( '5', F, 1, F, 1*n, 10*n, 1001*n ) + if options.measure is None or 5 in options.measure: + logging.info('(5) measure for D \in [%d, %d[ with ds = %d and P fixed to %d' % (1*n, 1001*n, 10*n, F)) + do_measure( '5', F, 1, F, 1*n, 10*n, 1001*n ) # when executed, just run main(): if __name__ == '__main__': From 821c22e1d5a78c92f1879c3fcf8b886bafa610c4 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 23 Dec 2010 14:31:34 +0100 Subject: [PATCH 29/81] fixed a mistake in cflags setting about openmp flags --- eo/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eo/CMakeLists.txt b/eo/CMakeLists.txt index 7bdcdba4..6999bd36 100644 --- a/eo/CMakeLists.txt +++ b/eo/CMakeLists.txt @@ -46,8 +46,8 @@ ENABLE_LANGUAGE(C) FIND_PACKAGE(OpenMP REQUIRED) IF(OPENMP_FOUND) - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_CXX_FLAGS}") - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_C_FLAGS}") + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") ENDIF() INCLUDE(CMakeBackwardCompatibilityCXX) From f5ead806f6fe5c18222bffa564622fd7639e0d75 Mon Sep 17 00:00:00 2001 From: Johann Dreo Date: Tue, 14 Dec 2010 15:27:26 +0100 Subject: [PATCH 30/81] add the parser/logger to the general header --- eo/src/eo | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eo/src/eo b/eo/src/eo index cf18f3ea..7c988f1c 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -198,6 +198,8 @@ #include #include +#include + //----------------------------------------------------------------------------- #endif From 60bc4b3b96220222105e3606a732724be14eeb9e Mon Sep 17 00:00:00 2001 From: Johann Dreo Date: Thu, 16 Dec 2010 15:50:26 +0100 Subject: [PATCH 31/81] evaluator that throw an exception if a maximum CPU user time has been reached, for POSIX systems --- eo/NEWS | 5 ++- eo/src/eo | 1 + eo/src/eoEvalUserTimeThrowException.h | 61 +++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 eo/src/eoEvalUserTimeThrowException.h diff --git a/eo/NEWS b/eo/NEWS index 50e25608..0f067e00 100644 --- a/eo/NEWS +++ b/eo/NEWS @@ -1,4 +1,7 @@ -* release 1.1 (not yet released) +* current + - evaluators that throw an exception if a maximum time has en reached (wallclock and CPU user time for POSIX systems), independently of the number of generations + +* release 1.1 - provide cmake build system, remove the old autotools one - package generation system - GCC 4.3 compatibility diff --git a/eo/src/eo b/eo/src/eo index 7c988f1c..89ed7da9 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -77,6 +77,7 @@ #include #include #include +#include // Continuators - all include eoContinue.h #include diff --git a/eo/src/eoEvalUserTimeThrowException.h b/eo/src/eoEvalUserTimeThrowException.h new file mode 100644 index 00000000..d47c064a --- /dev/null +++ b/eo/src/eoEvalUserTimeThrowException.h @@ -0,0 +1,61 @@ +/* +(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 +*/ + +#include +#include + +#include + +/** Check at each evaluation if a given CPU user time contract has been reached. + * + * Throw an eoMaxTimeException if the given max time has been reached. + * Usefull if you want to end the search independently of generations. + * This class uses (almost-)POSIX headers. + * It uses a computation of the user time used on the CPU. For a wallclock time measure, see eoEvalTimeThrowException + * + * @ingroup Evaluation + */ +template< class EOT > +class eoEvalUserTimeThrowException : public eoEvalFuncCounter< EOT > +{ +public: + eoEvalUserTimeThrowException( eoEvalFunc & func, long max ) : _max(max), eoEvalFuncCounter( func, "CPU-user") {} + + virtual void operator() ( EOT & eo ) + { + if( eo.invalid() ) { + + getrusage(RUSAGE_SELF,&_usage); + + if( _usage.ru_utime.tv_sec >= _max ) { + throw eoMaxTimeException( _usage.ru_utime.tv_sec ); + } else { + func(eo); + } + } + } + +protected: + long _max; + struct rusage _usage; +}; From fbc212f80d2a49f45cc35ab7f9f890dbdc1815d1 Mon Sep 17 00:00:00 2001 From: Johann Dreo Date: Thu, 16 Dec 2010 15:51:28 +0100 Subject: [PATCH 32/81] set the version to 1.1.1-edge --- eo/CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/eo/CMakeLists.txt b/eo/CMakeLists.txt index 6999bd36..548f1b54 100644 --- a/eo/CMakeLists.txt +++ b/eo/CMakeLists.txt @@ -15,11 +15,11 @@ INCLUDE(eo-conf.cmake OPTIONAL) PROJECT(EO) SET(PROJECT_VERSION_MAJOR 1) -SET(PROJECT_VERSION_MINOR 02) +SET(PROJECT_VERSION_MINOR 1) SET(PROJECT_VERSION_PATCH 1) SET(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}" CACHE STRING "Package version" FORCE) -SET(VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}" CACHE STRING "Global version" FORCE) -SET(VERSION "1.02" CACHE STRING "Global version" FORCE) +#SET(VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}" CACHE STRING "Global version" FORCE) +SET(VERSION "1.1.1-edge" CACHE STRING "Global version" FORCE) SET(GLOBAL_VERSION "${VERSION}") SET(PACKAGE_BUGREPORT "eodev-help@sourceforge.net" CACHE STRING "Package bug report" FORCE) From 07c22771cf03de2d97a01f6aaa9e02a1053df2db Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 23 Dec 2010 18:09:25 +0100 Subject: [PATCH 33/81] + now you are able to enable or not parallelization with the option --parallelize-loops=1|0 --- eo/src/apply.h | 14 +++++++++----- eo/src/utils/eoParser.cpp | 7 +++++++ eo/src/utils/eoParser.h | 6 ++++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index 2cd977b0..41d96adb 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -26,6 +26,7 @@ #ifndef _apply_h #define _apply_h +#include #include #include @@ -37,7 +38,8 @@ template void apply(eoUF& _proc, std::vector& _pop) { - for (unsigned i = 0; i < _pop.size(); ++i) + size_t size = _pop.size(); + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } @@ -52,8 +54,9 @@ void apply(eoUF& _proc, std::vector& _pop) template void omp_apply(eoUF& _proc, std::vector& _pop) { -#pragma omp parallel for default(none) shared(_proc, _pop) - for (unsigned i = 0; i < _pop.size(); ++i) + size_t size = _pop.size(); +#pragma omp parallel for if(eo::parallelizeLoopParam.value()) //default(none) shared(_proc, _pop, size) + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } @@ -67,8 +70,9 @@ void omp_apply(eoUF& _proc, std::vector& _pop) template void omp_dynamic_apply(eoUF& _proc, std::vector& _pop) { -#pragma omp parallel for default(none) shared(_proc, _pop) schedule(dynamic) - for (unsigned i = 0; i < _pop.size(); ++i) + size_t size = _pop.size(); +#pragma omp parallel for if(eo::parallelizeLoopParam.value()) schedule(dynamic) //default(none) shared(_proc, _pop, size) + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index f6c81f14..f7c2aac4 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -61,6 +61,9 @@ eoParameterLoader::~eoParameterLoader() } } +//multithreading +eoValueParam eo::parallelizeLoopParam = eoValueParam(false, "parallelize-loop", "Enable memory shared parallelization into evaluation's loops", '\0'); +//multithreading ends eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, string _lFileParamName, char _shortHand) : @@ -99,6 +102,10 @@ eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, readFrom(stream); processParam(needHelp); processParam(stopOnUnknownParam); + + //multithreading + processParam(eo::parallelizeLoopParam); + //multithreading ends } diff --git a/eo/src/utils/eoParser.h b/eo/src/utils/eoParser.h index bb8e5811..073d1a3e 100644 --- a/eo/src/utils/eoParser.h +++ b/eo/src/utils/eoParser.h @@ -93,6 +93,12 @@ private : }; +//multithreading +namespace eo +{ + extern eoValueParam parallelizeLoopParam; +} +//multithreading ends /** eoParser: command line parser and configuration file reader From 64f36841be3bd8811f243c2be30be39194adde41 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 23 Dec 2010 23:03:02 +0100 Subject: [PATCH 34/81] added measure into apply function --- eo/src/apply.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/eo/src/apply.h b/eo/src/apply.h index 41d96adb..deb13da8 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -29,6 +29,7 @@ #include #include #include +#include /** Applies a unary function to a std::vector of things. @@ -38,11 +39,18 @@ template void apply(eoUF& _proc, std::vector& _pop) { + double t1 = omp_get_wtime(); + size_t size = _pop.size(); +#pragma omp parallel for if(eo::parallelizeLoopParam.value()) //default(none) shared(_proc, _pop, size) for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } + + double t2 = omp_get_wtime(); + + eo::log << eo::logging << "### apply called cost: " << t2 - t1 << std::endl; } /** From 40817a09312b3b65b3c7d05b961a9e79258a9093 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 26 Dec 2010 19:09:08 +0100 Subject: [PATCH 35/81] * changed apply.h to use new parallelization s parameters --- eo/src/apply.h | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index deb13da8..d8bc9796 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -26,7 +26,7 @@ #ifndef _apply_h #define _apply_h -#include +#include #include #include #include @@ -39,14 +39,22 @@ template void apply(eoUF& _proc, std::vector& _pop) { + size_t size = _pop.size(); + double t1 = omp_get_wtime(); - size_t size = _pop.size(); -#pragma omp parallel for if(eo::parallelizeLoopParam.value()) //default(none) shared(_proc, _pop, size) - for (size_t i = 0; i < size; ++i) - { - _proc(_pop[i]); - } + if (!eo::parallel.isDynamic()) + { +#pragma omp parallel for if(eo::parallel.isEnabled()) //default(none) shared(_proc, _pop, size) + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } + } + else + { +#pragma omp parallel for schedule(dynamic) if(eo::parallel.isEnabled()) + //doesnot work with gcc 4.1.2 + //default(none) shared(_proc, _pop, size) + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } + } double t2 = omp_get_wtime(); @@ -63,7 +71,9 @@ template void omp_apply(eoUF& _proc, std::vector& _pop) { size_t size = _pop.size(); -#pragma omp parallel for if(eo::parallelizeLoopParam.value()) //default(none) shared(_proc, _pop, size) +#pragma omp parallel for if(eo::parallel.isEnabled()) + //doesnot work with gcc 4.1.2 + //default(none) shared(_proc, _pop, size) for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); @@ -79,7 +89,9 @@ template void omp_dynamic_apply(eoUF& _proc, std::vector& _pop) { size_t size = _pop.size(); -#pragma omp parallel for if(eo::parallelizeLoopParam.value()) schedule(dynamic) //default(none) shared(_proc, _pop, size) +#pragma omp parallel for if(eo::parallel.isEnabled()) schedule(dynamic) + //doesnot work with gcc 4.1.2 + //default(none) shared(_proc, _pop, size) for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); From 63d28c1c791ff11187e3a13ea4b74df325197060 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 26 Dec 2010 19:11:00 +0100 Subject: [PATCH 36/81] + created new eoParallel class with a global variable eo::parallel in order to store all parameters tied to parallelization and to access from anywhere --- eo/src/utils/eoParallel.cpp | 55 ++++++++++++++++++++++++++ eo/src/utils/eoParallel.h | 77 +++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 eo/src/utils/eoParallel.cpp create mode 100644 eo/src/utils/eoParallel.h diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp new file mode 100644 index 00000000..d8585592 --- /dev/null +++ b/eo/src/utils/eoParallel.cpp @@ -0,0 +1,55 @@ +// -*- 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 + +*/ + +#include "eoParallel.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", "Enable dynamic memory shared parallelization", '\0' ) +{} + +std::string eoParallel::className() const +{ + return "eoParallel"; +} + +void eoParallel::_createParameters( eoParser& parser ) +{ + std::string section("Parallelization"); + + parser.processParam( _isEnabled, section ); + parser.processParam( _isDynamic, section ); + parser.processParam( _prefix, section ); +} + +void make_parallel(eoParser& parser) +{ + eo::parallel._createParameters( parser ); +} + +eoParallel eo::parallel; diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h new file mode 100644 index 00000000..397bb5f0 --- /dev/null +++ b/eo/src/utils/eoParallel.h @@ -0,0 +1,77 @@ +// -*- 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 + +*/ + +/** @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(); + + virtual std::string className() const; + + inline bool isEnabled() { return _isEnabled.value(); } + inline bool isDynamic() { return _isDynamic.value(); } + inline std::string prefix() { return _prefix.value(); } + + friend void make_parallel(eoParser&); + +private: + void _createParameters( eoParser& ); + +private: + eoValueParam _isEnabled; + eoValueParam _isDynamic; + eoValueParam _prefix; +}; + +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 From b7379050bc79037a09ffe4ea6dbb5accb5565864 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 26 Dec 2010 19:12:20 +0100 Subject: [PATCH 37/81] * updated cmakelists.txt to compile new eoParallel class --- eo/src/utils/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/eo/src/utils/CMakeLists.txt b/eo/src/utils/CMakeLists.txt index ec70053b..94f994d2 100644 --- a/eo/src/utils/CMakeLists.txt +++ b/eo/src/utils/CMakeLists.txt @@ -27,7 +27,8 @@ SET (EOUTILS_SOURCES eoData.cpp make_help.cpp pipecom.cpp eoLogger.cpp - eoParserLogger.cpp) + eoParserLogger.cpp + eoParallel.cpp) ADD_LIBRARY(eoutils STATIC ${EOUTILS_SOURCES}) From 85fdbe6aba82b0c8d3ff90856dcb3c19a9513efd Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 26 Dec 2010 19:13:43 +0100 Subject: [PATCH 38/81] - removed old parallelization parameters from the old-style from eoParser class --- eo/src/utils/eoParser.cpp | 8 -------- eo/src/utils/eoParser.h | 7 ------- 2 files changed, 15 deletions(-) diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index f7c2aac4..23970023 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -61,10 +61,6 @@ eoParameterLoader::~eoParameterLoader() } } -//multithreading -eoValueParam eo::parallelizeLoopParam = eoValueParam(false, "parallelize-loop", "Enable memory shared parallelization into evaluation's loops", '\0'); -//multithreading ends - eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, string _lFileParamName, char _shortHand) : programName(_argv[0]), @@ -102,10 +98,6 @@ eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, readFrom(stream); processParam(needHelp); processParam(stopOnUnknownParam); - - //multithreading - processParam(eo::parallelizeLoopParam); - //multithreading ends } diff --git a/eo/src/utils/eoParser.h b/eo/src/utils/eoParser.h index 073d1a3e..adce9017 100644 --- a/eo/src/utils/eoParser.h +++ b/eo/src/utils/eoParser.h @@ -93,13 +93,6 @@ private : }; -//multithreading -namespace eo -{ - extern eoValueParam parallelizeLoopParam; -} -//multithreading ends - /** eoParser: command line parser and configuration file reader This class is persistent, so it can be stored and reloaded to restore From 7b87e4107215dfe33a518e391f47658984d6cf86 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Sun, 26 Dec 2010 19:19:20 +0100 Subject: [PATCH 39/81] * added eoParallel header inclusion to eo --- eo/src/eo | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eo/src/eo b/eo/src/eo index 89ed7da9..14dc831c 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -201,6 +201,8 @@ #include +#include + //----------------------------------------------------------------------------- #endif From 16e6e7f3b7c7c0371ce02bf72af7eb4efd8dd945 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 28 Dec 2010 16:41:14 +0100 Subject: [PATCH 40/81] * apply.h: now results stored to a filename defined with parallelization parameters --- eo/src/apply.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index d8bc9796..cb46c11d 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -58,7 +58,8 @@ void apply(eoUF& _proc, std::vector& _pop) double t2 = omp_get_wtime(); - eo::log << eo::logging << "### apply called cost: " << t2 - t1 << std::endl; + eoLogger log; + log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; } /** From 388d81b1ff7737f95aaa3f4ef8f001a0cd90d53b Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 28 Dec 2010 16:42:53 +0100 Subject: [PATCH 41/81] * updated eoParallel class in order to define the result filename according to the parallelization mode --- eo/src/utils/eoParallel.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index d8585592..ddfec8fb 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -44,7 +44,35 @@ void eoParallel::_createParameters( eoParser& parser ) parser.processParam( _isEnabled, section ); parser.processParam( _isDynamic, section ); + + std::string default_value( _prefix.defValue() ); + + if ( _isEnabled.value() ) + { + if ( _isDynamic.value() ) + { + default_value += "_dynamic.out"; + } + else + { + default_value += "_parallel.out"; + } + } + else + { + default_value += "_sequential.out"; + } + + _prefix.defValue( default_value ); + + std::cout << "defvalue: " << _prefix.defValue() << std::endl; + parser.processParam( _prefix, section ); + + std::cout << "value: " << parser.getParamWithLongName("parallelize-prefix")->getValue() << std::endl; + + std::cout << "defvalue: " << _prefix.defValue() << std::endl; + } void make_parallel(eoParser& parser) From bd88da01f769cdec3278955f61039ba6d3d1ffe6 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 28 Dec 2010 16:43:44 +0100 Subject: [PATCH 42/81] + added a test file for eoParallel class --- eo/test/CMakeLists.txt | 1 + eo/test/t-eoParallel.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 eo/test/t-eoParallel.cpp diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index 22006350..436c4503 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -65,6 +65,7 @@ SET (TEST_LIST t-eoExtendedVelocity t-eoLogger t-eoIQRStat + t-eoParallel t-openmp ) diff --git a/eo/test/t-eoParallel.cpp b/eo/test/t-eoParallel.cpp new file mode 100644 index 00000000..055f4598 --- /dev/null +++ b/eo/test/t-eoParallel.cpp @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------------- +// t-eoParallel.cpp +//----------------------------------------------------------------------------- + +#include +#include +//#include +#include "real_value.h" + +//----------------------------------------------------------------------------- + +typedef eoReal< eoMinimizingFitness > EOT; + +int main(int ac, char** av) +{ + eoParser parser(ac, av); + + unsigned int popSize = parser.getORcreateParam((unsigned int)100, "popSize", "Population Size", 'P', "Evolution Engine").value(); + unsigned int dimSize = parser.getORcreateParam((unsigned int)10, "dimSize", "Dimension Size", 'd', "Evolution Engine").value(); + + uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); + if (seedParam == 0) { seedParam = time(0); } + + make_parallel(parser); + make_help(parser); + + rng.reseed( seedParam ); + + eoUniformGenerator< double > gen(-5, 5); + eoInitFixedLength< EOT > init( dimSize, gen ); + + eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); + eoEvalFuncCounter< EOT > eval( mainEval ); + + eoPop< EOT > pop( popSize, init ); + + //apply< EOT >( eval, pop ); + eoPopLoopEval< EOT > popEval( eval ); + popEval( pop, pop ); + + eo::log << eo::quiet << "DONE!" << std::endl; + + return 0; +} + +//----------------------------------------------------------------------------- From 2013d57fe8bfd397388846079e32f2eb0aff0f3c Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 28 Dec 2010 22:54:10 +0100 Subject: [PATCH 43/81] fixed an issue in eoParallel class --- eo/src/utils/eoParallel.cpp | 30 ++++++++++++------------------ eo/src/utils/eoParallel.h | 7 ++++--- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index ddfec8fb..d3fd2d66 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -38,41 +38,35 @@ std::string eoParallel::className() const return "eoParallel"; } -void eoParallel::_createParameters( eoParser& parser ) +std::string eoParallel::prefix() const { - std::string section("Parallelization"); - - parser.processParam( _isEnabled, section ); - parser.processParam( _isDynamic, section ); - - std::string default_value( _prefix.defValue() ); + std::string value( _prefix.value() ); if ( _isEnabled.value() ) { if ( _isDynamic.value() ) { - default_value += "_dynamic.out"; + value += "_dynamic.out"; } else { - default_value += "_parallel.out"; + value += "_parallel.out"; } } else { - default_value += "_sequential.out"; + value += "_sequential.out"; } - _prefix.defValue( default_value ); - - std::cout << "defvalue: " << _prefix.defValue() << std::endl; + return value; +} +void eoParallel::_createParameters( eoParser& parser ) +{ + std::string section("Parallelization"); + parser.processParam( _isEnabled, section ); + parser.processParam( _isDynamic, section ); parser.processParam( _prefix, section ); - - std::cout << "value: " << parser.getParamWithLongName("parallelize-prefix")->getValue() << std::endl; - - std::cout << "defvalue: " << _prefix.defValue() << std::endl; - } void make_parallel(eoParser& parser) diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h index 397bb5f0..4e13f8b3 100644 --- a/eo/src/utils/eoParallel.h +++ b/eo/src/utils/eoParallel.h @@ -47,9 +47,10 @@ public: virtual std::string className() const; - inline bool isEnabled() { return _isEnabled.value(); } - inline bool isDynamic() { return _isDynamic.value(); } - inline std::string prefix() { return _prefix.value(); } + inline bool isEnabled() const { return _isEnabled.value(); } + inline bool isDynamic() const { return _isDynamic.value(); } + + std::string prefix() const; friend void make_parallel(eoParser&); From 6ecfab080248c30a5cad2be2e5581341a7ab7a95 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 5 Jan 2011 16:07:08 +0100 Subject: [PATCH 44/81] * --parallelize-prefix parameter description --- eo/src/utils/eoParallel.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index d3fd2d66..3ab25e7f 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -30,7 +30,7 @@ Authors: 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", "Enable dynamic memory shared parallelization", '\0' ) + _prefix( "results", "parallelize-prefix", "Here's the prefix filename where the results are going to be stored", '\0' ) {} std::string eoParallel::className() const From 7357e2a54f31efacc692ee79c05290df91ea93d4 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 6 Jan 2011 09:16:01 +0100 Subject: [PATCH 45/81] * a little update tu be compatible with gnuplot --- eo/src/apply.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index cb46c11d..175ce51d 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -59,7 +59,7 @@ void apply(eoUF& _proc, std::vector& _pop) double t2 = omp_get_wtime(); eoLogger log; - log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; + log << eo::file(eo::parallel.prefix()) << t2 - t1 << std::endl; } /** From 914842253657988a126e2a866833c6666e585e3f Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 26 Jan 2011 18:09:37 +0100 Subject: [PATCH 46/81] * doc: solved some mistakes Conflicts: eo/doc/index.h --- eo/doc/index.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/eo/doc/index.h b/eo/doc/index.h index 2fad16e2..52a5758c 100644 --- a/eo/doc/index.h +++ b/eo/doc/index.h @@ -43,17 +43,17 @@ massively use templates, so that you will not be limited by interfaces when using your own representation. Once you have a representation, you will build your own evolutionary algorithm -by assembling @ref Operators in @ref Algorithms. +by assembling @ref Operators in @ref Algorithms. In %EO, most of the objects are functors, that is classes with an operator(), that you -can call just as if they were classical functions. For example, an algorithm is a -functor, that manipulate a population of individuals, it will be implemented as a functor, +can call just as if they were classical functions. For example, an algorithm is a +functor, that manipulate a population of individuals, it will be implemented as a functor, with a member like: operator()(eoPop). Once called on a given population, it will search for the optimum of a given problem. Generally, operators are instanciated once and then binded in an algorithm by reference. Thus, you can easily build your own algorithm by trying several combination of operators. -For a more detailled introduction to the design of %EO you can look at the +For a more detailled introduction to the design of %EO you can look at the slides from a talk at EA 2001 or at the corresponding article in Lecture Notes In Computer Science, 2310, Selected Papers from the 5th European Conference on Artificial Evolution: - http://portal.acm.org/citation.cfm?id=727742 From df01e1790e785467bb5aa25e1888b2941bc4c662 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 22 Dec 2010 13:40:49 +0100 Subject: [PATCH 47/81] * package dependancies changed --- eo/Packaging.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eo/Packaging.cmake b/eo/Packaging.cmake index c9e2d44b..de81fadc 100644 --- a/eo/Packaging.cmake +++ b/eo/Packaging.cmake @@ -67,7 +67,7 @@ SET(CPACK_PACKAGE_INSTALL_DIRECTORY "${PROJECT_NAME} ${PROJECT_VERSION_MAJOR}.${ ### 4) Set up debian packaging information ###################################################################################### -SET(CPACK_DEBIAN_PACKAGE_DEPENDS "libstdc++6, libgcc1, libc6, libxml2, libmpich2-1.2") +SET(CPACK_DEBIAN_PACKAGE_DEPENDS "libstdc++6, libgcc1, libc6, g++") SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") From 9f8521f0862fdce26c2e434b4ec89026ae980047 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 23 Dec 2010 12:22:29 +0100 Subject: [PATCH 48/81] + add the value() method in eoParam used by dae --- eo/src/utils/eoParam.h | 46 +++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/eo/src/utils/eoParam.h b/eo/src/utils/eoParam.h index 1eb97b30..868507cf 100644 --- a/eo/src/utils/eoParam.h +++ b/eo/src/utils/eoParam.h @@ -169,32 +169,46 @@ public : eoParam::defValue(getValue()); } - /** Parameter value + /** Get a reference on the parameter value @return parameter value */ - ValueType& value() - { return repValue; } + ValueType& value() { return repValue; } - /** Parameter value + /** Get a const reference on the parameter value @overload @return parameter value */ - const ValueType& value() const - { return repValue; } + 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(); - } + { + std::ostringstream os; + os << repValue; + return os.str(); + } - /** @brief Set value according to the speciied string + /** @brief Set the value according to the speciied string For scalar types the textual represenation is typically quite straigtforward. @@ -208,10 +222,10 @@ public : @param _value Textual representation of the new value */ void setValue(const std::string& _value) - { - std::istringstream is(_value); - is >> repValue; - } + { + std::istringstream is(_value); + is >> repValue; + } protected: From aa214e78553d9178ec754e8b22703fb333936b42 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 26 Jan 2011 18:10:34 +0100 Subject: [PATCH 49/81] - removed t-eoDualFitness from test/CMakeLists.txt because it fails Conflicts: eo/test/CMakeLists.txt --- eo/test/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index 436c4503..4e68b02a 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -67,6 +67,8 @@ SET (TEST_LIST t-eoIQRStat t-eoParallel t-openmp + #t-eoDualFitness + t-eoParser ) From 007c29e7361fd50b611d84b05bf637a92c5e1bc1 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:25:22 +0100 Subject: [PATCH 50/81] add the parser/logger to the general header Conflicts: eo/src/eo --- eo/src/eo | 2 -- 1 file changed, 2 deletions(-) diff --git a/eo/src/eo b/eo/src/eo index 14dc831c..18e91d60 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -203,8 +203,6 @@ #include -//----------------------------------------------------------------------------- - #endif // Local Variables: From ecd8f7ec0336e2e22185796d9eb29b26063bce4b Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:29:09 +0100 Subject: [PATCH 51/81] + now you are able to enable or not parallelization with the option --parallelize-loops=1|0 Conflicts: eo/src/apply.h eo/src/utils/eoParser.cpp eo/src/utils/eoParser.h --- eo/src/apply.h | 1 + eo/src/utils/eoParser.cpp | 4 ++++ eo/src/utils/eoParser.h | 1 - 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index 175ce51d..bba8adc8 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -27,6 +27,7 @@ #define _apply_h #include +#include #include #include #include diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index 23970023..34726c81 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -98,6 +98,10 @@ eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, readFrom(stream); processParam(needHelp); processParam(stopOnUnknownParam); + + //multithreading + processParam(eo::parallelizeLoopParam); + //multithreading ends } diff --git a/eo/src/utils/eoParser.h b/eo/src/utils/eoParser.h index adce9017..a96ec1be 100644 --- a/eo/src/utils/eoParser.h +++ b/eo/src/utils/eoParser.h @@ -92,7 +92,6 @@ private : std::vector ownedParams; }; - /** eoParser: command line parser and configuration file reader This class is persistent, so it can be stored and reloaded to restore From a3dda50b8fc25f6e9dc0ac77ee4aa371e0d8e73a Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:30:40 +0100 Subject: [PATCH 52/81] added measure into apply function Conflicts: eo/src/apply.h --- eo/src/apply.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index bba8adc8..9e112cdc 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -40,9 +40,8 @@ template void apply(eoUF& _proc, std::vector& _pop) { - size_t size = _pop.size(); - double t1 = omp_get_wtime(); + size_t size = _pop.size(); if (!eo::parallel.isDynamic()) { From 48115ee2f00843dc25c11dbd88fb7fa7841a51a2 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:31:28 +0100 Subject: [PATCH 53/81] * changed apply.h to use new parallelization s parameters Conflicts: eo/src/apply.h --- eo/src/apply.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index 9e112cdc..bba8adc8 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -40,9 +40,10 @@ template void apply(eoUF& _proc, std::vector& _pop) { - double t1 = omp_get_wtime(); size_t size = _pop.size(); + double t1 = omp_get_wtime(); + if (!eo::parallel.isDynamic()) { #pragma omp parallel for if(eo::parallel.isEnabled()) //default(none) shared(_proc, _pop, size) From 5f67e0e151687a7ab1091a1fe4160aa1118758db Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:35:49 +0100 Subject: [PATCH 54/81] - removed old parallelization parameters from the old-style from eoParser class Conflicts: eo/src/utils/eoParser.h --- eo/src/utils/eoParser.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index 34726c81..23970023 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -98,10 +98,6 @@ eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, readFrom(stream); processParam(needHelp); processParam(stopOnUnknownParam); - - //multithreading - processParam(eo::parallelizeLoopParam); - //multithreading ends } From 03600594c4275d5cf62f2d2fab7212e79c28e2ca Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 28 Dec 2010 16:42:53 +0100 Subject: [PATCH 55/81] * updated eoParallel class in order to define the result filename according to the parallelization mode --- eo/src/utils/eoParallel.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index 3ab25e7f..c590c7ad 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -66,7 +66,35 @@ void eoParallel::_createParameters( eoParser& parser ) std::string section("Parallelization"); parser.processParam( _isEnabled, section ); parser.processParam( _isDynamic, section ); + + std::string default_value( _prefix.defValue() ); + + if ( _isEnabled.value() ) + { + if ( _isDynamic.value() ) + { + default_value += "_dynamic.out"; + } + else + { + default_value += "_parallel.out"; + } + } + else + { + default_value += "_sequential.out"; + } + + _prefix.defValue( default_value ); + + std::cout << "defvalue: " << _prefix.defValue() << std::endl; + parser.processParam( _prefix, section ); + + std::cout << "value: " << parser.getParamWithLongName("parallelize-prefix")->getValue() << std::endl; + + std::cout << "defvalue: " << _prefix.defValue() << std::endl; + } void make_parallel(eoParser& parser) From c8ecdb4beecf740a39352051d5312157acee3c3b Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:39:15 +0100 Subject: [PATCH 56/81] fixed an issue in eoParallel class Conflicts: eo/src/utils/eoParallel.cpp --- eo/src/utils/eoParallel.cpp | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index c590c7ad..3ab25e7f 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -66,35 +66,7 @@ void eoParallel::_createParameters( eoParser& parser ) std::string section("Parallelization"); parser.processParam( _isEnabled, section ); parser.processParam( _isDynamic, section ); - - std::string default_value( _prefix.defValue() ); - - if ( _isEnabled.value() ) - { - if ( _isDynamic.value() ) - { - default_value += "_dynamic.out"; - } - else - { - default_value += "_parallel.out"; - } - } - else - { - default_value += "_sequential.out"; - } - - _prefix.defValue( default_value ); - - std::cout << "defvalue: " << _prefix.defValue() << std::endl; - parser.processParam( _prefix, section ); - - std::cout << "value: " << parser.getParamWithLongName("parallelize-prefix")->getValue() << std::endl; - - std::cout << "defvalue: " << _prefix.defValue() << std::endl; - } void make_parallel(eoParser& parser) From 3d06d4a42a6dae784e11eaaad07efc3fb3499e3f Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 10:43:13 +0100 Subject: [PATCH 57/81] + eoParallel: nthreads option * apply.h: mangled the openmp code with pre-processing conditions --- eo/src/apply.h | 12 +++++++++++- eo/src/utils/eoParallel.cpp | 12 +++++++----- eo/src/utils/eoParallel.h | 6 ++++-- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index bba8adc8..63044c38 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -40,6 +40,10 @@ template void apply(eoUF& _proc, std::vector& _pop) { +#ifdef _OPENMP + + omp_set_num_threads(eo::parallel.nthreads()); + size_t size = _pop.size(); double t1 = omp_get_wtime(); @@ -60,7 +64,13 @@ void apply(eoUF& _proc, std::vector& _pop) double t2 = omp_get_wtime(); eoLogger log; - log << eo::file(eo::parallel.prefix()) << t2 - t1 << std::endl; + log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; + +#else // _OPENMP + + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } + +#endif // !_OPENMP } /** diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index 3ab25e7f..e267ce7f 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -21,16 +21,17 @@ Contact: http://eodev.sourceforge.net Authors: - Caner Candan +Caner Candan */ #include "eoParallel.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' ) +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' ) {} std::string eoParallel::className() const @@ -67,6 +68,7 @@ void eoParallel::_createParameters( eoParser& parser ) parser.processParam( _isEnabled, section ); parser.processParam( _isDynamic, section ); parser.processParam( _prefix, section ); + parser.processParam( _nthreads, section ); } void make_parallel(eoParser& parser) diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h index 4e13f8b3..2ce9ea47 100644 --- a/eo/src/utils/eoParallel.h +++ b/eo/src/utils/eoParallel.h @@ -26,7 +26,7 @@ Caner Candan /** @defgroup Parallel Parallel * @ingroup Utilities -@{ + @{ */ #ifndef eoParallel_h @@ -52,6 +52,8 @@ public: std::string prefix() const; + inline unsigned int nthreads() const { return _nthreads.value(); } + friend void make_parallel(eoParser&); private: @@ -65,7 +67,7 @@ private: void make_parallel(eoParser&); -namespace eo +namespace eo { /** * parallel is an external global variable defined in order to use where ever you want the parallel parameters From db4eda2de527dcc026d1080990c4c294c24d506a Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 27 Jan 2011 14:41:17 +0100 Subject: [PATCH 58/81] * eoParallel: added a missing attribute --- eo/src/utils/eoParallel.h | 1 + 1 file changed, 1 insertion(+) diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h index 2ce9ea47..79cedfda 100644 --- a/eo/src/utils/eoParallel.h +++ b/eo/src/utils/eoParallel.h @@ -63,6 +63,7 @@ private: eoValueParam _isEnabled; eoValueParam _isDynamic; eoValueParam _prefix; + eoValueParam _nthreads; }; void make_parallel(eoParser&); From 54e2a8b91e4cad695d5090101de48d97615f7594 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Fri, 28 Jan 2011 14:38:50 +0100 Subject: [PATCH 59/81] * apply.h: size variable missing without openmp --- eo/CMakeLists.txt | 2 +- eo/src/apply.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eo/CMakeLists.txt b/eo/CMakeLists.txt index 548f1b54..3a5fe04b 100644 --- a/eo/CMakeLists.txt +++ b/eo/CMakeLists.txt @@ -106,7 +106,7 @@ ENDIF (ENABLE_CMAKE_TESTING) ### 5) Where must cmake go now ? ###################################################################################### -ADD_SUBDIRECTORY(app) +#ADD_SUBDIRECTORY(app) ADD_SUBDIRECTORY(doc) ADD_SUBDIRECTORY(src) ADD_SUBDIRECTORY(test) diff --git a/eo/src/apply.h b/eo/src/apply.h index 63044c38..ba6d2f9a 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -40,12 +40,12 @@ template void apply(eoUF& _proc, std::vector& _pop) { + size_t size = _pop.size(); + #ifdef _OPENMP omp_set_num_threads(eo::parallel.nthreads()); - size_t size = _pop.size(); - double t1 = omp_get_wtime(); if (!eo::parallel.isDynamic()) From 2044d92eff240d90e7b86eff662bfda5319f48d9 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 2 Feb 2011 23:50:58 +0100 Subject: [PATCH 60/81] * eoParallel: added the call to omp_set_num_threads to define the number of threads with parameters --- eo/src/apply.h | 2 -- eo/src/utils/eoParallel.cpp | 12 ++++++++++++ eo/test/t-eoParallel.cpp | 10 ++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index ba6d2f9a..024dd896 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -44,8 +44,6 @@ void apply(eoUF& _proc, std::vector& _pop) #ifdef _OPENMP - omp_set_num_threads(eo::parallel.nthreads()); - double t1 = omp_get_wtime(); if (!eo::parallel.isDynamic()) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index e267ce7f..fdc047ac 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -25,6 +25,8 @@ Caner Candan */ +#include + #include "eoParallel.h" eoParallel::eoParallel() : @@ -74,6 +76,16 @@ void eoParallel::_createParameters( eoParser& parser ) 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() ); + } + } +#endif // !_OPENMP } eoParallel eo::parallel; diff --git a/eo/test/t-eoParallel.cpp b/eo/test/t-eoParallel.cpp index 055f4598..72d4f264 100644 --- a/eo/test/t-eoParallel.cpp +++ b/eo/test/t-eoParallel.cpp @@ -2,6 +2,8 @@ // t-eoParallel.cpp //----------------------------------------------------------------------------- +#include + #include #include //#include @@ -40,6 +42,14 @@ int main(int ac, char** av) eo::log << eo::quiet << "DONE!" << std::endl; +#pragma omp parallel + { + if ( 0 == omp_get_thread_num() ) + { + eo::log << "num of threads: " << omp_get_num_threads() << std::endl; + } + } + return 0; } From 85d02cbdb304760704bfe5905b277808e0e81ab7 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Fri, 4 Feb 2011 16:28:24 +0100 Subject: [PATCH 61/81] * eoParallel: added the parameter enableResults --- eo/src/apply.h | 7 +++++-- eo/src/utils/eoParallel.cpp | 4 +++- eo/src/utils/eoParallel.h | 3 +++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index 024dd896..5c683671 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -61,8 +61,11 @@ void apply(eoUF& _proc, std::vector& _pop) double t2 = omp_get_wtime(); - eoLogger log; - log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; + if ( eo::parallel.enableResults() ) + { + eoLogger log; + log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; + } #else // _OPENMP diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index fdc047ac..e58585ef 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -33,7 +33,8 @@ 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' ) + _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' ) {} std::string eoParallel::className() const @@ -71,6 +72,7 @@ void eoParallel::_createParameters( eoParser& parser ) parser.processParam( _isDynamic, section ); parser.processParam( _prefix, section ); parser.processParam( _nthreads, section ); + parser.processParam( _enableResults, section ); } void make_parallel(eoParser& parser) diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h index 79cedfda..54b42821 100644 --- a/eo/src/utils/eoParallel.h +++ b/eo/src/utils/eoParallel.h @@ -54,6 +54,8 @@ public: inline unsigned int nthreads() const { return _nthreads.value(); } + inline bool enableResults() const { return _enableResults.value(); } + friend void make_parallel(eoParser&); private: @@ -64,6 +66,7 @@ private: eoValueParam _isDynamic; eoValueParam _prefix; eoValueParam _nthreads; + eoValueParam _enableResults; }; void make_parallel(eoParser&); From 7add23931b0365a65ed0c732785bb2109e1496af Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Fri, 4 Feb 2011 16:29:27 +0100 Subject: [PATCH 62/81] * t-openmpy.*: added a header --- eo/test/t-openmp.cpp | 26 ++++++++++++++++++++++++++ eo/test/t-openmp.py | 23 +++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/eo/test/t-openmp.cpp b/eo/test/t-openmp.cpp index 325cb653..cd345080 100644 --- a/eo/test/t-openmp.cpp +++ b/eo/test/t-openmp.cpp @@ -1,3 +1,29 @@ +// -*- 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 + +*/ + //----------------------------------------------------------------------------- // t-openmp.cpp //----------------------------------------------------------------------------- diff --git a/eo/test/t-openmp.py b/eo/test/t-openmp.py index ab43bb93..5cd9e131 100755 --- a/eo/test/t-openmp.py +++ b/eo/test/t-openmp.py @@ -1,5 +1,28 @@ #!/usr/bin/env python +# +# (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 +# + import optparse, logging, sys, os from datetime import datetime From 9e95eefb529881feec57253db87cc51164860022 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 8 Feb 2011 10:59:00 +0100 Subject: [PATCH 63/81] * eoParallel: added the both parameters enable_results and do_measure --- eo/src/apply.h | 10 +++++++--- eo/src/utils/eoParallel.cpp | 26 ++++++++++++++++++++++++-- eo/src/utils/eoParallel.h | 4 ++++ 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/eo/src/apply.h b/eo/src/apply.h index 5c683671..33b354fc 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -44,7 +44,12 @@ void apply(eoUF& _proc, std::vector& _pop) #ifdef _OPENMP - double t1 = omp_get_wtime(); + double t1 = 0; + + if ( eo::parallel.enableResults() ) + { + t1 = omp_get_wtime(); + } if (!eo::parallel.isDynamic()) { @@ -59,10 +64,9 @@ void apply(eoUF& _proc, std::vector& _pop) for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } } - double t2 = omp_get_wtime(); - if ( eo::parallel.enableResults() ) { + double t2 = omp_get_wtime(); eoLogger log; log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; } diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index e58585ef..e0ce63aa 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -28,14 +28,30 @@ Caner Candan #include #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' ) -{} + _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 { @@ -73,6 +89,7 @@ void eoParallel::_createParameters( eoParser& parser ) parser.processParam( _prefix, section ); parser.processParam( _nthreads, section ); parser.processParam( _enableResults, section ); + parser.processParam( _doMeasure, section ); } void make_parallel(eoParser& parser) @@ -87,6 +104,11 @@ void make_parallel(eoParser& parser) omp_set_num_threads( eo::parallel.nthreads() ); } } + + if ( eo::parallel.doMeasure() ) + { + eo::parallel._t_start = omp_get_wtime(); + } #endif // !_OPENMP } diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h index 54b42821..3f22f6c4 100644 --- a/eo/src/utils/eoParallel.h +++ b/eo/src/utils/eoParallel.h @@ -44,6 +44,7 @@ class eoParallel : public eoObject { public: eoParallel(); + ~eoParallel(); virtual std::string className() const; @@ -55,6 +56,7 @@ public: 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&); @@ -67,6 +69,8 @@ private: eoValueParam _prefix; eoValueParam _nthreads; eoValueParam _enableResults; + eoValueParam _doMeasure; + double _t_start; }; void make_parallel(eoParser&); From 1d568a5abdf967e19b2a8e1ef2220cba1ea90a5d Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 24 Feb 2011 10:32:13 +0100 Subject: [PATCH 64/81] * application/common/cmakelists.txt: fixed issues with copy of files --- edo/application/common/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/edo/application/common/CMakeLists.txt b/edo/application/common/CMakeLists.txt index d16353f5..14c3509e 100644 --- a/edo/application/common/CMakeLists.txt +++ b/edo/application/common/CMakeLists.txt @@ -10,6 +10,6 @@ FOREACH(file ${RESOURCES}) EXECUTE_PROCESS( COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/${file} - ${DO_BINARY_DIR}/${file} + ${EDO_BINARY_DIR}/${file} ) ENDFOREACH(file) From d1426b4bce43dc6c562398b264432e39c2bdabde Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 24 Feb 2011 11:09:51 +0100 Subject: [PATCH 65/81] * fixed issues on the code to be compatible with last version of boost --- edo/src/edoEstimatorNormalMulti.h | 2 +- edo/src/edoSamplerNormalMulti.h | 2 +- edo/test/t-mean-distance.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/edo/src/edoEstimatorNormalMulti.h b/edo/src/edoEstimatorNormalMulti.h index f06fadd8..8b4b7abb 100644 --- a/edo/src/edoEstimatorNormalMulti.h +++ b/edo/src/edoEstimatorNormalMulti.h @@ -73,7 +73,7 @@ public: //------------------------------------------------------------- - _varcovar.resize(s_size, s_size); + _varcovar.resize(s_size); //------------------------------------------------------------- diff --git a/edo/src/edoSamplerNormalMulti.h b/edo/src/edoSamplerNormalMulti.h index c1ce5745..889c2e54 100644 --- a/edo/src/edoSamplerNormalMulti.h +++ b/edo/src/edoSamplerNormalMulti.h @@ -53,7 +53,7 @@ public: assert( Vl == Vc ); - _L.resize(Vl, Vc); + _L.resize(Vl); unsigned int i,j,k; diff --git a/edo/test/t-mean-distance.cpp b/edo/test/t-mean-distance.cpp index 40a95c99..6f3b84f6 100644 --- a/edo/test/t-mean-distance.cpp +++ b/edo/test/t-mean-distance.cpp @@ -41,7 +41,7 @@ Authors: #include #include -#include +#include #include "Rosenbrock.h" #include "Sphere.h" From aa23cec2a04fe81857758af0cb1b4a3310844c1e Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 24 Feb 2011 11:10:47 +0100 Subject: [PATCH 66/81] + added install.cmake to configure dependancies paths --- edo/CMakeLists.txt | 35 +++++++++++++++++++++++------------ edo/install.cmake-dist | 20 ++++++++++++++++++++ 2 files changed, 43 insertions(+), 12 deletions(-) create mode 100644 edo/install.cmake-dist diff --git a/edo/CMakeLists.txt b/edo/CMakeLists.txt index 868c456b..56343704 100644 --- a/edo/CMakeLists.txt +++ b/edo/CMakeLists.txt @@ -1,5 +1,14 @@ +############################################################################ +########## +### 1) If you want to set your own variables in install.cmake and avoid the cmd line ###################################################################################### -### 1) Set the application properties + +INCLUDE(install.cmake OPTIONAL) + +###################################################################################### + +###################################################################################### +### 2) Project properties ###################################################################################### # Checks cmake version compatibility @@ -16,15 +25,12 @@ SET(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT ###################################################################################### -### 2) Include useful features +### 3) Include useful features ###################################################################################### INCLUDE(FindDoxygen) INCLUDE(FindPkgConfig) -PKG_CHECK_MODULES(EO eo REQUIRED) -PKG_CHECK_MODULES(MO mo REQUIRED) - FIND_PACKAGE(Boost 1.33.0) INCLUDE_DIRECTORIES( @@ -34,11 +40,16 @@ INCLUDE_DIRECTORIES( # /Dev/ometah-0.3/common ) +LINK_DIRECTORIES( + ${EO_LIBRARY_DIRS} + ${MO_LIBRARY_DIRS} + ) + ###################################################################################### ###################################################################################### -### 3) Include header files path +### 4) Include header files path ###################################################################################### INCLUDE_DIRECTORIES( @@ -49,7 +60,7 @@ INCLUDE_DIRECTORIES( ###################################################################################### -### 4) Set compiler definitions +### 5) Set compiler definitions ###################################################################################### IF(UNIX) @@ -63,7 +74,7 @@ ENDIF() ###################################################################################### -### 5) Prepare some variables for CMAKE usage +### 6) Prepare some variables for CMAKE usage ###################################################################################### SET(SAMPLE_SRCS) @@ -72,7 +83,7 @@ SET(SAMPLE_SRCS) ###################################################################################### -### 6) Now where we go ? +### 7) Now where we go ? ###################################################################################### ADD_SUBDIRECTORY(src) @@ -85,7 +96,7 @@ ADD_SUBDIRECTORY(doc) ###################################################################################### -### 7) Create executable, link libraries and prepare target +### 8) Create executable, link libraries and prepare target ###################################################################################### SET(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) @@ -99,7 +110,7 @@ INSTALL(TARGETS edo ARCHIVE DESTINATION lib COMPONENT libraries) ###################################################################################### -### 8) Install pkg-config config file for EO +### 9) Install pkg-config config file for EO ###################################################################################### INSTALL(FILES edo.pc DESTINATION lib/pkgconfig COMPONENT headers) @@ -108,7 +119,7 @@ INSTALL(FILES edo.pc DESTINATION lib/pkgconfig COMPONENT headers) ###################################################################################### -### 9) Include packaging +### 10) Include packaging ###################################################################################### INCLUDE(Packaging.cmake) diff --git a/edo/install.cmake-dist b/edo/install.cmake-dist new file mode 100644 index 00000000..bd07be7c --- /dev/null +++ b/edo/install.cmake-dist @@ -0,0 +1,20 @@ +# Variables to set + +# directory we need to build project +SET(EO_DIR "<>" CACHE PATH "EO directory" FORCE) +SET(MO_DIR "<>" CACHE PATH "MO directory" FORCE) + +# automagically set parameters, do not edit + +SET(EO_INCLUDE_DIRS "${EO_DIR}/src" CACHE PATH "EO include directory" FORCE) +SET(EO_LIBRARY_DIRS "${EO_DIR}/release/lib" CACHE PATH "EO library directory" FORCE) +SET(EO_LIBRARIES "eoutils eo es ga cma gcov") + +SET(MO_INCLUDE_DIRS "${MO_DIR}/src" CACHE PATH "MO include directory" FORCE) +SET(MO_LIBRARY_DIRS "${MO_DIR}/release/lib" CACHE PATH "MO library directory" FORCE) +SET(MO_LIBRARIES "mo") + +# ... or rather use pkg-config (dont forget to comment the code above) + +#PKG_CHECK_MODULES(EO eo REQUIRED) +#PKG_CHECK_MODULES(MO mo REQUIRED) From 3a409a789e55f997c3489c4c30dc796cb6881760 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 23 Mar 2011 17:34:35 +0100 Subject: [PATCH 67/81] * eoEasyEA: moved offspring into attributes space in order to avoid memory reallocation when we restart --- eo/src/eoEasyEA.h | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 4fc6d6e7..c058c233 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -81,6 +81,25 @@ template class eoEasyEA: public eoAlgo replace(_replace) {} + /** Ctor taking a breed and merge, an overload of ctor to define an offspring size */ + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoBreed& _breed, + eoReplacement& _replace, + unsigned _offspringSize + ) : continuator(_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + selectTransform(dummySelect, dummyTransform), + breed(_breed), + mergeReduce(dummyMerge, dummyReduce), + replace(_replace) + { + offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. + } + /* eoEasyEA(eoContinue & _continuator, eoPopEvalFunc & _pop_eval, @@ -191,7 +210,7 @@ template class eoEasyEA: public eoAlgo /// Apply a few generation of evolution to the population. virtual void operator()(eoPop& _pop) { - eoPop offspring, empty_pop; + eoPop empty_pop; popEval(empty_pop, _pop); // A first eval of pop. @@ -270,6 +289,8 @@ template class eoEasyEA: public eoAlgo eoMergeReduce mergeReduce; eoReplacement& replace; + eoPop offspring; + // Friend classes friend class eoIslandsEasyEA ; friend class eoDistEvalEasyEA ; From b0844ae27b6ad4a3c51403ced3d0a5ac223e9cf6 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 24 Mar 2011 12:52:27 +0100 Subject: [PATCH 68/81] * switched eoGenOp::apply method from protected to public in order to be visible from eoSequentialOp --- eo/src/eoGenOp.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/eo/src/eoGenOp.h b/eo/src/eoGenOp.h index 86d4ebbd..c304ec64 100644 --- a/eo/src/eoGenOp.h +++ b/eo/src/eoGenOp.h @@ -66,17 +66,17 @@ class eoGenOp : public eoOp, public eoUF &, void> /** Max production is used to reserve space for all elements that are used by the operator, not setting it properly can result in a crash */ - virtual unsigned max_production(void) = 0; + virtual unsigned max_production(void) = 0; + + virtual std::string className() const = 0; - virtual std::string className() const = 0; void operator()(eoPopulator& _pop) { - _pop.reserve(max_production()); - apply(_pop); + _pop.reserve( max_production() ); + apply(_pop); } - - protected : + //protected : /** the function that will do the work */ virtual void apply(eoPopulator& _pop) = 0; From d8bbe055ca33f5c5305cd20086b96228ce3ecc66 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 30 Mar 2011 15:50:19 +0200 Subject: [PATCH 69/81] * eoEasyEA: pop reserve at each call to algo --- eo/src/eoEasyEA.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index c058c233..2ca8d37e 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -210,6 +210,8 @@ template class eoEasyEA: public eoAlgo /// Apply a few generation of evolution to the population. virtual void operator()(eoPop& _pop) { + _pop.reserve(offspring.capacity()); + eoPop empty_pop; popEval(empty_pop, _pop); // A first eval of pop. From f9848393668cb2e6192bf18ff3e7421690081dcd Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 30 Mar 2011 15:52:23 +0200 Subject: [PATCH 70/81] * eoOpContainer: call to eoGenOp::apply instead of operator() to avoid calling reserve --- eo/src/eoOpContainer.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/eo/src/eoOpContainer.h b/eo/src/eoOpContainer.h index 70252a49..d295f0ce 100644 --- a/eo/src/eoOpContainer.h +++ b/eo/src/eoOpContainer.h @@ -100,6 +100,8 @@ public: void apply(eoPopulator& _pop) { + _pop.reserve( this->max_production() ); + position_type pos = _pop.tellp(); for (size_t i = 0; i < rates.size(); ++i) { _pop.seekp(pos); @@ -108,7 +110,11 @@ public: // try // { // apply it to all the guys in the todo std::list - (*ops[i])(_pop); + + //(*ops[i])(_pop); + + ops[i]->apply(_pop); + // } // check for out of individuals and do nothing with that... // catch(eoPopulator::OutOfIndividuals&) From 211de53623f0820152998b2bda2de5a914436019 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 4 May 2011 17:28:46 +0200 Subject: [PATCH 71/81] * eoReduceSplit.h: bad syntax in using eo::log --- eo/src/eoReduceSplit.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eo/src/eoReduceSplit.h b/eo/src/eoReduceSplit.h index 758f48bd..db119032 100644 --- a/eo/src/eoReduceSplit.h +++ b/eo/src/eoReduceSplit.h @@ -270,7 +270,7 @@ public: { if (t_rate <= 0.5) { - eo::log << eo:warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51" << std::endl; + eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51" << std::endl; t_rate = 0.51; } if (t_rate > 1) From 688003e559fa40adc9c3e53b68ffdc0956839c32 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Wed, 4 May 2011 17:29:45 +0200 Subject: [PATCH 72/81] * pyeo: updated pyeo in order to make it works --- eo/src/pyeo/CMakeLists.txt | 35 +++++++++++++++++++++------------- eo/src/pyeo/Makefile | 4 ++-- eo/src/pyeo/pickle.h | 6 +++--- eo/src/pyeo/random_numbers.cpp | 2 +- 4 files changed, 28 insertions(+), 19 deletions(-) diff --git a/eo/src/pyeo/CMakeLists.txt b/eo/src/pyeo/CMakeLists.txt index 6e23de10..22909f02 100644 --- a/eo/src/pyeo/CMakeLists.txt +++ b/eo/src/pyeo/CMakeLists.txt @@ -16,13 +16,19 @@ # ---------------------------------------------------------------------------- # change this to your local boost-path -SET(BOOST_PATH "C:/development/libs/os/boost/boost_1_33_1") - +# SET(BOOST_PATH "C:/development/libs/os/boost/boost_1_33_1") # ---------------------------------------------------------------------------- +CMAKE_MINIMUM_REQUIRED(VERSION 2.8) + PROJECT(PyEO) +FIND_PACKAGE(Boost 1.42 COMPONENTS program_options python) + +INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) +LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) + # python IF(APPLE) @@ -38,10 +44,10 @@ IF(APPLE) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) # boost - SET(BOOST_INC ${BOOST_PATH}) - INCLUDE_DIRECTORIES(${BOOST_INC}) - SET(BOOST_LIBRARY ${BOOST_PATH}/libs/python/build/bin-stage/) - SET(BOOSTPYTHON_LIBRARY ${BOOST_LIBRARY}/boost_python) + # SET(BOOST_INC ${BOOST_PATH}) + # INCLUDE_DIRECTORIES(${BOOST_INC}) + # SET(BOOST_LIBRARY ${BOOST_PATH}/libs/python/build/bin-stage/) + # SET(BOOSTPYTHON_LIBRARY ${BOOST_LIBRARY}/boost_python) # osx internal find_library(APPLE_CARBON Carbon) @@ -54,10 +60,10 @@ ELSE(APPLE) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) # boost - SET(BOOST_INC ${BOOST_PATH}) - INCLUDE_DIRECTORIES(${BOOST_INC}) - SET(BOOST_LIBRARY ${BOOST_PATH}/libs/python/build/bin-stage/) - SET(BOOSTPYTHON_LIBRARY ${BOOST_LIBRARY}/boost_python) + # SET(BOOST_INC ${BOOST_PATH}) + # INCLUDE_DIRECTORIES(${BOOST_INC}) + # SET(BOOST_LIBRARY ${BOOST_PATH}/libs/python/build/bin-stage/) + # SET(BOOSTPYTHON_LIBRARY ${BOOST_LIBRARY}/boost_python) ENDIF(APPLE) @@ -84,8 +90,11 @@ ENDIF(WIN32 AND NOT CYGWIN) # add the libs if(APPLE) - target_link_libraries(PyEO ${APPLE_CARBON} ${PYTHON_LIBRARY} ${BOOSTPYTHON_LIBRARY} ) + target_link_libraries(PyEO ${APPLE_CARBON} ${PYTHON_LIBRARY} ${Boost_LIBRARIES} + #${BOOSTPYTHON_LIBRARY} + ) else(APPLE) - target_link_libraries(PyEO ${PYTHON_LIBRARY} ${BOOSTPYTHON_LIBRARY} ) + target_link_libraries(PyEO ${PYTHON_LIBRARY} ${Boost_LIBRARIES} + #${BOOSTPYTHON_LIBRARY} + ) endif(APPLE) - diff --git a/eo/src/pyeo/Makefile b/eo/src/pyeo/Makefile index ca2d762b..6953249c 100644 --- a/eo/src/pyeo/Makefile +++ b/eo/src/pyeo/Makefile @@ -10,7 +10,7 @@ CPPFLAGS = -Wall -O2 #-g #-O2 LDFLAGS = COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) -INC=-I/usr/include/python2.4 -I.. -I../.. -ftemplate-depth-50 +INC=-I/usr/include/python2.6 -I.. -I../.. -ftemplate-depth-50 OBJECTS=eoFunctorStore.o PyEO.o abstract1.o algos.o \ random_numbers.o geneticOps.o selectOne.o continuators.o\ @@ -26,7 +26,7 @@ clean: rm PyEO/*.so *.o test/*.pyc PyEO/PyEO.so: $(OBJECTS) - $(LINK) -o PyEO/PyEO.so $(OBJECTS) -lboost_python -lpython2.4 ${LIB} -shared #-lstlport + $(LINK) -o PyEO/PyEO.so $(OBJECTS) -lboost_python -lpython2.6 ${LIB} -shared #-lstlport eoFunctorStore.o: ../eoFunctorStore.h ../eoFunctorStore.cpp $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) diff --git a/eo/src/pyeo/pickle.h b/eo/src/pyeo/pickle.h index 20399364..ee2706fb 100644 --- a/eo/src/pyeo/pickle.h +++ b/eo/src/pyeo/pickle.h @@ -21,9 +21,9 @@ #ifndef PICKLE_H #define PICKLE_h -#ifndef WIN32 -#include -#endif +// #ifndef WIN32 +// #include +// #endif #include #include diff --git a/eo/src/pyeo/random_numbers.cpp b/eo/src/pyeo/random_numbers.cpp index 7b6a483a..aa9e4feb 100644 --- a/eo/src/pyeo/random_numbers.cpp +++ b/eo/src/pyeo/random_numbers.cpp @@ -99,7 +99,7 @@ void random_numbers() .def("rand", &eoRng::rand) .def("rand_max", &eoRng::rand_max) .def("reseed", &eoRng::reseed) - .def("uniform", &eoRng::uniform) + // .def("uniform", &eoRng::uniform) .def("normal", normal) .def("negexp", &eoRng::negexp) .def("to_string", rng_to_string) From 4f70128ab7a6858503ff852eeeaf80d5052bb47a Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 15 Mar 2011 16:39:46 +0100 Subject: [PATCH 73/81] * eoLogger: forgot to close opened file --- eo/src/utils/eoLogger.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/eo/src/utils/eoLogger.cpp b/eo/src/utils/eoLogger.cpp index a729d0cf..ff6f8407 100644 --- a/eo/src/utils/eoLogger.cpp +++ b/eo/src/utils/eoLogger.cpp @@ -67,7 +67,9 @@ eoLogger::eoLogger() } eoLogger::~eoLogger() -{} +{ + if (_fd > 2) { ::close(_fd); } +} std::string eoLogger::className() const { From 7dcc7b62dd2cc836e7e5a64998eefb51e6c213f8 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Tue, 15 Mar 2011 18:05:45 +0100 Subject: [PATCH 74/81] * edoSampler: sampler method protected --- edo/src/edoSampler.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/edo/src/edoSampler.h b/edo/src/edoSampler.h index efd77649..4a0d9244 100644 --- a/edo/src/edoSampler.h +++ b/edo/src/edoSampler.h @@ -51,8 +51,6 @@ public: // virtual EOType operator()( D& ) = 0 (provided by eoUF< A1, R >) - virtual EOType sample( D& ) = 0; - EOType operator()( D& distrib ) { unsigned int size = distrib.size(); @@ -84,6 +82,10 @@ public: return solution; } +protected: + + virtual EOType sample( D& ) = 0; + private: //edoBounderNo _dummy_bounder; From 8bec56f469c0acc7ad5cdf6414ea41121cded7b6 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 5 May 2011 11:47:30 +0200 Subject: [PATCH 75/81] * pyeo cmake config file --- eo/src/pyeo/CMakeLists.txt | 91 ++++++++++++++------------------------ 1 file changed, 33 insertions(+), 58 deletions(-) diff --git a/eo/src/pyeo/CMakeLists.txt b/eo/src/pyeo/CMakeLists.txt index 22909f02..b08bf459 100644 --- a/eo/src/pyeo/CMakeLists.txt +++ b/eo/src/pyeo/CMakeLists.txt @@ -3,98 +3,73 @@ # PyEO - cmake version # # -------------------------------------------------------------------------- -# +# # Hochschule fuer Gestaltung und Kunst Zuerich # Studienberreich Interaction Design # http://interaction.hgkz.ch -# +# # -------------------------------------------------------------------------- -# +# # prog: max rheiner;xohm@users.sourceforge.net # date: 7/27/2007 (m/d/y) # # ---------------------------------------------------------------------------- -# change this to your local boost-path -# SET(BOOST_PATH "C:/development/libs/os/boost/boost_1_33_1") - -# ---------------------------------------------------------------------------- - CMAKE_MINIMUM_REQUIRED(VERSION 2.8) PROJECT(PyEO) FIND_PACKAGE(Boost 1.42 COMPONENTS program_options python) +FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) + LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) # python IF(APPLE) - - # python - # osx can have several version of python, on dif places -# SET(PYTHON /Library/Frameworks/Python.framework/Versions/) -# SET(PYTHON_VERSION 2.4) -# SET(PYTHON_INCLUDE_PATH "${PYTHON}${PYTHON_VERSION}/include/python${PYTHON_VERSION}" CACHE STRING "") -# SET(PYTHON_BINARY ${PYTHON}${PYTHON_VERSION}/bin/python${PYTHON_VERSION} CACHE STRING "") -# SET(PYTHON_LIBRARIES ${PYTHON}${PYTHON_VERSION}/lib/python${PYTHON_VERSION}/config CACHE STRING "") -# SET(PYTHON_DEBUG_LIBRARIES ${PYTHON}${PYTHON_VERSION}/lib/python${PYTHON_VERSION}/config CACHE STRING "") - FIND_PACKAGE(PythonLibs) - INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) - - # boost - # SET(BOOST_INC ${BOOST_PATH}) - # INCLUDE_DIRECTORIES(${BOOST_INC}) - # SET(BOOST_LIBRARY ${BOOST_PATH}/libs/python/build/bin-stage/) - # SET(BOOSTPYTHON_LIBRARY ${BOOST_LIBRARY}/boost_python) - - # osx internal - find_library(APPLE_CARBON Carbon) - -ELSE(APPLE) - # windows/unix - - # python - FIND_PACKAGE(PythonLibs) - INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) - - # boost - # SET(BOOST_INC ${BOOST_PATH}) - # INCLUDE_DIRECTORIES(${BOOST_INC}) - # SET(BOOST_LIBRARY ${BOOST_PATH}/libs/python/build/bin-stage/) - # SET(BOOSTPYTHON_LIBRARY ${BOOST_LIBRARY}/boost_python) - + # osx internal + FIND_LIBRARY(APPLE_CARBON Carbon) ENDIF(APPLE) -# includes +# includes INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) INCLUDE_DIRECTORIES(../) # source SET(PYEO_SRCS -../eoFunctorStore.cpp -PyEO.cpp abstract1.cpp algos.cpp random_numbers.cpp geneticOps.cpp selectOne.cpp continuators.cpp -reduce.cpp replacement.cpp selectors.cpp breeders.cpp mergers.cpp valueParam.cpp -perf2worth.cpp monitors.cpp statistics.cpp -) + ../eoFunctorStore.cpp + PyEO.cpp + abstract1.cpp + algos.cpp + random_numbers.cpp + geneticOps.cpp + selectOne.cpp + continuators.cpp + reduce.cpp + replacement.cpp + selectors.cpp + breeders.cpp + mergers.cpp + valueParam.cpp + perf2worth.cpp + monitors.cpp + statistics.cpp + ) # shared library ADD_LIBRARY(PyEO MODULE ${PYEO_SRCS}) # python 2.5 must have pyd IF(WIN32 AND NOT CYGWIN) - SET_TARGET_PROPERTIES(PyEO PROPERTIES SUFFIX ".pyd") + SET_TARGET_PROPERTIES(PyEO PROPERTIES SUFFIX ".pyd") ENDIF(WIN32 AND NOT CYGWIN) # add the libs -if(APPLE) - target_link_libraries(PyEO ${APPLE_CARBON} ${PYTHON_LIBRARY} ${Boost_LIBRARIES} - #${BOOSTPYTHON_LIBRARY} - ) -else(APPLE) - target_link_libraries(PyEO ${PYTHON_LIBRARY} ${Boost_LIBRARIES} - #${BOOSTPYTHON_LIBRARY} - ) -endif(APPLE) +IF(APPLE) + TARGET_LINK_LIBRARIES(PyEO ${APPLE_CARBON} ${PYTHON_LIBRARY} ${Boost_LIBRARIES}) +ELSE(APPLE) + TARGET_LINK_LIBRARIES(PyEO ${PYTHON_LIBRARY} ${Boost_LIBRARIES}) +ENDIF(APPLE) From 62157e28eec9ee00df91f929d6b9ba645c28b6fa Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 5 May 2011 16:53:02 +0200 Subject: [PATCH 76/81] * pyeo/CMakeLists.txt: auto find cpp files --- eo/src/pyeo/CMakeLists.txt | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/eo/src/pyeo/CMakeLists.txt b/eo/src/pyeo/CMakeLists.txt index b08bf459..626d0201 100644 --- a/eo/src/pyeo/CMakeLists.txt +++ b/eo/src/pyeo/CMakeLists.txt @@ -19,7 +19,7 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.8) PROJECT(PyEO) -FIND_PACKAGE(Boost 1.42 COMPONENTS program_options python) +FIND_PACKAGE(Boost 1.42 COMPONENTS python) FIND_PACKAGE(PythonLibs) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) @@ -39,28 +39,15 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) INCLUDE_DIRECTORIES(../) # source -SET(PYEO_SRCS +FILE(GLOB SOURCES *.cpp) + +SET(EO_SOURCES ../eoFunctorStore.cpp - PyEO.cpp - abstract1.cpp - algos.cpp - random_numbers.cpp - geneticOps.cpp - selectOne.cpp - continuators.cpp - reduce.cpp - replacement.cpp - selectors.cpp - breeders.cpp - mergers.cpp - valueParam.cpp - perf2worth.cpp - monitors.cpp - statistics.cpp + ../utils/eoLogger.cpp ) # shared library -ADD_LIBRARY(PyEO MODULE ${PYEO_SRCS}) +ADD_LIBRARY(PyEO MODULE ${SOURCES} ${EO_SOURCES}) # python 2.5 must have pyd IF(WIN32 AND NOT CYGWIN) From 8457e39efe75c910841c696a5bdb18b65d679dfb Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 5 May 2011 16:53:31 +0200 Subject: [PATCH 77/81] * pyeo/PyEO.cpp: renamed module name --- eo/src/pyeo/PyEO.cpp | 142 +++++++++++++++++++++---------------------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/eo/src/pyeo/PyEO.cpp b/eo/src/pyeo/PyEO.cpp index 40d36310..7c3f1b93 100644 --- a/eo/src/pyeo/PyEO.cpp +++ b/eo/src/pyeo/PyEO.cpp @@ -23,7 +23,6 @@ #include "PyEO.h" #include - using namespace std; //using namespace boost::python; @@ -35,28 +34,28 @@ bool PyFitness::dominates(const PyFitness& oth) const bool dom = false; for (unsigned i = 0; i < nObjectives(); ++i) - { - int objective = objective_info[i]; - - if (objective == 0) // ignore - continue; - - bool maxim = objective > 0; - - double aval = maxim? (*this)[i] : -(*this)[i]; - double bval = maxim? oth[i] : -oth[i]; - - if (fabs(aval - bval) > tol()) - { - if (aval < bval) { - return false; // cannot dominate + int objective = objective_info[i]; + + if (objective == 0) // ignore + continue; + + bool maxim = objective > 0; + + double aval = maxim? (*this)[i] : -(*this)[i]; + double bval = maxim? oth[i] : -oth[i]; + + if (fabs(aval - bval) > tol()) + { + if (aval < bval) + { + return false; // cannot dominate + } + // else aval < bval + dom = true; // for the moment: goto next objective + } + //else they're equal in this objective, goto next } - // else aval < bval - dom = true; // for the moment: goto next objective - } - //else they're equal in this objective, goto next - } return dom; } @@ -76,22 +75,22 @@ struct pyPop_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getstate(const eoPop& _pop) { - boost::python::list entries; - for (unsigned i = 0; i != _pop.size(); ++i) - entries.append( PyEO_pickle_suite::getstate(_pop[i]) ); + boost::python::list entries; + for (unsigned i = 0; i != _pop.size(); ++i) + entries.append( PyEO_pickle_suite::getstate(_pop[i]) ); - return boost::python::make_tuple(boost::python::object(_pop.size()), entries); + return boost::python::make_tuple(boost::python::object(_pop.size()), entries); } static void setstate( eoPop& _pop, boost::python::tuple pickled) { - int sz = boost::python::extract(pickled[0]); - boost::python::list entries = boost::python::list(pickled[1]); - _pop.resize(sz); - for (unsigned i = 0; i != _pop.size(); ++i) - { - PyEO_pickle_suite::setstate(_pop[i], boost::python::tuple(entries[i]) ); - } + int sz = boost::python::extract(pickled[0]); + boost::python::list entries = boost::python::list(pickled[1]); + _pop.resize(sz); + for (unsigned i = 0; i != _pop.size(); ++i) + { + PyEO_pickle_suite::setstate(_pop[i], boost::python::tuple(entries[i]) ); + } } }; @@ -109,21 +108,21 @@ void pop_shuffle(eoPop& pop) { pop.shuffle(); } void translate_index_error(index_error const& e) { - PyErr_SetString(PyExc_IndexError, e.what.c_str()); + PyErr_SetString(PyExc_IndexError, e.what.c_str()); } PyEO& pop_getitem(eoPop& pop, boost::python::object key) { boost::python::extract x(key); if (!x.check()) - throw index_error("Slicing not allowed"); + throw index_error("Slicing not allowed"); int i = x(); if (static_cast(i) >= pop.size()) - { - throw index_error("Index out of bounds"); - } + { + throw index_error("Index out of bounds"); + } return pop[i]; } @@ -131,14 +130,14 @@ void pop_setitem(eoPop& pop, boost::python::object key, PyEO& value) { boost::python::extract x(key); if (!x.check()) - throw index_error("Slicing not allowed"); + throw index_error("Slicing not allowed"); int i = x(); if (static_cast(i) >= pop.size()) - { - throw index_error("Index out of bounds"); - } + { + throw index_error("Index out of bounds"); + } pop[i] = value; } @@ -163,35 +162,35 @@ extern void perf2worth(); extern void monitors(); extern void statistics(); -BOOST_PYTHON_MODULE(PyEO) +BOOST_PYTHON_MODULE(libPyEO) { using namespace boost::python; boost::python::register_exception_translator(&translate_index_error); boost::python::class_("EO") - .add_property("fitness", &PyEO::getFitness, &PyEO::setFitness) - .add_property("genome", &PyEO::getGenome, &PyEO::setGenome) - .def_pickle(PyEO_pickle_suite()) - .def("invalidate", &PyEO::invalidate) - .def("invalid", &PyEO::invalid) - .def("__str__", &PyEO::to_string) - ; + .add_property("fitness", &PyEO::getFitness, &PyEO::setFitness) + .add_property("genome", &PyEO::getGenome, &PyEO::setGenome) + .def_pickle(PyEO_pickle_suite()) + .def("invalidate", &PyEO::invalidate) + .def("invalid", &PyEO::invalid) + .def("__str__", &PyEO::to_string) + ; boost::python::class_ >("eoPop", init<>() ) - .def( init< unsigned, eoInit& >()[with_custodian_and_ward<1,3>()] ) - .def("append", &eoPop::append, "docstring?") - .def("__str__", to_string >) - .def("__len__", pop_size) - .def("sort", pop_sort ) - .def("shuffle", pop_shuffle) - .def("__getitem__", pop_getitem, return_internal_reference<>() ) - .def("__setitem__", pop_setitem) - .def("best", &eoPop::best_element, return_internal_reference<>() ) - .def("push_back", pop_push_back) - .def("resize", pop_resize) - .def_pickle(pyPop_pickle_suite()) - ; + .def( init< unsigned, eoInit& >()[with_custodian_and_ward<1,3>()] ) + .def("append", &eoPop::append, "docstring?") + .def("__str__", to_string >) + .def("__len__", pop_size) + .def("sort", pop_sort ) + .def("shuffle", pop_shuffle) + .def("__getitem__", pop_getitem, return_internal_reference<>() ) + .def("__setitem__", pop_setitem) + .def("best", &eoPop::best_element, return_internal_reference<>() ) + .def("push_back", pop_push_back) + .def("resize", pop_resize) + .def_pickle(pyPop_pickle_suite()) + ; // Other definitions in different compilation units, @@ -215,17 +214,18 @@ BOOST_PYTHON_MODULE(PyEO) // The traits class class_("PyFitness"); - def("nObjectives", &PyFitness::nObjectives); - def("tol", &PyFitness::tol); - def("maximizing", &PyFitness::maximizing); - def("setObjectivesSize", &PyFitness::setObjectivesSize); - def("setObjectivesValue", &PyFitness::setObjectivesValue); - def("dominates", dominates); + def("nObjectives", &PyFitness::nObjectives); + def("tol", &PyFitness::tol); + def("maximizing", &PyFitness::maximizing); + def("setObjectivesSize", &PyFitness::setObjectivesSize); + def("setObjectivesValue", &PyFitness::setObjectivesValue); + def("dominates", dominates); } // to avoid having to build with libeo.a -ostream & operator << ( ostream& _os, const eoPrintable& _o ) { - _o.printOn(_os); - return _os; +ostream & operator << ( ostream& _os, const eoPrintable& _o ) +{ + _o.printOn(_os); + return _os; }; From 56c6edab045702927394e17f4d4b377e00d0a581 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 5 May 2011 16:54:00 +0200 Subject: [PATCH 78/81] * indentations + whitespace cleanup --- eo/src/CMakeLists.txt | 17 +- eo/src/EO.h | 43 +- eo/src/PO.h | 12 +- eo/src/do/Readme | 6 +- eo/src/do/make_algo_easea.h | 188 ++++---- eo/src/do/make_algo_scalar.h | 182 +++---- eo/src/do/make_checkpoint.h | 179 ++++--- eo/src/do/make_checkpoint_FDC.h | 184 +++---- eo/src/do/make_checkpoint_assembled.h | 4 +- eo/src/do/make_continue.h | 64 +-- eo/src/do/make_general_replacement.h | 66 +-- eo/src/do/make_pop.h | 20 +- eo/src/do/make_run.h | 2 +- eo/src/eoCellularEasyEA.h | 132 ++--- eo/src/eoCloneOps.h | 11 +- eo/src/eoCombinedContinue.h | 7 +- eo/src/eoCombinedInit.h | 9 +- eo/src/eoConstrictedVariableWeightVelocity.h | 37 +- eo/src/eoConstrictedVelocity.h | 35 +- eo/src/eoContinue.h | 11 +- eo/src/eoCounter.h | 66 +-- eo/src/eoCtrlCContinue.cpp | 12 +- eo/src/eoCtrlCContinue.h | 19 +- eo/src/eoDetSelect.h | 32 +- eo/src/eoDetTournamentSelect.h | 17 +- eo/src/eoDistribUpdater.h | 6 +- eo/src/eoDistribution.h | 6 +- eo/src/eoDualFitness.h | 53 +-- eo/src/eoEDA.h | 7 +- eo/src/eoEasyEA.h | 11 +- eo/src/eoEasyPSO.h | 56 +-- eo/src/eoEvalContinue.h | 24 +- eo/src/eoEvalCounterThrowException.h | 11 +- eo/src/eoEvalFunc.h | 8 +- eo/src/eoEvalFuncCounter.h | 6 +- eo/src/eoEvalFuncCounterBounder.h | 22 +- eo/src/eoEvalFuncPtr.h | 11 +- eo/src/eoEvalTimeThrowException.h | 4 +- eo/src/eoEvalUserTimeThrowException.h | 4 +- eo/src/eoExceptions.h | 4 +- eo/src/eoExtendedVelocity.h | 63 ++- eo/src/eoFactory.h | 46 +- eo/src/eoFitContinue.h | 18 +- eo/src/eoFitnessScalingSelect.h | 15 +- eo/src/eoFixedInertiaWeightedVelocity.h | 25 +- eo/src/eoFlOrBinOp.h | 52 +- eo/src/eoFlOrMonOp.h | 22 +- eo/src/eoFlOrQuadOp.h | 54 +-- eo/src/eoFunctor.h | 26 +- eo/src/eoG3Replacement.h | 30 +- eo/src/eoGaussRealWeightUp.h | 2 +- eo/src/eoGenContinue.h | 73 ++- eo/src/eoGenOp.h | 16 +- eo/src/eoGeneralBreeder.h | 17 +- eo/src/eoInit.h | 28 +- eo/src/eoInitializer.h | 11 +- eo/src/eoInt.h | 2 +- eo/src/eoIntegerVelocity.h | 53 +-- eo/src/eoInvalidateOps.h | 2 +- eo/src/eoLinearTopology.h | 64 ++- eo/src/eoMGGReplacement.h | 36 +- eo/src/eoMerge.h | 42 +- eo/src/eoMergeReduce.h | 12 +- eo/src/eoNDSorting.h | 234 ++++----- eo/src/eoNeighborhood.h | 15 +- eo/src/eoObject.h | 21 +- eo/src/eoOneToOneBreeder.h | 61 ++- eo/src/eoOp.h | 10 +- eo/src/eoOpContainer.h | 9 +- eo/src/eoOpSelMason.h | 116 ++--- eo/src/eoOrderXover.h | 114 ++--- eo/src/eoParticleBestInit.h | 5 +- eo/src/eoParticleFullInitializer.h | 45 +- eo/src/eoPeriodicContinue.h | 23 +- eo/src/eoPersistent.cpp | 2 +- eo/src/eoPersistent.h | 6 +- eo/src/eoPop.h | 151 +++--- eo/src/eoPopEvalFunc.h | 19 +- eo/src/eoPopulator.h | 1 - eo/src/eoPrintable.cpp | 7 +- eo/src/eoPrintable.h | 7 +- eo/src/eoPropGAGenOp.h | 22 +- eo/src/eoProportionalCombinedOp.h | 20 +- eo/src/eoProportionalSelect.h | 28 +- eo/src/eoRandomRealWeightUp.h | 2 +- eo/src/eoRandomSelect.h | 3 +- eo/src/eoRanking.h | 52 +- eo/src/eoRankingSelect.h | 10 +- eo/src/eoRealBoundModifier.h | 30 +- eo/src/eoReduce.h | 184 +++---- eo/src/eoReduceMerge.h | 40 +- eo/src/eoReduceMergeReduce.h | 100 ++-- eo/src/eoReduceSplit.h | 102 ++-- eo/src/eoReplacement.h | 32 +- eo/src/eoRingTopology.h | 86 ++-- eo/src/eoSGA.h | 38 +- eo/src/eoSGAGenOp.h | 24 +- eo/src/eoSGATransform.h | 88 ++-- eo/src/eoSIGContinue.cpp | 16 +- eo/src/eoSIGContinue.h | 18 +- eo/src/eoSTLFunctor.h | 3 +- eo/src/eoScalarFitness.h | 4 +- eo/src/eoScalarFitnessAssembled.cpp | 13 +- eo/src/eoScalarFitnessAssembled.h | 13 +- eo/src/eoSecondsElapsedContinue.h | 19 +- eo/src/eoSelect.h | 6 +- eo/src/eoSelectFactory.h | 86 ++-- eo/src/eoSelectFromWorth.h | 7 +- eo/src/eoSelectMany.h | 20 +- eo/src/eoSelectNumber.h | 16 +- eo/src/eoSelectOne.h | 6 +- eo/src/eoSelectPerc.h | 18 +- eo/src/eoSequentialSelect.h | 12 +- eo/src/eoSharing.h | 56 +-- eo/src/eoSharingSelect.h | 16 +- eo/src/eoShiftMutation.h | 35 +- eo/src/eoSigBinaryFlight.h | 20 +- eo/src/eoSimpleEDA.h | 37 +- eo/src/eoSocialNeighborhood.h | 3 +- eo/src/eoStandardFlight.h | 2 +- eo/src/eoStandardVelocity.h | 47 +- eo/src/eoStarTopology.h | 26 +- eo/src/eoSteadyFitContinue.h | 59 ++- eo/src/eoStochTournamentSelect.h | 17 +- eo/src/eoStochasticUniversalSelect.h | 20 +- eo/src/eoSurviveAndDie.h | 105 ++-- eo/src/eoSwapMutation.h | 41 +- eo/src/eoSyncEasyPSO.h | 68 +-- eo/src/eoTopology.h | 14 +- eo/src/eoTransform.h | 6 +- eo/src/eoTruncSelect.h | 18 +- eo/src/eoTruncatedSelectMany.h | 62 +-- eo/src/eoTruncatedSelectOne.h | 48 +- eo/src/eoVariableInertiaWeightedVelocity.h | 33 +- eo/src/eoVariableLengthCrossover.h | 157 +++--- eo/src/eoVariableLengthMutation.h | 7 +- eo/src/eoVector.h | 4 +- eo/src/eoVectorParticle.h | 18 +- eo/src/eoVelocity.h | 5 +- eo/src/eoVelocityInit.h | 3 +- eo/src/eoWeightUpdater.h | 2 +- eo/src/es.h | 8 +- eo/src/es/CMAParams.cpp | 189 ++++---- eo/src/es/CMAParams.h | 25 +- eo/src/es/CMAState.cpp | 477 +++++++++---------- eo/src/es/CMAState.h | 43 +- eo/src/es/eig.cpp | 207 ++++---- eo/src/es/eig.h | 12 +- eo/src/es/eoCMABreed.h | 56 +-- eo/src/es/eoCMAInit.h | 12 +- eo/src/es/eoEsGlobalXover.h | 36 +- eo/src/es/eoEsMutate.h | 4 +- eo/src/es/eoEsMutationInit.h | 2 +- eo/src/es/eoEsStandardXover.h | 20 +- eo/src/es/eoNormalMutation.h | 81 ++-- eo/src/es/eoReal.h | 2 +- eo/src/es/eoRealAtomXover.h | 30 +- eo/src/es/eoRealInitBounded.h | 13 +- eo/src/es/eoRealOp.h | 332 ++++++------- eo/src/es/eoSBXcross.h | 66 ++- eo/src/es/make_algo_scalar_es.cpp | 13 +- eo/src/es/make_algo_scalar_real.cpp | 7 +- eo/src/es/make_checkpoint_es.cpp | 22 +- eo/src/es/make_checkpoint_real.cpp | 12 +- eo/src/es/make_continue_es.cpp | 14 +- eo/src/es/make_continue_real.cpp | 8 +- eo/src/es/make_es.h | 22 +- eo/src/es/make_genotype_real.h | 2 +- eo/src/es/make_op.h | 28 +- eo/src/es/make_op_es.cpp | 7 +- eo/src/es/make_op_es.h | 6 +- eo/src/es/make_op_real.cpp | 6 +- eo/src/es/make_op_real.h | 8 +- eo/src/es/make_pop_es.cpp | 14 +- eo/src/es/make_pop_real.cpp | 8 +- eo/src/es/make_real.h | 16 +- eo/src/es/make_run_es.cpp | 13 +- eo/src/es/make_run_real.cpp | 7 +- eo/src/es/matrices.h | 17 +- eo/src/ga.h | 4 +- eo/src/ga/Readme | 7 +- eo/src/ga/eoBit.h | 8 +- eo/src/ga/eoBitOp.h | 105 ++-- eo/src/ga/eoBitOpFactory.h | 227 +++++---- eo/src/ga/eoBoolFlip.h | 4 +- eo/src/ga/eoPBILAdditive.h | 56 +-- eo/src/ga/eoPBILDistrib.h | 28 +- eo/src/ga/eoPBILOrg.h | 16 +- eo/src/ga/make_PBILdistrib.h | 14 +- eo/src/ga/make_PBILupdate.h | 8 +- eo/src/ga/make_algo_scalar_ga.cpp | 9 +- eo/src/ga/make_checkpoint_ga.cpp | 14 +- eo/src/ga/make_continue_ga.cpp | 10 +- eo/src/ga/make_ga.h | 8 +- eo/src/ga/make_genotype_ga.cpp | 8 +- eo/src/ga/make_genotype_ga.h | 16 +- eo/src/ga/make_op.h | 36 +- eo/src/ga/make_op_ga.cpp | 9 +- eo/src/ga/make_pop_ga.cpp | 8 +- eo/src/ga/make_run_ga.cpp | 9 +- eo/src/gp/eoParseTree.h | 28 +- eo/src/gp/eoParseTreeDepthInit.h | 216 ++++----- eo/src/gp/eoParseTreeOp.h | 214 ++++----- eo/src/gp/eoStParseTreeDepthInit.h | 178 +++---- eo/src/gp/eoStParseTreeOp.h | 218 ++++----- eo/src/gp/node_pool.h | 36 +- eo/src/gp/parse_tree.h | 424 ++++++++--------- eo/src/other/eoString.h | 5 +- eo/src/pyeo/Makefile | 30 +- eo/src/pyeo/Makefile.rpm | 6 +- eo/src/pyeo/PyEO.h | 142 +++--- eo/src/pyeo/PyEO/__init__.py | 104 ++-- eo/src/pyeo/abstract1.cpp | 24 +- eo/src/pyeo/algos.cpp | 160 ++++--- eo/src/pyeo/breeders.cpp | 30 +- eo/src/pyeo/continuators.cpp | 70 +-- eo/src/pyeo/def_abstract_functor.h | 170 +++---- eo/src/pyeo/geneticOps.cpp | 116 ++--- eo/src/pyeo/mergers.cpp | 7 +- eo/src/pyeo/monitors.cpp | 65 ++- eo/src/pyeo/perf2worth.cpp | 63 +-- eo/src/pyeo/pickle.h | 21 +- eo/src/pyeo/random_numbers.cpp | 58 +-- eo/src/pyeo/reduce.cpp | 6 +- eo/src/pyeo/replacement.cpp | 24 +- eo/src/pyeo/selectOne.cpp | 43 +- eo/src/pyeo/selectors.cpp | 5 +- eo/src/pyeo/statistics.cpp | 18 +- eo/src/pyeo/test/maxone.py | 77 ++- eo/src/pyeo/test/test_breeders.py | 9 +- eo/src/pyeo/test/test_mo.py | 62 +-- eo/src/pyeo/test/test_pickling.py | 35 +- eo/src/pyeo/test/test_populator.py | 30 +- eo/src/pyeo/test/test_reduce.py | 10 +- eo/src/pyeo/test/test_selectone.py | 74 ++- eo/src/pyeo/test/test_sga.py | 61 +-- eo/src/pyeo/test/test_transform.py | 81 ++-- eo/src/pyeo/valueParam.cpp | 43 +- eo/src/pyeo/valueParam.h | 32 +- eo/src/utils/ChangeLog | 40 +- eo/src/utils/compatibility.h | 18 +- eo/src/utils/eoCheckPoint.h | 44 +- eo/src/utils/eoData.h | 1 - eo/src/utils/eoDistance.h | 30 +- eo/src/utils/eoFDCStat.h | 39 +- eo/src/utils/eoFeasibleRatioStat.h | 10 +- eo/src/utils/eoFileMonitor.cpp | 21 +- eo/src/utils/eoFileMonitor.h | 24 +- eo/src/utils/eoFileSnapshot.h | 54 +-- eo/src/utils/eoFuncPtrStat.h | 8 +- eo/src/utils/eoGnuplot1DSnapshot.h | 4 +- eo/src/utils/eoHowMany.h | 2 +- eo/src/utils/eoIntBounds.cpp | 40 +- eo/src/utils/eoIntBounds.h | 170 +++---- eo/src/utils/eoLogger.cpp | 40 +- eo/src/utils/eoLogger.h | 46 +- eo/src/utils/eoMOFitnessStat.h | 2 +- eo/src/utils/eoMonitor.h | 4 +- eo/src/utils/eoOStreamMonitor.cpp | 2 +- eo/src/utils/eoOStreamMonitor.h | 14 +- eo/src/utils/eoParallel.cpp | 54 +-- eo/src/utils/eoParam.h | 13 +- eo/src/utils/eoParser.cpp | 79 ++- eo/src/utils/eoParser.h | 2 +- eo/src/utils/eoParserLogger.cpp | 20 +- eo/src/utils/eoParserLogger.h | 10 +- eo/src/utils/eoPopStat.h | 14 +- eo/src/utils/eoRNG.cpp | 1 - eo/src/utils/eoRNG.h | 2 +- eo/src/utils/eoRealBounds.cpp | 94 ++-- eo/src/utils/eoRealBounds.h | 166 +++---- eo/src/utils/eoRealVectorBounds.h | 118 ++--- eo/src/utils/eoScalarFitnessStat.h | 8 +- eo/src/utils/eoStat.h | 17 +- eo/src/utils/eoState.cpp | 27 +- eo/src/utils/eoStdoutMonitor.h | 15 +- eo/src/utils/eoTimeCounter.h | 18 +- eo/src/utils/eoTimedMonitor.h | 32 +- eo/src/utils/eoUniformInit.h | 18 +- eo/src/utils/eoUpdatable.h | 20 +- eo/src/utils/eoUpdater.cpp | 6 +- eo/src/utils/eoUpdater.h | 8 +- eo/src/utils/make_help.cpp | 2 +- eo/src/utils/pipecom.cpp | 86 ++-- eo/src/utils/selectors.h | 14 +- 285 files changed, 5968 insertions(+), 6123 deletions(-) diff --git a/eo/src/CMakeLists.txt b/eo/src/CMakeLists.txt index 70e2c755..97b74866 100644 --- a/eo/src/CMakeLists.txt +++ b/eo/src/CMakeLists.txt @@ -11,14 +11,15 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) SET(EO_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) SET(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH}) -SET (EO_SOURCES eoFunctorStore.cpp - eoPersistent.cpp - eoPrintable.cpp - eoCtrlCContinue.cpp - eoScalarFitnessAssembled.cpp - eoSIGContinue.cpp) +SET(EO_SOURCES + eoFunctorStore.cpp + eoPersistent.cpp + eoPrintable.cpp + eoCtrlCContinue.cpp + eoScalarFitnessAssembled.cpp + eoSIGContinue.cpp + ) - ADD_LIBRARY(eo STATIC ${EO_SOURCES}) INSTALL(TARGETS eo ARCHIVE DESTINATION lib COMPONENT libraries) @@ -42,6 +43,6 @@ ADD_SUBDIRECTORY(ga) ADD_SUBDIRECTORY(gp) ADD_SUBDIRECTORY(other) ADD_SUBDIRECTORY(utils) +ADD_SUBDIRECTORY(pyeo) ###################################################################################### - diff --git a/eo/src/EO.h b/eo/src/EO.h index 2c43b2c8..f904559d 100644 --- a/eo/src/EO.h +++ b/eo/src/EO.h @@ -40,17 +40,17 @@ */ /** EO is the base class for objects with a fitness. - + Those evolvable objects are the subjects of evolution. EOs have only got a fitness, which at the same time needs to be only an object with the operation less than (<) defined. Fitness says how good is the object; evolution or change of these objects is left to the - genetic operators. - + genetic operators. + A fitness less than another means a worse fitness, in whatever the context; thus, fitness is always maximized; although it can - be minimized with a proper definition of the < operator. - + be minimized with a proper definition of the < operator. + A fitness can be invalid if undefined, trying to read an invalid fitness will raise an error. @ref Operators that effectively modify EO objects must invalidate them. @@ -123,23 +123,23 @@ public: * @throw runtime_std::exception If a valid object can't be read. */ virtual void readFrom(std::istream& _is) { - + // the new version of the reafFrom function. - // It can distinguish between valid and invalid fitness values. + // It can distinguish between valid and invalid fitness values. std::string fitness_str; int pos = _is.tellg(); - _is >> fitness_str; + _is >> fitness_str; - if (fitness_str == "INVALID") - { - invalidFitness = true; - } - else - { - invalidFitness = false; - _is.seekg(pos); // rewind - _is >> repFitness; - } + if (fitness_str == "INVALID") + { + invalidFitness = true; + } + else + { + invalidFitness = false; + _is.seekg(pos); // rewind + _is >> repFitness; + } } /** @@ -151,13 +151,13 @@ public: // the latest version of the code. Very similar to the old code if (invalid()) { - _os << "INVALID "; + _os << "INVALID "; } else { - _os << repFitness << ' '; + _os << repFitness << ' '; } - + } //@} @@ -171,4 +171,3 @@ private: #endif /** @} */ - diff --git a/eo/src/PO.h b/eo/src/PO.h index 1cb4f50a..0c246135 100644 --- a/eo/src/PO.h +++ b/eo/src/PO.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // PO.h // (c) OPAC 2007 @@ -43,11 +43,11 @@ template < class F > class PO:public EO < F > public: - #if defined(__CUDACC__) - typedef typename EO < F >::Fitness Fitness; - #else - typedef typename PO::Fitness Fitness; - #endif + #if defined(__CUDACC__) + typedef typename EO < F >::Fitness Fitness; + #else + typedef typename PO::Fitness Fitness; + #endif /** Default constructor. Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor. diff --git a/eo/src/do/Readme b/eo/src/do/Readme index cd3e5acd..0b3ccd8a 100644 --- a/eo/src/do/Readme +++ b/eo/src/do/Readme @@ -9,11 +9,11 @@ the functions here for eoBit AND eoBit and in EO test dir the t-eoGA.cpp file that is a sample program that uses the whole facility. -All make_XXX.h file define some parser-based constructions of basic +All make_XXX.h file define some parser-based constructions of basic Evolutionary Algorithms components, using state-based memory management (see in src/utils dir, or read the tutorial). -In this src/do dir, the following ***representation indedendent*** code +In this src/do dir, the following ***representation indedendent*** code is defined make_algo_scalar.h The selection/replacement for scalar fitnesses @@ -23,7 +23,7 @@ make_pop.h Init of the population (from an EOT initializer) make_run.h Run the algorithm See also (NOW MOVED TO util DIR, as it was useful everywhere) -make_help.cpp Help on demand (+ status file) +make_help.cpp Help on demand (+ status file) Note: ----- diff --git a/eo/src/do/make_algo_easea.h b/eo/src/do/make_algo_easea.h index a6522ef9..c432c1e8 100644 --- a/eo/src/do/make_algo_easea.h +++ b/eo/src/do/make_algo_easea.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_easea.h // (c) Marc Schoenauer and Pierre Collet, 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 @@ -81,18 +81,18 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF eoParamParamType & ppSelect = selectionParam.value(); // std::pair > eoSelectOne* select ; - if (ppSelect.first == std::string("DetTour")) + if (ppSelect.first == std::string("DetTour")) { unsigned detSize; if (!ppSelect.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; - detSize = 2; - // put back 2 in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; + detSize = 2; + // put back 2 in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("2")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) detSize = atoi(ppSelect.second[0].c_str()); select = new eoDetTournamentSelect(detSize); } @@ -100,57 +100,57 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF { double p; if (!ppSelect.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; - p = 1; - // put back p in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("1")); - } - else // parameter passed by user as DetTour(T) - p = atof(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; + p = 1; + // put back p in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("1")); + } + else // parameter passed by user as DetTour(T) + p = atof(ppSelect.second[0].c_str()); + select = new eoStochTournamentSelect(p); } else if (ppSelect.first == std::string("Ranking")) { double p,e; if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent - { - p = atof(ppSelect.second[0].c_str()); - e = atof(ppSelect.second[1].c_str()); - } - else if (ppSelect.second.size()==1) // 1 parameter: pressure - { - std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; - e = 1; - ppSelect.second.push_back(std::string("1")); - p = atof(ppSelect.second[0].c_str()); - } + { + p = atof(ppSelect.second[0].c_str()); + e = atof(ppSelect.second[1].c_str()); + } + else if (ppSelect.second.size()==1) // 1 parameter: pressure + { + std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; + e = 1; + ppSelect.second.push_back(std::string("1")); + p = atof(ppSelect.second[0].c_str()); + } else // no parameters ... or garbage - { - std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; - p=2; - e=1; - // put back in parameter for consistency (and status file) - ppSelect.second.resize(2); // just in case - ppSelect.second[0] = (std::string("2")); - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; + p=2; + e=1; + // put back in parameter for consistency (and status file) + ppSelect.second.resize(2); // just in case + ppSelect.second[0] = (std::string("2")); + ppSelect.second[1] = (std::string("1")); + } // check for authorized values // pressure in (0,1] if ( (p<=1) || (p>2) ) - { - std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n"; - p=2; - ppSelect.second[0] = (std::string("2")); - } + { + std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n"; + p=2; + ppSelect.second[0] = (std::string("2")); + } // exponent >0 if (e<=0) - { - std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; - e=1; - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; + e=1; + ppSelect.second[1] = (std::string("1")); + } // now we're OK eoPerf2Worth & p2w = _state.storeFunctor( new eoRanking(p,e) ); select = new eoRouletteWorthSelect(p2w); @@ -159,13 +159,13 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF { bool b; if (ppSelect.second.size() == 0) // no argument -> default = ordered - { - b=true; - // put back in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("ordered")); - } + { + b=true; + // put back in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("ordered")); + } else - b = !(ppSelect.second[0] == std::string("unordered")); + b = !(ppSelect.second[0] == std::string("unordered")); select = new eoSequentialSelect(b); } else if (ppSelect.first == std::string("EliteSequential")) // Best first, one after the other in random order afterwards @@ -188,7 +188,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF _state.storeFunctor(select); - // the number of offspring + // the number of offspring eoValueParam& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); ///////////////////////////////////////////////////// @@ -196,7 +196,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF ///////////////////////////////////////////////////// /** Replacement type - high level: predefined replacements - * ESComma : + * ESComma : * elite = 0 * surviveParents=0 (no reduce) * surviveOffspring=100% (no reduce) @@ -208,8 +208,8 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF * GGA : generational GA - idem ESComma except for * offspringRate = 100% * all reducers are unused - * - * SSGA(T/t) : Steady-State GA + * + * SSGA(T/t) : Steady-State GA * surviveParents = 1.0 - offspringRate * reduceFinal = DetTour(T>1) ou StochTour(0.5 & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF // the tournament size if (!replacementParam.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl; - tSize = 2; - // put back 2 in parameter for consistency (and status file) - replacementParam.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl; + tSize = 2; + // put back 2 in parameter for consistency (and status file) + replacementParam.second.push_back(std::string("2")); } else { - t = atof(replacementParam.second[0].c_str()); - if (t>=2) - { // build the appropriate deafult value - tSize = unsigned(t); - } - else - { - throw std::runtime_error("Sorry, only deterministic tournament available at the moment"); - } + t = atof(replacementParam.second[0].c_str()); + if (t>=2) + { // build the appropriate deafult value + tSize = unsigned(t); + } + else + { + throw std::runtime_error("Sorry, only deterministic tournament available at the moment"); + } } - ptReplace = new eoMGGReplacement(-surviveParents, tSize); + ptReplace = new eoMGGReplacement(-surviveParents, tSize); _state.storeFunctor(ptReplace); } else { // until the end of what was the only loop/switch - + // the default deafult values eoHowMany elite (0.0); bool strongElitism (false); @@ -283,12 +283,12 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF // ---------- General if (replacementParam.first == std::string("General")) { - ; // defaults OK + ; // defaults OK } // ---------- ESComma else if (replacementParam.first == std::string("ESComma")) { - ; // OK too + ; // OK too } // ---------- ESPlus else if (replacementParam.first == std::string("ESPlus")) @@ -298,16 +298,16 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF // ---------- Generational else if (replacementParam.first == std::string("Generational")) { - ; // OK too (we should check nb of offspring) + ; // OK too (we should check nb of offspring) } // ---------- EP else if (replacementParam.first == std::string("EP")) { if (!replacementParam.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl; - // put back 6 in parameter for consistency (and status file) - replacementParam.second.push_back(std::string("6")); + std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl; + // put back 6 in parameter for consistency (and status file) + replacementParam.second.push_back(std::string("6")); } // by coincidence, the syntax for the EP reducer is the same than here: reduceFinalType = replacementParam; @@ -318,28 +318,28 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF { if (!replacementParam.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl; - // put back 2 in parameter for consistency (and status file) - replacementParam.second.push_back(std::string("2")); - reduceParentType = eoParamParamType(std::string("DetTour(2)")); + std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl; + // put back 2 in parameter for consistency (and status file) + replacementParam.second.push_back(std::string("2")); + reduceParentType = eoParamParamType(std::string("DetTour(2)")); } else { - t = atof(replacementParam.second[0].c_str()); - if (t>=2) - { // build the appropriate deafult value - reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")"); - } - else // check for [0.5,1] will be made in make_general_replacement - { // build the appropriate deafult value - reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")"); - } + t = atof(replacementParam.second[0].c_str()); + if (t>=2) + { // build the appropriate deafult value + reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")"); + } + else // check for [0.5,1] will be made in make_general_replacement + { // build the appropriate deafult value + reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")"); + } } - // + // surviveParents = eoHowMany(-1); surviveOffspring = eoHowMany(1); } - else // no replacement recognized + else // no replacement recognized { throw std::runtime_error("Invalid replacement type " + replacementParam.first); } @@ -353,7 +353,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF /////////////////////////////// // the general breeder /////////////////////////////// - eoGeneralBreeder *breed = + eoGeneralBreeder *breed = new eoGeneralBreeder(*select, _op, offspringRateParam.value()); _state.storeFunctor(breed); @@ -381,7 +381,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF template eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op) { - do_make_algo_scalar( _parser, _state, *(new eoPopLoopEval(_eval)), _continue, _op); + do_make_algo_scalar( _parser, _state, *(new eoPopLoopEval(_eval)), _continue, _op); } diff --git a/eo/src/do/make_algo_scalar.h b/eo/src/do/make_algo_scalar.h index 5a63eb9d..52df8f4f 100644 --- a/eo/src/do/make_algo_scalar.h +++ b/eo/src/do/make_algo_scalar.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar.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 @@ -84,42 +84,42 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc if (_dist == NULL) comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)"; else - comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e), Sharing(sigma_share) or Sequential(ordered/unordered)"; + comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e), Sharing(sigma_share) or Sequential(ordered/unordered)"; eoValueParam& selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection", comment, 'S', "Evolution Engine"); eoParamParamType & ppSelect = selectionParam.value(); // std::pair > eoSelectOne* select ; - if (ppSelect.first == std::string("DetTour")) + if (ppSelect.first == std::string("DetTour")) { unsigned detSize; if (!ppSelect.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; - detSize = 2; - // put back 2 in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; + detSize = 2; + // put back 2 in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("2")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) detSize = atoi(ppSelect.second[0].c_str()); select = new eoDetTournamentSelect(detSize); } - else if (ppSelect.first == std::string("Sharing")) + else if (ppSelect.first == std::string("Sharing")) { double nicheSize; if (!ppSelect.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl; - nicheSize = 0.5; - // put back 2 in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("0.5")); + std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl; + nicheSize = 0.5; + // put back 2 in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("0.5")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) nicheSize = atof(ppSelect.second[0].c_str()); - if (_dist == NULL) // no distance + if (_dist == NULL) // no distance throw std::runtime_error("You didn't specify a distance when calling make_algo_scalar and using sharing"); select = new eoSharingSelect(nicheSize, *_dist); } @@ -127,57 +127,57 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc { double p; if (!ppSelect.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; - p = 1; - // put back p in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("1")); - } - else // parameter passed by user as DetTour(T) - p = atof(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; + p = 1; + // put back p in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("1")); + } + else // parameter passed by user as DetTour(T) + p = atof(ppSelect.second[0].c_str()); + select = new eoStochTournamentSelect(p); } else if (ppSelect.first == std::string("Ranking")) { double p,e; if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent - { - p = atof(ppSelect.second[0].c_str()); - e = atof(ppSelect.second[1].c_str()); - } - else if (ppSelect.second.size()==1) // 1 parameter: pressure - { - std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; - e = 1; - ppSelect.second.push_back(std::string("1")); - p = atof(ppSelect.second[0].c_str()); - } + { + p = atof(ppSelect.second[0].c_str()); + e = atof(ppSelect.second[1].c_str()); + } + else if (ppSelect.second.size()==1) // 1 parameter: pressure + { + std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; + e = 1; + ppSelect.second.push_back(std::string("1")); + p = atof(ppSelect.second[0].c_str()); + } else // no parameters ... or garbage - { - std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; - p=2; - e=1; - // put back in parameter for consistency (and status file) - ppSelect.second.resize(2); // just in case - ppSelect.second[0] = (std::string("2")); - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; + p=2; + e=1; + // put back in parameter for consistency (and status file) + ppSelect.second.resize(2); // just in case + ppSelect.second[0] = (std::string("2")); + ppSelect.second[1] = (std::string("1")); + } // check for authorized values // pressure in (0,1] if ( (p<=1) || (p>2) ) - { - std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n"; - p=2; - ppSelect.second[0] = (std::string("2")); - } + { + std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n"; + p=2; + ppSelect.second[0] = (std::string("2")); + } // exponent >0 if (e<=0) - { - std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; - e=1; - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; + e=1; + ppSelect.second[1] = (std::string("1")); + } // now we're OK eoPerf2Worth & p2w = _state.storeFunctor( new eoRanking(p,e) ); select = new eoRouletteWorthSelect(p2w); @@ -186,13 +186,13 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc { bool b; if (ppSelect.second.size() == 0) // no argument -> default = ordered - { - b=true; - // put back in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("ordered")); - } + { + b=true; + // put back in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("ordered")); + } else - b = !(ppSelect.second[0] == std::string("unordered")); + b = !(ppSelect.second[0] == std::string("unordered")); select = new eoSequentialSelect(b); } else if (ppSelect.first == std::string("Roulette")) // no argument (yet) @@ -211,7 +211,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc _state.storeFunctor(select); - // the number of offspring + // the number of offspring eoValueParam& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); // the replacement @@ -231,16 +231,16 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc else if (ppReplace.first == std::string("EPTour")) { unsigned detSize; - + if (!ppReplace.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl; - detSize = 6; - // put back in parameter for consistency (and status file) - ppReplace.second.push_back(std::string("6")); - } - else // parameter passed by user as EPTour(T) - detSize = atoi(ppSelect.second[0].c_str()); + { + std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl; + detSize = 6; + // put back in parameter for consistency (and status file) + ppReplace.second.push_back(std::string("6")); + } + else // parameter passed by user as EPTour(T) + detSize = atoi(ppSelect.second[0].c_str()); replace = new eoEPReplacement(detSize); } @@ -251,32 +251,32 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc else if (ppReplace.first == std::string("SSGADet")) { unsigned detSize; - + if (!ppReplace.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl; - detSize = 2; - // put back in parameter for consistency (and status file) - ppReplace.second.push_back(std::string("2")); - } - else // parameter passed by user as SSGADet(T) - detSize = atoi(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl; + detSize = 2; + // put back in parameter for consistency (and status file) + ppReplace.second.push_back(std::string("2")); + } + else // parameter passed by user as SSGADet(T) + detSize = atoi(ppSelect.second[0].c_str()); + replace = new eoSSGADetTournamentReplacement(detSize); } else if (ppReplace.first == std::string("SSGAStoch")) { double p; if (!ppReplace.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl; - p = 1; - // put back in parameter for consistency (and status file) - ppReplace.second.push_back(std::string("1")); - } - else // parameter passed by user as SSGADet(T) - p = atof(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl; + p = 1; + // put back in parameter for consistency (and status file) + ppReplace.second.push_back(std::string("1")); + } + else // parameter passed by user as SSGADet(T) + p = atof(ppSelect.second[0].c_str()); + replace = new eoSSGAStochTournamentReplacement(p); } else @@ -294,10 +294,10 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc eoReplacement *replaceTmp = replace; replace = new eoWeakElitistReplacement(*replaceTmp); _state.storeFunctor(replace); - } + } // the general breeder - eoGeneralBreeder *breed = + eoGeneralBreeder *breed = new eoGeneralBreeder(*select, _op, offspringRateParam.value()); _state.storeFunctor(breed); diff --git a/eo/src/do/make_checkpoint.h b/eo/src/do/make_checkpoint.h index 37cf5d0a..7958ed5b 100644 --- a/eo/src/do/make_checkpoint.h +++ b/eo/src/do/make_checkpoint.h @@ -129,7 +129,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu eoValueParam& eraseParam = _parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); - bool dirOK = false; // not tested yet + bool dirOK = false; // not tested yet @@ -179,15 +179,15 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - bestStat = new eoBestFitnessStat; + bestStat = new eoBestFitnessStat; - // store it + // store it - _state.storeFunctor(bestStat); + _state.storeFunctor(bestStat); - // add it to the checkpoint + // add it to the checkpoint - checkpoint->add(*bestStat); + checkpoint->add(*bestStat); } @@ -203,15 +203,15 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - averageStat = new eoAverageStat; + averageStat = new eoAverageStat; - // store it + // store it - _state.storeFunctor(averageStat); + _state.storeFunctor(averageStat); - // add it to the checkpoint + // add it to the checkpoint - checkpoint->add(*averageStat); + checkpoint->add(*averageStat); } @@ -223,19 +223,19 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu eoSecondMomentStats *secondStat = NULL; - if ( printBestParam.value() || fileBestParam.value() ) // we need it for screen output or file output + if ( printBestParam.value() || fileBestParam.value() ) // we need it for screen output or file output { - secondStat = new eoSecondMomentStats; + secondStat = new eoSecondMomentStats; - // store it + // store it - _state.storeFunctor(secondStat); + _state.storeFunctor(secondStat); - // add it to the checkpoint + // add it to the checkpoint - checkpoint->add(*secondStat); + checkpoint->add(*secondStat); } @@ -255,15 +255,15 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - popStat = new eoSortedPopStat; + popStat = new eoSortedPopStat; - // store it + // store it - _state.storeFunctor(popStat); + _state.storeFunctor(popStat); - // add it to the checkpoint + // add it to the checkpoint - checkpoint->add(*popStat); + checkpoint->add(*popStat); } @@ -287,7 +287,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu bool needStdoutMonitor = printBestParam.value() - || printPopParam.value() ; + || printPopParam.value() ; @@ -297,53 +297,53 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + eoStdoutMonitor *monitor = new eoStdoutMonitor(false); - _state.storeFunctor(monitor); + _state.storeFunctor(monitor); - // when called by the checkpoint (i.e. at every generation) + // when called by the checkpoint (i.e. at every generation) - checkpoint->add(*monitor); + checkpoint->add(*monitor); - // the monitor will output a series of parameters: add them + // the monitor will output a series of parameters: add them - monitor->add(*generationCounter); + monitor->add(*generationCounter); - if (useEvalParam.value()) // we want nb of evaluations + if (useEvalParam.value()) // we want nb of evaluations - monitor->add(_eval); + monitor->add(_eval); - if (useTimeParam.value()) // we want time + if (useTimeParam.value()) // we want time - { + { - tCounter = new eoTimeCounter; + tCounter = new eoTimeCounter; - _state.storeFunctor(tCounter); + _state.storeFunctor(tCounter); - checkpoint->add(*tCounter); + checkpoint->add(*tCounter); - monitor->add(*tCounter); + monitor->add(*tCounter); - } + } - if (printBestParam.value()) + if (printBestParam.value()) - { + { - monitor->add(*bestStat); + monitor->add(*bestStat); - monitor->add(*secondStat); + monitor->add(*secondStat); - } + } - if ( printPopParam.value()) + if ( printPopParam.value()) - monitor->add(*popStat); + monitor->add(*popStat); } @@ -353,9 +353,9 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu if ( ( fileBestParam.value() || plotBestParam.value() || - plotHistogramParam.value() ) + plotHistogramParam.value() ) - && !dirOK ) // just in case we add something before + && !dirOK ) // just in case we add something before dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE @@ -367,41 +367,41 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu #ifdef _MSVC - std::string stmp = dirNameParam.value() + "\best.xg"; + std::string stmp = dirNameParam.value() + "\best.xg"; #else - std::string stmp = dirNameParam.value() + "/best.xg"; + std::string stmp = dirNameParam.value() + "/best.xg"; #endif - eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); + eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); - // save and give to checkpoint + // save and give to checkpoint - _state.storeFunctor(fileMonitor); + _state.storeFunctor(fileMonitor); - checkpoint->add(*fileMonitor); + checkpoint->add(*fileMonitor); - // and feed with some statistics + // and feed with some statistics - fileMonitor->add(*generationCounter); + fileMonitor->add(*generationCounter); - fileMonitor->add(_eval); + fileMonitor->add(_eval); - if (tCounter) // we want the time as well + if (tCounter) // we want the time as well - { + { - // std::cout << "On met timecounter\n"; + // std::cout << "On met timecounter\n"; - fileMonitor->add(*tCounter); + fileMonitor->add(*tCounter); - } + } - fileMonitor->add(*bestStat); + fileMonitor->add(*bestStat); - fileMonitor->add(*secondStat); + fileMonitor->add(*secondStat); } @@ -413,33 +413,33 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - std::string stmp = dirNameParam.value() + "/gnu_best.xg"; + std::string stmp = dirNameParam.value() + "/gnu_best.xg"; - eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); + eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); - // save and give to checkpoint + // save and give to checkpoint - _state.storeFunctor(gnuMonitor); + _state.storeFunctor(gnuMonitor); - checkpoint->add(*gnuMonitor); + checkpoint->add(*gnuMonitor); - // and feed with some statistics + // and feed with some statistics - if (useEvalParam.value()) // do we want eval as X coordinate + if (useEvalParam.value()) // do we want eval as X coordinate - gnuMonitor->add(_eval); + gnuMonitor->add(_eval); - else if (tCounter) // or time? + else if (tCounter) // or time? - gnuMonitor->add(*tCounter); + gnuMonitor->add(*tCounter); - else // default: generation + else // default: generation - gnuMonitor->add(*generationCounter); + gnuMonitor->add(*generationCounter); - gnuMonitor->add(*bestStat); + gnuMonitor->add(*bestStat); - gnuMonitor->add(*averageStat); + gnuMonitor->add(*averageStat); } @@ -451,25 +451,25 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; + eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; - _state.storeFunctor(fitStat); + _state.storeFunctor(fitStat); - checkpoint->add(*fitStat); + checkpoint->add(*fitStat); - // a gnuplot-based monitor for snapshots: needs a dir name + // a gnuplot-based monitor for snapshots: needs a dir name - eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); + eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); - _state.storeFunctor(fitSnapshot); + _state.storeFunctor(fitSnapshot); - // add any stat that is a std::vector to it + // add any stat that is a std::vector to it - fitSnapshot->add(*fitStat); + fitSnapshot->add(*fitStat); - // and of course add it to the checkpoint + // and of course add it to the checkpoint - checkpoint->add(*fitSnapshot); + checkpoint->add(*fitSnapshot); } @@ -499,7 +499,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE @@ -537,7 +537,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE @@ -570,4 +570,3 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu #endif - diff --git a/eo/src/do/make_checkpoint_FDC.h b/eo/src/do/make_checkpoint_FDC.h index 1c2ec493..33c7f720 100644 --- a/eo/src/do/make_checkpoint_FDC.h +++ b/eo/src/do/make_checkpoint_FDC.h @@ -70,7 +70,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoValueParam& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk"); // shoudl we empty it if exists eoValueParam& eraseParam = _parser.createParam(false, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); - bool dirOK = false; // not tested yet + bool dirOK = false; // not tested yet ///////////////////////////////////////// // now some statistics on the population: @@ -98,11 +98,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() ) // we need the bestStat for at least one of the 3 above { - bestStat = new eoBestFitnessStat; - // store it - _state.storeFunctor(bestStat); - // add it to the checkpoint - checkpoint->add(*bestStat); + bestStat = new eoBestFitnessStat; + // store it + _state.storeFunctor(bestStat); + // add it to the checkpoint + checkpoint->add(*bestStat); } // Average fitness alone @@ -110,11 +110,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoAverageStat *averageStat = NULL; // do we need averageStat? if ( plotBestParam.value() ) // we need it for gnuplot output { - averageStat = new eoAverageStat; - // store it - _state.storeFunctor(averageStat); - // add it to the checkpoint - checkpoint->add(*averageStat); + averageStat = new eoAverageStat; + // store it + _state.storeFunctor(averageStat); + // add it to the checkpoint + checkpoint->add(*averageStat); } // Second moment stats: average and stdev @@ -122,11 +122,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoSecondMomentStats *secondStat = NULL; if ( printBestParam.value() ) // we need it for sreen output { - secondStat = new eoSecondMomentStats; - // store it - _state.storeFunctor(secondStat); - // add it to the checkpoint - checkpoint->add(*secondStat); + secondStat = new eoSecondMomentStats; + // store it + _state.storeFunctor(secondStat); + // add it to the checkpoint + checkpoint->add(*secondStat); } @@ -136,11 +136,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoValueParam& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output"); if ( printPopParam.value() ) // we do want pop dump { - popStat = new eoSortedPopStat("Dump of whole population"); - // store it - _state.storeFunctor(popStat); - // add it to the checkpoint - checkpoint->add(*popStat); + popStat = new eoSortedPopStat("Dump of whole population"); + // store it + _state.storeFunctor(popStat); + // add it to the checkpoint + checkpoint->add(*popStat); } @@ -152,14 +152,14 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoFDCStat *fdcStat = NULL; if ( printFDCParam.value() || plotFDCParam.value() ) // we need FDCStat { - // need first an object to compute the distances - here Hamming dist. - eoQuadDistance *dist = new eoQuadDistance; - _state.storeFunctor(dist); - fdcStat = new eoFDCStat(*dist); - // storeFunctor it - _state.storeFunctor(fdcStat); - // add it to the checkpoint - checkpoint->add(*fdcStat); + // need first an object to compute the distances - here Hamming dist. + eoQuadDistance *dist = new eoQuadDistance; + _state.storeFunctor(dist); + fdcStat = new eoFDCStat(*dist); + // storeFunctor it + _state.storeFunctor(fdcStat); + // add it to the checkpoint + checkpoint->add(*fdcStat); } // do we wnat some histogram of fitnesses snpashots? @@ -170,95 +170,95 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval /////////////// // do we want an eoStdoutMonitor? bool needStdoutMonitor = printBestParam.value() || printFDCParam.value() - || printPopParam.value() ; + || printPopParam.value() ; // The Stdout monitor will print parameters to the screen ... if ( needStdoutMonitor ) { - eoStdoutMonitor *monitor = new eoStdoutMonitor(false); - _state.storeFunctor(monitor); + eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + _state.storeFunctor(monitor); - // when called by the checkpoint (i.e. at every generation) - checkpoint->add(*monitor); + // when called by the checkpoint (i.e. at every generation) + checkpoint->add(*monitor); - // the monitor will output a series of parameters: add them - monitor->add(*generationCounter); - if (useEvalParam.value()) // we want nb of evaluations - monitor->add(_eval); - if (printBestParam.value()) - { - monitor->add(*bestStat); - monitor->add(*secondStat); - } - if (printFDCParam.value()) - monitor->add(*fdcStat); - if ( printPopParam.value()) - monitor->add(*popStat); + // the monitor will output a series of parameters: add them + monitor->add(*generationCounter); + if (useEvalParam.value()) // we want nb of evaluations + monitor->add(_eval); + if (printBestParam.value()) + { + monitor->add(*bestStat); + monitor->add(*secondStat); + } + if (printFDCParam.value()) + monitor->add(*fdcStat); + if ( printPopParam.value()) + monitor->add(*popStat); } // first handle the dir test - if we need at least one file if ( ( fileBestParam.value() || plotBestParam.value() || - plotFDCParam.value() || plotHistogramParam.value() ) - && !dirOK ) // just in case we add something before + plotFDCParam.value() || plotHistogramParam.value() ) + && !dirOK ) // just in case we add something before dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE if (fileBestParam.value()) // A file monitor for best & secondMoment { - std::string stmp = dirNameParam.value() + "/best.xg"; - eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); - // save and give to checkpoint - _state.storeFunctor(fileMonitor); - checkpoint->add(*fileMonitor); - // and feed with some statistics - fileMonitor->add(*generationCounter); - fileMonitor->add(_eval); - fileMonitor->add(*bestStat); - fileMonitor->add(*secondStat); + std::string stmp = dirNameParam.value() + "/best.xg"; + eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); + // save and give to checkpoint + _state.storeFunctor(fileMonitor); + checkpoint->add(*fileMonitor); + // and feed with some statistics + fileMonitor->add(*generationCounter); + fileMonitor->add(_eval); + fileMonitor->add(*bestStat); + fileMonitor->add(*secondStat); } if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average { - std::string stmp = dirNameParam.value() + "_gnu_best.xg"; - eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); - // save and give to checkpoint - _state.storeFunctor(gnuMonitor); - checkpoint->add(*gnuMonitor); - // and feed with some statistics - if (useEvalParam.value()) - gnuMonitor->add(_eval); - else - gnuMonitor->add(*generationCounter); - gnuMonitor->add(*bestStat); - gnuMonitor->add(*averageStat); + std::string stmp = dirNameParam.value() + "_gnu_best.xg"; + eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); + // save and give to checkpoint + _state.storeFunctor(gnuMonitor); + checkpoint->add(*gnuMonitor); + // and feed with some statistics + if (useEvalParam.value()) + gnuMonitor->add(_eval); + else + gnuMonitor->add(*generationCounter); + gnuMonitor->add(*bestStat); + gnuMonitor->add(*averageStat); } if (plotFDCParam.value()) // a specific plot monitor for FDC { - // first into a file (it adds everything ti itself - eoFDCFileSnapshot *fdcFileSnapshot = new eoFDCFileSnapshot(*fdcStat, dirNameParam.value()); - _state.storeFunctor(fdcFileSnapshot); - // then to a Gnuplot monitor - eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot); - _state.storeFunctor(fdcGnuplot); + // first into a file (it adds everything ti itself + eoFDCFileSnapshot *fdcFileSnapshot = new eoFDCFileSnapshot(*fdcStat, dirNameParam.value()); + _state.storeFunctor(fdcFileSnapshot); + // then to a Gnuplot monitor + eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot); + _state.storeFunctor(fdcGnuplot); - // and of course add them to the checkPoint - checkpoint->add(*fdcFileSnapshot); - checkpoint->add(*fdcGnuplot); + // and of course add them to the checkPoint + checkpoint->add(*fdcFileSnapshot); + checkpoint->add(*fdcGnuplot); } // historgram? if (plotHistogramParam.value()) // want to see how the fitness is spread? { - eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; - _state.storeFunctor(fitStat); - checkpoint->add(*fitStat); - // a gnuplot-based monitor for snapshots: needs a dir name - eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); - _state.storeFunctor(fitSnapshot); - // add any stat that is a std::vector to it - fitSnapshot->add(*fitStat); - // and of course add it to the checkpoint - checkpoint->add(*fitSnapshot); + eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; + _state.storeFunctor(fitStat); + checkpoint->add(*fitStat); + // a gnuplot-based monitor for snapshots: needs a dir name + eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); + _state.storeFunctor(fitSnapshot); + // add any stat that is a std::vector to it + fitSnapshot->add(*fitStat); + // and of course add it to the checkpoint + checkpoint->add(*fitSnapshot); } ////////////////////////////////// @@ -273,7 +273,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval { // first make sure dirName is OK if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX ); std::string stmp = dirNameParam.value() + "/generations"; @@ -288,7 +288,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval { // first make sure dirName is OK if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE std::string stmp = dirNameParam.value() + "/time"; eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); diff --git a/eo/src/do/make_checkpoint_assembled.h b/eo/src/do/make_checkpoint_assembled.h index 656b1376..26463fab 100644 --- a/eo/src/do/make_checkpoint_assembled.h +++ b/eo/src/do/make_checkpoint_assembled.h @@ -49,7 +49,7 @@ bool testDirRes(std::string _dirName, bool _erase); /////////////////// The checkpoint and other I/O ////////////// -/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! +/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! * * * @ingroup Builders @@ -153,7 +153,7 @@ eoCheckPoint& do_make_checkpoint_assembled(eoParser& _parser, eoState& _sta _state.storeFunctor(fitStat); checkpoint->add(*fitStat); #ifdef HAVE_GNUPLOT - // a gnuplot-based monitor for snapshots: needs a dir name + // a gnuplot-based monitor for snapshots: needs a dir name eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirName); _state.storeFunctor(fitSnapshot); // add any stat that is a vector to it diff --git a/eo/src/do/make_continue.h b/eo/src/do/make_continue.h index 62862438..27b4e945 100644 --- a/eo/src/do/make_continue.h +++ b/eo/src/do/make_continue.h @@ -55,7 +55,7 @@ It can then be instantiated, and compiled on its own for a given EOType template eoCombinedContinue * make_combinedContinue(eoCombinedContinue *_combined, eoContinue *_cont) { - if (_combined) // already exists + if (_combined) // already exists _combined->add(*_cont); else _combined = new eoCombinedContinue(*_cont); @@ -81,10 +81,10 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu if (maxGenParam.value()) // positive: -> define and store { - eoGenContinue *genCont = new eoGenContinue(maxGenParam.value()); - _state.storeFunctor(genCont); - // and "add" to combined - continuator = make_combinedContinue(continuator, genCont); + eoGenContinue *genCont = new eoGenContinue(maxGenParam.value()); + _state.storeFunctor(genCont); + // and "add" to combined + continuator = make_combinedContinue(continuator, genCont); } // the steadyGen continue - only if user imput @@ -92,12 +92,12 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion"); if (_parser.isItThere(steadyGenParam)) { - eoSteadyFitContinue *steadyCont = new eoSteadyFitContinue - (minGenParam.value(), steadyGenParam.value()); - // store - _state.storeFunctor(steadyCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, steadyCont); + eoSteadyFitContinue *steadyCont = new eoSteadyFitContinue + (minGenParam.value(), steadyGenParam.value()); + // store + _state.storeFunctor(steadyCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, steadyCont); } // Same thing with Eval - but here default value is 0 @@ -108,10 +108,10 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu if (maxEvalParam.value()) // positive: -> define and store { - eoEvalContinue *evalCont = new eoEvalContinue(_eval, maxEvalParam.value()); - _state.storeFunctor(evalCont); - // and "add" to combined - continuator = make_combinedContinue(continuator, evalCont); + eoEvalContinue *evalCont = new eoEvalContinue(_eval, maxEvalParam.value()); + _state.storeFunctor(evalCont); + // and "add" to combined + continuator = make_combinedContinue(continuator, evalCont); } /* // the steadyEval continue - only if user imput @@ -119,12 +119,12 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion"); if (_parser.isItThere(steadyGenParam)) { - eoSteadyGenContinue *steadyCont = new eoSteadyFitContinue - (minGenParam.value(), steadyGenParam.value()); - // store - _state.storeFunctor(steadyCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, steadyCont); + eoSteadyGenContinue *steadyCont = new eoSteadyFitContinue + (minGenParam.value(), steadyGenParam.value()); + // store + _state.storeFunctor(steadyCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, steadyCont); } */ // the target fitness @@ -132,12 +132,12 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& targetFitnessParam = _parser.createParam(double(0.0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion"); if (_parser.isItThere(targetFitnessParam)) { - fitCont = new eoFitContinue - (targetFitnessParam.value()); - // store - _state.storeFunctor(fitCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, fitCont); + fitCont = new eoFitContinue + (targetFitnessParam.value()); + // store + _state.storeFunctor(fitCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, fitCont); } #ifndef _MSC_VER @@ -146,11 +146,11 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion"); if (ctrlCParam.value()) { - ctrlCCont = new eoCtrlCContinue; - // store - _state.storeFunctor(ctrlCCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, ctrlCCont); + ctrlCCont = new eoCtrlCContinue; + // store + _state.storeFunctor(ctrlCCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, ctrlCCont); } #endif diff --git a/eo/src/do/make_general_replacement.h b/eo/src/do/make_general_replacement.h index 4f1f52e8..1d42345c 100644 --- a/eo/src/do/make_general_replacement.h +++ b/eo/src/do/make_general_replacement.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_general_replacement.h // (c) Marc Schoenauer and Pierre Collet, 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 @@ -49,8 +49,8 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) eoReduce * ptReduce; // ---------- Deterministic - if ( (_ppReduce.first == std::string("Deterministic")) || - (_ppReduce.first == std::string("Sequential")) + if ( (_ppReduce.first == std::string("Deterministic")) || + (_ppReduce.first == std::string("Sequential")) ) { ptReduce = new eoTruncate; @@ -65,7 +65,7 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) // put back 6 in parameter for consistency (and status file) _ppReduce.second.push_back(std::string("6")); } - else // parameter passed by user as EP(T) + else // parameter passed by user as EP(T) detSize = atoi(_ppReduce.second[0].c_str()); ptReduce = new eoEPReduce(detSize); } @@ -74,12 +74,12 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) { if (!_ppReduce.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; - detSize = 2; - // put back 2 in parameter for consistency (and status file) - _ppReduce.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; + detSize = 2; + // put back 2 in parameter for consistency (and status file) + _ppReduce.second.push_back(std::string("2")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) detSize = atoi(_ppReduce.second[0].c_str()); ptReduce = new eoDetTournamentTruncate(detSize); } @@ -87,24 +87,24 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) { double p; if (!_ppReduce.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; - p = 1; - // put back p in parameter for consistency (and status file) - _ppReduce.second.push_back(std::string("1")); - } - else // parameter passed by user as DetTour(T) - { - p = atof(_ppReduce.second[0].c_str()); - if ( (p<=0.5) || (p>1) ) - throw std::runtime_error("Stochastic tournament size should be in [0.5,1]"); - } - + { + std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; + p = 1; + // put back p in parameter for consistency (and status file) + _ppReduce.second.push_back(std::string("1")); + } + else // parameter passed by user as DetTour(T) + { + p = atof(_ppReduce.second[0].c_str()); + if ( (p<=0.5) || (p>1) ) + throw std::runtime_error("Stochastic tournament size should be in [0.5,1]"); + } + ptReduce = new eoStochTournamentTruncate(p); } - else if ( (_ppReduce.first == std::string("Uniform")) || - (_ppReduce.first == std::string("Random")) - ) + else if ( (_ppReduce.first == std::string("Uniform")) || + (_ppReduce.first == std::string("Random")) + ) { ptReduce = new eoRandomReduce; } @@ -117,10 +117,10 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) return (*ptReduce); } -/** Helper function that creates a replacement from the class - * eoReduceMergeReduce using 6 parameters +/** Helper function that creates a replacement from the class + * eoReduceMergeReduce using 6 parameters * (after the usual eoState and eoParser) - * + * * eoHowMany _elite the number of elite parents (0 = no elitism) * see below * bool _strongElitism if elite > 0, std::string elitism or weak elitism @@ -136,15 +136,15 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) */ template eoReplacement & make_general_replacement( - eoParser& _parser, eoState& _state, - eoHowMany _elite = eoHowMany(0), + eoParser& _parser, eoState& _state, + eoHowMany _elite = eoHowMany(0), bool _strongElitism = false, eoHowMany _surviveParents = eoHowMany(0.0), eoParamParamType & _reduceParentType = eoParamParamType("Deterministic"), eoHowMany _surviveOffspring = eoHowMany(1.0), eoParamParamType & _reduceOffspringType = eoParamParamType("Deterministic"), eoParamParamType & _reduceFinalType = eoParamParamType("Deterministic") - ) + ) { ///////////////////////////////////////////////////// // the replacement @@ -157,14 +157,14 @@ eoReplacement & make_general_replacement( // reduce the parents eoHowMany surviveParents = _parser.createParam(_surviveParents, "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); - + eoParamParamType & reduceParentType = _parser.createParam(_reduceParentType, "reduceParents", "Parents reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value(); eoReduce & reduceParent = decode_reduce(reduceParentType, _state); // reduce the offspring eoHowMany surviveOffspring = _parser.createParam(_surviveOffspring, "surviveOffspring", "Nb of surviving offspring (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); - + eoParamParamType & reduceOffspringType = _parser.createParam(_reduceOffspringType, "reduceOffspring", "Offspring reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value(); eoReduce & reduceOffspring = decode_reduce(reduceOffspringType, _state); diff --git a/eo/src/do/make_pop.h b/eo/src/do/make_pop.h index 191ab065..c2a1d1a8 100644 --- a/eo/src/do/make_pop.h +++ b/eo/src/do/make_pop.h @@ -59,7 +59,7 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini // random seed eoValueParam& seedParam = _parser.getORcreateParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) - seedParam.value() = time(0); + seedParam.value() = time(0); eoValueParam& popSize = _parser.getORcreateParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine"); // Either load or initialize @@ -82,17 +82,17 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini // the fitness is read in the file: // do only evaluate the pop if the fitness has changed if (recomputeFitnessParam.value()) - { - for (unsigned i=0; i popSize.value()) - { - std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl; - pop.resize(popSize.value()); - } + { + std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl; + pop.resize(popSize.value()); + } } else // nothing loaded from a file { diff --git a/eo/src/do/make_run.h b/eo/src/do/make_run.h index 7e1e2889..485cb870 100644 --- a/eo/src/do/make_run.h +++ b/eo/src/do/make_run.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_run.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 diff --git a/eo/src/eoCellularEasyEA.h b/eo/src/eoCellularEasyEA.h index 98595ae0..fbf3085f 100644 --- a/eo/src/eoCellularEasyEA.h +++ b/eo/src/eoCellularEasyEA.h @@ -8,16 +8,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: cahon@lifl.fr */ @@ -32,26 +32,26 @@ #include /** - The abstract cellular easy algorithm. + The abstract cellular easy algorithm. @ingroup Algorithms */ template class eoCellularEasyEA : public eoAlgo { - + public : - + /** Two constructors */ eoCellularEasyEA (eoContinue & _cont, // Stop. criterion - eoEvalFunc & _eval, // Evaluation function - eoSelectOne & _sel_neigh, // To choose a partner - eoBinOp & _cross, // Cross-over operator - eoMonOp & _mut, // Mutation operator - eoSelectOne & _sel_repl /* Which to keep between the new - child and the old individual ? */ - ) : + eoEvalFunc & _eval, // Evaluation function + eoSelectOne & _sel_neigh, // To choose a partner + eoBinOp & _cross, // Cross-over operator + eoMonOp & _mut, // Mutation operator + eoSelectOne & _sel_repl /* Which to keep between the new + child and the old individual ? */ + ) : cont (_cont), eval (_eval), popEval (_eval), @@ -60,18 +60,18 @@ public : mut (_mut), sel_child (eoSelectFirstOne ()), sel_repl (_sel_repl) { - + } - + eoCellularEasyEA (eoContinue & _cont, - eoEvalFunc & _eval, - eoSelectOne & _sel_neigh, - eoQuadOp & _cross, - eoMonOp & _mut, - eoSelectOne & _sel_child, /* To choose one from - the both children */ - eoSelectOne & _sel_repl - ) : + eoEvalFunc & _eval, + eoSelectOne & _sel_neigh, + eoQuadOp & _cross, + eoMonOp & _mut, + eoSelectOne & _sel_child, /* To choose one from + the both children */ + eoSelectOne & _sel_repl + ) : cont (_cont), eval (_eval), popEval (_eval), @@ -80,7 +80,7 @@ public : mut (_mut), sel_child (_sel_child), sel_repl (_sel_repl) { - + } /** @@ -88,55 +88,55 @@ public : */ void operator () (eoPop & pop) { - + do { - + for (unsigned i = 0 ; i < pop.size () ; i ++) { - - // Who are neighbouring to the current individual ? - eoPop neigh = neighbours (pop, i) ; - - // To select a partner - EOT part, old_sol = pop [i] ; - part = sel_neigh (neigh) ; - // To perform cross-over - cross (pop [i], part) ; + // Who are neighbouring to the current individual ? + eoPop neigh = neighbours (pop, i) ; - // To perform mutation - mut (pop [i]) ; - mut (part) ; - - pop [i].invalidate () ; - part.invalidate () ; - eval (pop [i]) ; - eval (part) ; + // To select a partner + EOT part, old_sol = pop [i] ; + part = sel_neigh (neigh) ; - // To choose one of the two children ... - eoPop pop_loc ; - pop_loc.push_back (pop [i]) ; - pop_loc.push_back (part) ; + // To perform cross-over + cross (pop [i], part) ; - pop [i] = sel_child (pop_loc) ; + // To perform mutation + mut (pop [i]) ; + mut (part) ; - // To choose only one between the new made child and the old individual - pop_loc.clear () ; - pop_loc.push_back (pop [i]) ; - - pop_loc.push_back (old_sol) ; - - pop [i] = sel_repl (pop_loc) ; + pop [i].invalidate () ; + part.invalidate () ; + eval (pop [i]) ; + eval (part) ; + + // To choose one of the two children ... + eoPop pop_loc ; + pop_loc.push_back (pop [i]) ; + pop_loc.push_back (part) ; + + pop [i] = sel_child (pop_loc) ; + + // To choose only one between the new made child and the old individual + pop_loc.clear () ; + pop_loc.push_back (pop [i]) ; + + pop_loc.push_back (old_sol) ; + + pop [i] = sel_repl (pop_loc) ; } - + } while (cont (pop)) ; } protected : - + virtual eoPop neighbours (const eoPop & pop, int rank) = 0 ; private : - + eoContinue & cont ; eoEvalFunc & eval ; eoPopLoopEval popEval ; @@ -145,18 +145,18 @@ private : eoMonOp & mut ; eoSelectOne & sel_child ; eoSelectOne & sel_repl ; - + class eoSelectFirstOne : public eoSelectOne { - + public : - + const EOT & operator () (const eoPop & pop) { - - return pop [0] ; + + return pop [0] ; } - - } ; - + + } ; + } ; #endif diff --git a/eo/src/eoCloneOps.h b/eo/src/eoCloneOps.h index bdb9f041..e53cbd74 100644 --- a/eo/src/eoCloneOps.h +++ b/eo/src/eoCloneOps.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoCloneOps.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -18,7 +18,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - CVS Info: $Date: 2003-02-27 19:26:09 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoCloneOps.h,v 1.2 2003-02-27 19:26:09 okoenig Exp $ $Author: okoenig $ + CVS Info: $Date: 2003-02-27 19:26:09 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoCloneOps.h,v 1.2 2003-02-27 19:26:09 okoenig Exp $ $Author: okoenig $ */ //----------------------------------------------------------------------------- @@ -29,9 +29,9 @@ /** * The different null-variation operators (i.e. they do nothing) - * - * eoQuadCloneOp at least is useful to emulate the standard - * crossover(pCross) + mutation(pMut) + * + * eoQuadCloneOp at least is useful to emulate the standard + * crossover(pCross) + mutation(pMut) * within the eoGenOp framework * eoMonCloneOp will probably be useful as the copy operator * eoBinCloneOp will certainly never been used - but let's be complete :-) @@ -80,4 +80,3 @@ virtual bool operator()(EOT& , EOT& ) {return false;} #endif /** @} */ - diff --git a/eo/src/eoCombinedContinue.h b/eo/src/eoCombinedContinue.h index 2788f415..4dac4d69 100644 --- a/eo/src/eoCombinedContinue.h +++ b/eo/src/eoCombinedContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCombinedContinue.h // (c) Maarten Keijzer, 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 @@ -27,7 +27,7 @@ #include -/** +/** Combined continuators - logical AND: Continues until one of the embedded continuators says halt! @@ -35,7 +35,7 @@ to be consistent with other Combined constructs and allow to easily handle more than 2 continuators -02/2003 Ramón Casero Cañas - added the removeLast() method +02/2003 Ramón Casero Cañas - added the removeLast() method @ingroup Combination */ @@ -90,4 +90,3 @@ private: }; #endif - diff --git a/eo/src/eoCombinedInit.h b/eo/src/eoCombinedInit.h index 67fa0230..d41122d8 100644 --- a/eo/src/eoCombinedInit.h +++ b/eo/src/eoCombinedInit.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCombinedInit.h // (c) Maarten Keijzer, GeNeura Team, Marc Schoenauer 2004 -/* +/* 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 @@ -27,7 +27,7 @@ #include -/** +/** Combined INIT: a proportional recombination of eoInit objects @ingroup Initializators @@ -49,7 +49,7 @@ public: eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoCombinedInit::add is deprecated and will be removed in the next release." << std::endl; add( _init, _rate ); } - + /** The usual method to add objects to the combination */ void add(eoInit & _init, double _rate) @@ -78,7 +78,7 @@ public: virtual void operator() ( EOT & _eo ) { unsigned what = rng.roulette_wheel(rates); // choose one op - (*initializers[what])(_eo); // apply it + (*initializers[what])(_eo); // apply it return; } @@ -90,4 +90,3 @@ std::vector rates; }; #endif - diff --git a/eo/src/eoConstrictedVariableWeightVelocity.h b/eo/src/eoConstrictedVariableWeightVelocity.h index fd0dc13b..9e96d7ef 100644 --- a/eo/src/eoConstrictedVariableWeightVelocity.h +++ b/eo/src/eoConstrictedVariableWeightVelocity.h @@ -56,9 +56,9 @@ public: * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -85,9 +85,9 @@ public: * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -112,8 +112,8 @@ public: * @param _topology - The topology to get the global/local/other best* * @param _coeff - The constriction coefficient * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology, @@ -134,7 +134,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - update the weight with the weightUpdater (use the dummy updater if there's no updater provided) @@ -189,22 +189,21 @@ public: protected: eoTopology < POT > & topology; - + const VelocityType & coeff; // the fixed constriction coefficient - eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate - - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 - + eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate + + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealBoundModifier & bndsModifier; - + VelocityType weight; - eoRng & gen; // the random generator - + eoRng & gen; // the random generator + // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H*/ - diff --git a/eo/src/eoConstrictedVelocity.h b/eo/src/eoConstrictedVelocity.h index bd68f042..45f6e03d 100644 --- a/eo/src/eoConstrictedVelocity.h +++ b/eo/src/eoConstrictedVelocity.h @@ -56,9 +56,9 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -82,9 +82,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -106,8 +106,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoConstrictedVelocity (eoTopology < POT > & _topology, @@ -126,7 +126,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) @@ -173,20 +173,20 @@ public: topology.updateNeighborhood(_po,_indice); } - //! eoTopology getTopology + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 const VelocityType & coeff; // the fixed constriction coefficient - eoRng & gen; // the random generator + eoRng & gen; // the random generator eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealBoundModifier & bndsModifier; @@ -197,4 +197,3 @@ protected: #endif /*EOCONSTRICTEDVELOCITY_H */ - diff --git a/eo/src/eoContinue.h b/eo/src/eoContinue.h index 98321512..dbbf2480 100644 --- a/eo/src/eoContinue.h +++ b/eo/src/eoContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoContinue.h // (c) Maarten Keijzer, 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 @@ -31,7 +31,7 @@ /** @defgroup Continuators Stopping criteria * - * A stopping criterion is called a "continue". This is a functor that is called at each generation end + * A stopping criterion is called a "continue". This is a functor that is called at each generation end * and that return true if one should stop the search. * * @ingroup Utilities @@ -39,13 +39,13 @@ /** Termination condition for the genetic algorithm * Takes the population as input, returns true for continue, - * false for termination + * false for termination * * @ingroup Continuators * @ingroup Core */ template< class EOT> -class eoContinue : public eoUF&, bool>, public eoPersistent +class eoContinue : public eoUF&, bool>, public eoPersistent { public: virtual std::string className(void) const { return "eoContinue"; } @@ -57,7 +57,7 @@ public: (void)__is; /* It should be implemented by subclasses ! */ } - + /** Print on a stream * @param __os ostream to print on */ @@ -68,4 +68,3 @@ public: }; #endif - diff --git a/eo/src/eoCounter.h b/eo/src/eoCounter.h index cb0b57cf..afd7fd2e 100644 --- a/eo/src/eoCounter.h +++ b/eo/src/eoCounter.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCounter.h // (c) Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,9 +31,9 @@ #include /** - Generic counter class that counts the number of times - a procedure is used. Add a procedure through its ctor and - use this class instead of it. + Generic counter class that counts the number of times + a procedure is used. Add a procedure through its ctor and + use this class instead of it. It is derived from eoValueParam so you can add it to a monitor. @@ -44,21 +44,21 @@ class eoProcedureCounter : public Procedure, public eoValueParam { public: - eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter") + eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter") : eoValueParam(0, _name), proc(_proc) {} /** Calls the embedded function and increments the counter - + Note for MSVC users, if this code does not compile, you are quite likely trying to count a function that has a non-void return type. Don't look at us, look at the MSVC builders. Code like "return void;" is perfectly legal according to the ANSI standard, but the guys at - Microsoft didn't get to implementing it yet. - + Microsoft didn't get to implementing it yet. + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. Given that in EO most functors return void, it was chosen to support void. - But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite capable of compiling return void; type of code. We'll try to change the signature then. You happy GNU (and other compiler) users will not have a problem with this.. @@ -79,39 +79,39 @@ class eoProcedureCounter : public Procedure, public eoValueParam }; /** - Generic counter class that counts the number of times - a unary function is used. Add a unary function through its ctor and - use this class instead of it. - + Generic counter class that counts the number of times + a unary function is used. Add a unary function through its ctor and + use this class instead of it. + It is derived from eoValueParam so you can add it to a monitor. - Example: suppose you have an eoEvalFunc called myeval, to count the + Example: suppose you have an eoEvalFunc called myeval, to count the number of evaluations, just define: eoUnaryFunctorCounter evalCounter(myeval); - and use evalCounter now instead of myeval. + and use evalCounter now instead of myeval. */ template class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam { public: - eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter") + eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter") : eoValueParam(0, _name), func(_func) {} - + /** Calls the embedded function and increments the counter - + Note for MSVC users, if this code does not compile, you are quite likely trying to count a function that has a non-void return type. Don't look at us, look at the MSVC builders. Code like "return void;" is perfectly legal according to the ANSI standard, but the guys at - Microsoft didn't get to implementing it yet. - + Microsoft didn't get to implementing it yet. + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. Given that in EO most functors return void, it was chosen to support void. - But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite capable of compiling return void; type of code. We'll try to change the signature then. You happy GNU (and other compiler) users will not have a problem with this. @@ -133,10 +133,10 @@ class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam { public: - eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter") + eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter") : eoValueParam(0, _name), func(_func) {} /** Calls the embedded function and increments the counter - + Note for MSVC users, if this code does not compile, you are quite likely trying to count a function that has a non-void return type. Don't look at us, look at the MSVC builders. Code like "return void;" is perfectly legal according to the ANSI standard, but the guys at - Microsoft didn't get to implementing it yet. - + Microsoft didn't get to implementing it yet. + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. Given that in EO most functors return void, it was chosen to support void. - But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite capable of compiling return void; type of code. We'll try to change the signature then. - + You happy GNU (and other compiler) users will not have a problem with this. */ typename BinaryFunctor::result_type operator() - (typename BinaryFunctor::first_argument_type _arg1, + (typename BinaryFunctor::first_argument_type _arg1, typename BinaryFunctor::second_argument_type _arg2) { value()++; @@ -185,7 +185,7 @@ class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam), by simply stating: diff --git a/eo/src/eoCtrlCContinue.cpp b/eo/src/eoCtrlCContinue.cpp index 0e04422a..b7ee7fea 100644 --- a/eo/src/eoCtrlCContinue.cpp +++ b/eo/src/eoCtrlCContinue.cpp @@ -1,23 +1,23 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoCtrlCContinue.cpp -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either 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 @@ -26,7 +26,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include diff --git a/eo/src/eoCtrlCContinue.h b/eo/src/eoCtrlCContinue.h index 9b1aac0f..9bbcf9c0 100644 --- a/eo/src/eoCtrlCContinue.h +++ b/eo/src/eoCtrlCContinue.h @@ -1,23 +1,23 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoCtrlCContinue.h -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either 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 @@ -50,14 +50,14 @@ template< class EOT> class eoCtrlCContinue: public eoContinue { public: - + /// Ctor : installs the signal handler eoCtrlCContinue() { // First checks that no other eoCtrlCContinue does exist if (existCtrlCContinue) throw std::runtime_error("A signal handler for Ctrl C is already defined!\n"); - + #ifndef _WINDOWS #ifdef SIGQUIT signal( SIGINT, signal_handler ); @@ -65,9 +65,9 @@ public: existCtrlCContinue = true; #endif #endif - + } - + /** Returns false when Ctrl C has been typed in * reached */ virtual bool operator() ( const eoPop& _vEO ) @@ -84,4 +84,3 @@ public: #endif /** @} */ - diff --git a/eo/src/eoDetSelect.h b/eo/src/eoDetSelect.h index 2ad6cde0..4a0858b6 100644 --- a/eo/src/eoDetSelect.h +++ b/eo/src/eoDetSelect.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoDetSelect.h + eoDetSelect.h (c) Marc Schoenauer, Maarten Keijzer, 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 @@ -48,7 +48,7 @@ class eoDetSelect : public eoSelect /** @param _source the source population - @param _dest the resulting population (size of this population is + @param _dest the resulting population (size of this population is given by the HowMany data It empties the destination and adds the selection into it) */ @@ -58,32 +58,32 @@ class eoDetSelect : public eoSelect size_t target = howMany(pSize); if ( target == 0 ) - { - eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl; - target = 1; - } + { + eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl; + target = 1; + } _dest.resize(target); unsigned remain = target % pSize; unsigned entireCopy = target / pSize; typename eoPop::iterator it = _dest.begin(); - + if (target >= pSize) { - for (unsigned i=0; i // +#include // #include // accumulate #include @@ -37,7 +37,7 @@ #include /** eoDetTournamentSelect: a selection method that selects ONE individual by - deterministic tournament + deterministic tournament -MS- 24/10/99 @ingroup Selectors @@ -45,7 +45,7 @@ template class eoDetTournamentSelect: public eoSelectOne { public: - /* (Default) Constructor - + /* (Default) Constructor - @param _tSize tournament size */ eoDetTournamentSelect(unsigned _tSize = 2 ):eoSelectOne(), tSize(_tSize) { @@ -55,15 +55,15 @@ template class eoDetTournamentSelect: public eoSelectOne tSize = 2; } } - - /* Perform deterministic tournament calling the appropriate fn + + /* Perform deterministic tournament calling the appropriate fn see selectors.h */ - virtual const EOT& operator()(const eoPop& _pop) + virtual const EOT& operator()(const eoPop& _pop) { return deterministic_tournament(_pop, tSize); } - + private: unsigned tSize; }; @@ -71,4 +71,3 @@ template class eoDetTournamentSelect: public eoSelectOne //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoDistribUpdater.h b/eo/src/eoDistribUpdater.h index 6166e733..79b22814 100644 --- a/eo/src/eoDistribUpdater.h +++ b/eo/src/eoDistribUpdater.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoDistribUpdater.h // (c) Marc Schoenauer, Maarten Keijzer, 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 @@ -32,7 +32,7 @@ #include /** - * Base class for Distribution Evolution Algorithms within EO: + * Base class for Distribution Evolution Algorithms within EO: * the update rule of distribution * * It takes one distribution and updates it according to one population @@ -40,7 +40,7 @@ * @ingroup Core */ template -class eoDistribUpdater : +class eoDistribUpdater : public eoBF &, eoPop &, void> { public: diff --git a/eo/src/eoDistribution.h b/eo/src/eoDistribution.h index 1f38ab94..6ca90fe4 100644 --- a/eo/src/eoDistribution.h +++ b/eo/src/eoDistribution.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoDistribution.h // (c) Marc Schoenauer, Maarten Keijzer, 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 @@ -44,8 +44,8 @@ */ template -class eoDistribution : public eoInit, - public eoPersistent, public eoObject +class eoDistribution : public eoInit, + public eoPersistent, public eoObject { public: virtual void operator()(EOT &) = 0; // DO NOT FORGET TO INVALIDATE the EOT diff --git a/eo/src/eoDualFitness.h b/eo/src/eoDualFitness.h index 4cd34c6a..4803361f 100644 --- a/eo/src/eoDualFitness.h +++ b/eo/src/eoDualFitness.h @@ -4,7 +4,7 @@ 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 + 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, @@ -40,7 +40,7 @@ Authors: //! A fitness class that permits to compare feasible and unfeasible individuals and guaranties that a feasible individual will always be better than an unfeasible one. /** - * Use this class as fitness if you have some kind of individuals + * Use this class as fitness if you have some kind of individuals * that must be always considered as better than others while having the same fitness type. * * Wraps a scalar fitness _values such as a double or int, with the option of @@ -52,7 +52,7 @@ Authors: * * When changing the fitness, you can use: * individual.fitness( std::make_pair( fitness, feasibility ) ); - * + * * Be aware that, when printing or reading an eDualFitness instance on a iostream, * friend IO classes use a space separator. * @@ -80,19 +80,19 @@ public: /*! * Unfeasible by default */ - eoDualFitness() : - _value(), - _is_feasible(false) + eoDualFitness() : + _value(), + _is_feasible(false) {} //! Copy constructor eoDualFitness(const eoDualFitness& other) : _value(other._value), - _is_feasible(other._is_feasible) + _is_feasible(other._is_feasible) {} //! Constructor from explicit value/feasibility - eoDualFitness(const BaseType& v, const bool& is_feasible) : + eoDualFitness(const BaseType& v, const bool& is_feasible) : _value(v), _is_feasible(is_feasible) {} @@ -118,15 +118,15 @@ public: { _value = v.first; _is_feasible = v.second; - return *this; + return *this; } - + //! Copy operator from another eoDualFitness template eoDualFitness & operator=(const eoDualFitness& other ) { if (this != &other) { - this->_value = other._value; + this->_value = other._value; this->_is_feasible = other._is_feasible; } return *this; @@ -135,12 +135,12 @@ public: //! Comparison that separate feasible individuals from unfeasible ones. Feasible are always better /*! - * Use less as a default comparison operator + * Use less as a default comparison operator * (see the "Compare" template of the class to change this behaviour, * @see eoMinimizingDualFitness for an example). */ bool operator<(const eoDualFitness& other) const - { + { // am I better (less, by default) than the other ? // if I'm feasible and the other is not @@ -152,7 +152,7 @@ public: // yes, a feasible fitness is always better than an unfeasible one return true; - } else { + } else { // the two fitness are of the same type // lets rely on the comparator return Compare()(_value, other._value); @@ -168,7 +168,7 @@ public: //! Greater or equal: if the other is not greater than me bool operator>=(const eoDualFitness& other ) const { return !(*this < other); } - + public: //! Add a given fitness to the current one @@ -199,7 +199,7 @@ public: // Add this fitness's value to that other, and return a _new_ instance with the result. template - eoDualFitness operator+(const eoDualFitness & that) + eoDualFitness operator+(const eoDualFitness & that) { eoDualFitness from( *this ); return from += that; @@ -207,7 +207,7 @@ public: // Add this fitness's value to that other, and return a _new_ instance with the result. template - eoDualFitness operator-(const eoDualFitness & that) + eoDualFitness operator-(const eoDualFitness & that) { eoDualFitness from( *this ); return from -= that; @@ -224,7 +224,7 @@ public: //! Read an eoDualFitness instance as a pair of numbers, separated by a space template - friend + friend std::istream& operator>>(std::istream& is, eoDualFitness& f) { F value; @@ -265,11 +265,11 @@ public: // eoDualStatSwitch( eoStat & stat_feasible, eoStat & stat_unfeasible, std::string sep=" " ) : eoDualStatSwitch( EOSTAT & stat_feasible, EOSTAT & stat_unfeasible, std::string sep=" " ) : eoStat( - "?"+sep+"?", - stat_feasible.longName()+sep+stat_unfeasible.longName() - ), - _stat_feasible(stat_feasible), - _stat_unfeasible(stat_unfeasible), + "?"+sep+"?", + stat_feasible.longName()+sep+stat_unfeasible.longName() + ), + _stat_feasible(stat_feasible), + _stat_unfeasible(stat_unfeasible), _sep(sep) { } @@ -277,7 +277,7 @@ public: { eoPop pop_feasible; pop_feasible.reserve(pop.size()); - + eoPop pop_unfeasible; pop_unfeasible.reserve(pop.size()); @@ -296,7 +296,7 @@ public: _stat_feasible( pop_feasible ); _stat_unfeasible( pop_unfeasible ); - + std::ostringstream out; out << _stat_feasible.value() << _sep << _stat_unfeasible.value(); @@ -311,7 +311,6 @@ protected: std::string _sep; }; - + /** @} */ #endif // _eoDualFitness_h_ - diff --git a/eo/src/eoEDA.h b/eo/src/eoEDA.h index 896c5a97..553b751f 100644 --- a/eo/src/eoEDA.h +++ b/eo/src/eoEDA.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEDA.h // (c) Marc Schoenauer, Maarten Keijzer, 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 @@ -30,8 +30,8 @@ #include -/** The abstract class for estimation of disribution algorithms. - * This design evolve a probability distribution +/** The abstract class for estimation of disribution algorithms. + * This design evolve a probability distribution * on the spaces of populations rather than a population * * It IS NOT an eoAlgo, as it evolves a distribution, not a population. @@ -44,4 +44,3 @@ template class eoEDA: public eoUF&, void> }; #endif - diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 2ca8d37e..eb773969 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -97,7 +97,7 @@ template class eoEasyEA: public eoAlgo mergeReduce(dummyMerge, dummyReduce), replace(_replace) { - offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. + offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. } /* @@ -135,8 +135,8 @@ template class eoEasyEA: public eoAlgo {} - /// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval - eoEasyEA( + /// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval + eoEasyEA( eoContinue& _continuator, eoPopEvalFunc& _eval, eoSelect& _select, @@ -185,7 +185,7 @@ template class eoEasyEA: public eoAlgo mergeReduce(dummyMerge, dummyReduce), replace(_replace) {} - + /// Ctor eoSelect, eoTransform, eoMerge and eoReduce. eoEasyEA( eoContinue& _continuator, @@ -291,7 +291,7 @@ template class eoEasyEA: public eoAlgo eoMergeReduce mergeReduce; eoReplacement& replace; - eoPop offspring; + eoPop offspring; // Friend classes friend class eoIslandsEasyEA ; @@ -303,4 +303,3 @@ Example of a test program building an EA algorithm. */ #endif - diff --git a/eo/src/eoEasyPSO.h b/eo/src/eoEasyPSO.h index bcfc891a..da071bc0 100644 --- a/eo/src/eoEasyPSO.h +++ b/eo/src/eoEasyPSO.h @@ -32,16 +32,16 @@ #include //----------------------------------------------------------------------------- -/** An easy-to-use particle swarm algorithm. -* Use any particle, any flight, any topology... +/** An easy-to-use particle swarm algorithm. +* Use any particle, any flight, any topology... * * The main steps are : -* (The population is expected to be already evaluated) -* - for each generation and each particle pi -* - evaluate the velocities -* -- perform the fligth of pi -* -- evaluate pi -* -- update the neighborhoods +* (The population is expected to be already evaluated) +* - for each generation and each particle pi +* - evaluate the velocities +* -- perform the fligth of pi +* -- evaluate pi +* -- update the neighborhoods * * @ingroup Algorithms */ @@ -54,7 +54,7 @@ public: * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoEasyPSO ( @@ -90,11 +90,11 @@ public: {} - /* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm + /* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoEasyPSO ( @@ -125,7 +125,7 @@ public: velocity (_velocity), flight (dummyFlight) {} - + /// Apply a few iteration of flight to the population (=swarm). virtual void operator () (eoPop < POT > &_pop) { @@ -171,22 +171,22 @@ protected: eoVelocity < POT > &velocity; eoFlight < POT > &flight; - // if the flight does not need to be used, use the dummy flight instance - class eoDummyFlight:public eoFlight < POT > - { - public: - eoDummyFlight () {} - void operator () (POT & _po) {} - }dummyFlight; - - // if the initializer does not need to be used, use the dummy one instead - class eoDummyInitializer:public eoInitializerBase < POT > - { - public: - eoDummyInitializer () {} - void operator () (POT & _po) {} - }dummyInit; - + // if the flight does not need to be used, use the dummy flight instance + class eoDummyFlight:public eoFlight < POT > + { + public: + eoDummyFlight () {} + void operator () (POT & _po) {} + }dummyFlight; + + // if the initializer does not need to be used, use the dummy one instead + class eoDummyInitializer:public eoInitializerBase < POT > + { + public: + eoDummyInitializer () {} + void operator () (POT & _po) {} + }dummyInit; + }; /** * @example t-eoEasyPSO.cpp diff --git a/eo/src/eoEvalContinue.h b/eo/src/eoEvalContinue.h index 05ac2f0a..ef74e075 100644 --- a/eo/src/eoEvalContinue.h +++ b/eo/src/eoEvalContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEvalContinue.h // (c) GeNeura Team, 1999, 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 @@ -29,7 +29,7 @@ #include #include -/** +/** * Continues until a number of evaluations has been made * * @ingroup Continuators @@ -38,28 +38,28 @@ template< class EOT> class eoEvalContinue: public eoContinue { public: - /// Ctor + /// Ctor eoEvalContinue( eoEvalFuncCounter & _eval, unsigned long _totalEval) - : eval(_eval), repTotalEvaluations( _totalEval ) {}; - + : eval(_eval), repTotalEvaluations( _totalEval ) {}; + /** Returns false when a certain number of evaluations has been done */ virtual bool operator() ( const eoPop& _vEO ) { (void)_vEO; - if (eval.value() >= repTotalEvaluations) + if (eval.value() >= repTotalEvaluations) { eo::log << eo::progress << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]" << std::endl; - return false; + return false; } return true; } - + /** Returns the number of generations to reach*/ - virtual unsigned long totalEvaluations( ) - { - return repTotalEvaluations; + virtual unsigned long totalEvaluations( ) + { + return repTotalEvaluations; }; - + virtual std::string className(void) const { return "eoEvalContinue"; } private: eoEvalFuncCounter & eval; diff --git a/eo/src/eoEvalCounterThrowException.h b/eo/src/eoEvalCounterThrowException.h index 133d3afb..4eb4fccc 100644 --- a/eo/src/eoEvalCounterThrowException.h +++ b/eo/src/eoEvalCounterThrowException.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo Caner Candan @@ -49,7 +49,7 @@ class eoEvalCounterThrowException : public eoEvalFuncCounter< EOT > { public : eoEvalCounterThrowException( eoEvalFunc& func, unsigned long max_evals, std::string name = "Eval. ") - : eoEvalFuncCounter< EOT >( func, name ), _threshold( max_evals ) + : eoEvalFuncCounter< EOT >( func, name ), _threshold( max_evals ) {} using eoEvalFuncCounter< EOT >::value; @@ -60,8 +60,8 @@ public : // bypass already evaluated individuals if (eo.invalid()) { - // increment the value of the self parameter - // (eoEvalFuncCounter inherits from @see eoValueParam) + // increment the value of the self parameter + // (eoEvalFuncCounter inherits from @see eoValueParam) value()++; // if we have reached the maximum @@ -84,4 +84,3 @@ private : }; #endif // __eoEvalCounterThrowException_h__ - diff --git a/eo/src/eoEvalFunc.h b/eo/src/eoEvalFunc.h index 275c5185..b05b667b 100644 --- a/eo/src/eoEvalFunc.h +++ b/eo/src/eoEvalFunc.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEvalFunc.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -37,8 +37,8 @@ The requirements on the types with which this class is to be instantiated with are null, or else, they depend on the particular - class it's going to be applied to; EO does not impose any requirement - on it. If you subclass this abstract class, and use it to evaluate an + class it's going to be applied to; EO does not impose any requirement + on it. If you subclass this abstract class, and use it to evaluate an EO, the requirements on this EO will depend on the evaluator. @ingroup Evaluation @@ -49,7 +49,7 @@ template class eoEvalFunc : public eoUF public : typedef EOT EOType; - typedef typename EOT::Fitness EOFitT; + typedef typename EOT::Fitness EOFitT; }; #endif diff --git a/eo/src/eoEvalFuncCounter.h b/eo/src/eoEvalFuncCounter.h index 55973d06..a63821d6 100644 --- a/eo/src/eoEvalFuncCounter.h +++ b/eo/src/eoEvalFuncCounter.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEvalFuncCounter.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 @@ -30,7 +30,7 @@ #include #include -/** +/** Counts the number of evaluations actually performed. @ingroup Evaluation @@ -38,7 +38,7 @@ Counts the number of evaluations actually performed. template class eoEvalFuncCounter : public eoEvalFunc, public eoValueParam { public : - eoEvalFuncCounter(eoEvalFunc& _func, std::string _name = "Eval. ") + eoEvalFuncCounter(eoEvalFunc& _func, std::string _name = "Eval. ") : eoValueParam(0, _name), func(_func) {} virtual void operator()(EOT& _eo) diff --git a/eo/src/eoEvalFuncCounterBounder.h b/eo/src/eoEvalFuncCounterBounder.h index 68c9770c..1c8a29b1 100644 --- a/eo/src/eoEvalFuncCounterBounder.h +++ b/eo/src/eoEvalFuncCounterBounder.h @@ -8,7 +8,7 @@ * @{ */ -/** The exception raised by eoEvalFuncCounterBounder +/** The exception raised by eoEvalFuncCounterBounder * when the maximum number of allowed evaluations is reached. */ class eoEvalFuncCounterBounderException : public std::exception @@ -18,9 +18,9 @@ public: const char* what() const throw() { - std::ostringstream ss; - ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ")."; - return ss.str().c_str(); + std::ostringstream ss; + ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ")."; + return ss.str().c_str(); } private: @@ -31,7 +31,7 @@ private: * when the maximum number of allowed evaluations is reached. * * This eval counter permits to stop a search during a generation, without waiting for a continue to be - * checked at the end of the loop. Useful if you have 10 individuals and 10 generations, + * checked at the end of the loop. Useful if you have 10 individuals and 10 generations, * but want to stop after 95 evaluations. */ template < typename EOT > @@ -39,21 +39,21 @@ class eoEvalFuncCounterBounder : public eoEvalFuncCounter< EOT > { public : eoEvalFuncCounterBounder(eoEvalFunc& func, unsigned long threshold, std::string name = "Eval. ") - : eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold ) + : eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold ) {} using eoEvalFuncCounter< EOT >::value; virtual void operator()(EOT& eo) { - if (eo.invalid()) + if (eo.invalid()) { value()++; - if (_threshold > 0 && value() >= _threshold) - { - throw eoEvalFuncCounterBounderException(_threshold); - } + if (_threshold > 0 && value() >= _threshold) + { + throw eoEvalFuncCounterBounderException(_threshold); + } func(eo); } diff --git a/eo/src/eoEvalFuncPtr.h b/eo/src/eoEvalFuncPtr.h index d493b9b0..f4952c21 100644 --- a/eo/src/eoEvalFuncPtr.h +++ b/eo/src/eoEvalFuncPtr.h @@ -6,7 +6,7 @@ evaluation object (c) GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -52,17 +52,16 @@ struct eoEvalFuncPtr: public eoEvalFunc { */ eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) ) : eoEvalFunc(), evalFunc( _eval ) {}; - - /// Effectively applies the evaluation function to an EO - virtual void operator() ( EOT & _eo ) + + /// Effectively applies the evaluation function to an EO + virtual void operator() ( EOT & _eo ) { if (_eo.invalid()) _eo.fitness((*evalFunc)( _eo )); }; - + private: FitT (* evalFunc )( FunctionArg ); }; #endif - diff --git a/eo/src/eoEvalTimeThrowException.h b/eo/src/eoEvalTimeThrowException.h index 752fafba..be0e149a 100644 --- a/eo/src/eoEvalTimeThrowException.h +++ b/eo/src/eoEvalTimeThrowException.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo */ diff --git a/eo/src/eoEvalUserTimeThrowException.h b/eo/src/eoEvalUserTimeThrowException.h index c237c09b..5d1f4c8a 100644 --- a/eo/src/eoEvalUserTimeThrowException.h +++ b/eo/src/eoEvalUserTimeThrowException.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo */ diff --git a/eo/src/eoExceptions.h b/eo/src/eoExceptions.h index 9760efc6..3b888436 100644 --- a/eo/src/eoExceptions.h +++ b/eo/src/eoExceptions.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo */ diff --git a/eo/src/eoExtendedVelocity.h b/eo/src/eoExtendedVelocity.h index 5aec4c21..e7667204 100644 --- a/eo/src/eoExtendedVelocity.h +++ b/eo/src/eoExtendedVelocity.h @@ -35,7 +35,7 @@ //----------------------------------------------------------------------------- -/** Extended velocity performer for particle swarm optimization. +/** Extended velocity performer for particle swarm optimization. * * Derivated from abstract eoVelocity, * At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) + c3 * r3 * ( gbest(t) - x(t) ) @@ -57,16 +57,16 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c2 - Learning factor used for the local best - * @param _c3 - Learning factor used for the global best - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c3 - Learning factor used for the global best + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng */ eoExtendedVelocity (eoTopology < POT > & _topology, - const VelocityType & _w, + const VelocityType & _w, const VelocityType & _c1, const VelocityType & _c2, const VelocityType & _c3, @@ -86,10 +86,10 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology * @param _w - The weight factor. - * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType + * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType * @param _c3 - Learning factor used for the global best - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -113,8 +113,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology * @param _w - The weight factor. - * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType + * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType * @param _c3 - Learning factor used for the global best * @param _gen - The eo random generator, default=rng */ @@ -145,25 +145,25 @@ public: { VelocityType r1; VelocityType r2; - VelocityType r3; - + VelocityType r3; + VelocityType newVelocity; // cast the learning factors to VelocityType r1 = (VelocityType) rng.uniform (1) * c1; r2 = (VelocityType) rng.uniform (1) * c2; - r3 = (VelocityType) rng.uniform (1) * c3; - + r3 = (VelocityType) rng.uniform (1) * c3; + // need to resize the bounds even if there are dummy because of "isBounded" call bounds.adjust_size(_po.size()); // assign the new velocities for (unsigned j = 0; j < _po.size (); j++) { - newVelocity= omega * _po.velocities[j] - + r1 * (_po.bestPositions[j] - _po[j]) - + r2 * (topology.best (_indice)[j] - _po[j]) - + r3 * (topology.globalBest()[j] - _po[j]); + newVelocity= omega * _po.velocities[j] + + r1 * (_po.bestPositions[j] - _po[j]) + + r2 * (topology.best (_indice)[j] - _po[j]) + + r3 * (topology.globalBest()[j] - _po[j]); /* check bounds */ if (bounds.isMinBounded(j)) @@ -182,27 +182,27 @@ public: { topology.updateNeighborhood(_po,_indice); } - + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & omega; // social/cognitive coefficient + const VelocityType & omega; // social/cognitive coefficient const VelocityType & c1; - const VelocityType & c2; // social/cognitive coefficient - const VelocityType & c3; // social/cognitive coefficient - - eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. - eoRealBoundModifier & bndsModifier; + const VelocityType & c2; // social/cognitive coefficient + const VelocityType & c3; // social/cognitive coefficient + + eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + eoRng & gen; // the random generator - eoRng & gen; // the random generator - // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; @@ -211,4 +211,3 @@ protected: * Example of a test program using this class: */ #endif /*eoExtendedVelocity_H */ - diff --git a/eo/src/eoFactory.h b/eo/src/eoFactory.h index 7e02d124..73a8faf1 100644 --- a/eo/src/eoFactory.h +++ b/eo/src/eoFactory.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFactory.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -43,32 +43,32 @@ have to be modified */ template class eoFactory: public eoObject { - + public: - - /// @name ctors and dtors - //{@ - /// constructor - eoFactory( ) {} - - /// destructor - virtual ~eoFactory() {} - //@} - /** Another factory methods: creates an object from an std::istream, reading from - it whatever is needed to create the object. Usually, the format for the std::istream will be\\ - objectType parameter1 parameter2 ... parametern\\ - */ - virtual EOClass* make(std::istream& _is) = 0; + /// @name ctors and dtors + //{@ + /// constructor + eoFactory( ) {} - ///@name eoObject methods - //@{ - /** Return the class id */ - virtual std::string className() const { return "eoFactory"; } + /// destructor + virtual ~eoFactory() {} + //@} + + /** Another factory methods: creates an object from an std::istream, reading from + it whatever is needed to create the object. Usually, the format for the std::istream will be\\ + objectType parameter1 parameter2 ... parametern\\ + */ + virtual EOClass* make(std::istream& _is) = 0; + + ///@name eoObject methods + //@{ + /** Return the class id */ + virtual std::string className() const { return "eoFactory"; } + + /** Read and print are left without implementation */ + //@} - /** Read and print are left without implementation */ - //@} - }; diff --git a/eo/src/eoFitContinue.h b/eo/src/eoFitContinue.h index 96401451..2db88f80 100644 --- a/eo/src/eoFitContinue.h +++ b/eo/src/eoFitContinue.h @@ -49,15 +49,15 @@ public: /** Returns false when a fitness criterium is reached. Assumes pop is not sorted! */ virtual bool operator() ( const eoPop& _pop ) { - //FitnessType bestCurrentFitness = _pop.nth_element_fitness(0); - FitnessType bestCurrentFitness = _pop.best_element().fitness(); - if (bestCurrentFitness >= optimum) - { - eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " << - bestCurrentFitness << "\n"; - return false; - } - return true; + //FitnessType bestCurrentFitness = _pop.nth_element_fitness(0); + FitnessType bestCurrentFitness = _pop.best_element().fitness(); + if (bestCurrentFitness >= optimum) + { + eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " << + bestCurrentFitness << "\n"; + return false; + } + return true; } virtual std::string className(void) const { return "eoFitContinue"; } diff --git a/eo/src/eoFitnessScalingSelect.h b/eo/src/eoFitnessScalingSelect.h index 7ea61607..c1753201 100644 --- a/eo/src/eoFitnessScalingSelect.h +++ b/eo/src/eoFitnessScalingSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFitnessScalingSelect.h // (c) GeNeura Team, 1998, Maarten Keijzer 2000, 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 @@ -32,25 +32,24 @@ #include #include -/** eoFitnessScalingSelect: select an individual proportional to the +/** eoFitnessScalingSelect: select an individual proportional to the * linearly scaled fitness that is computed by the private * eoLinearFitScaling object * * @ingroup Selectors */ -template -class eoFitnessScalingSelect: public eoRouletteWorthSelect +template +class eoFitnessScalingSelect: public eoRouletteWorthSelect { public: /** Ctor: * @param _p the selective pressure, should be in [1,2] (2 is the default) */ - eoFitnessScalingSelect(double _p = 2.0): + eoFitnessScalingSelect(double _p = 2.0): eoRouletteWorthSelect(scaling), scaling(_p) {} private : - eoLinearFitScaling scaling; // derived from eoPerf2Worth + eoLinearFitScaling scaling; // derived from eoPerf2Worth }; -#endif - +#endif diff --git a/eo/src/eoFixedInertiaWeightedVelocity.h b/eo/src/eoFixedInertiaWeightedVelocity.h index b19d36a9..291c85a0 100644 --- a/eo/src/eoFixedInertiaWeightedVelocity.h +++ b/eo/src/eoFixedInertiaWeightedVelocity.h @@ -54,9 +54,9 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _weight - The weight with type VelocityType - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -80,9 +80,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _weight - The weight with type VelocityType - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -104,8 +104,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _weight - The weight with type VelocityType - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology, @@ -124,7 +124,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) @@ -175,10 +175,10 @@ public: protected: eoTopology < POT > & topology; - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 const VelocityType & weight; // the fixed weight - eoRng & gen; // the random generator + eoRng & gen; // the random generator eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealBoundModifier & bndsModifier; @@ -189,4 +189,3 @@ protected: #endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */ - diff --git a/eo/src/eoFlOrBinOp.h b/eo/src/eoFlOrBinOp.h index dd1ff617..bcdc9c5c 100644 --- a/eo/src/eoFlOrBinOp.h +++ b/eo/src/eoFlOrBinOp.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFlOrBinOp.h // (c) Marc Schoenauer - Maarten Keijzer 2000-2003 -/* +/* 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 @@ -35,11 +35,11 @@ /** Generic eoBinOps on fixed length genotypes. * Contains exchange crossovers (1pt and uniform) - * and crossovers that applies an Atom crossover + * and crossovers that applies an Atom crossover * to all components with given rate, or * to a fixed prescribed nb of components * - * Example: the standard bitstring 1-point and uniform crossovers + * Example: the standard bitstring 1-point and uniform crossovers * could be implemented as resp. eoFlOr1ptBinOp and eoFlOrUniformBinOp */ @@ -65,14 +65,14 @@ public : { if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool changed = false; for ( unsigned i = 0; i < _eo1.size(); i++ ) { if ( rng.flip( rate ) ) { - bool changedHere = op( _eo1[i], _eo2[i] ); - changed |= changedHere; + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; } } return changed; @@ -108,16 +108,16 @@ public : { if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool changed = false; for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same { - unsigned where = eo::rng.random(_eo1.size()); - bool changedHere = op( _eo1[where], _eo2[where] ); - changed |= changedHere; + unsigned where = eo::rng.random(_eo1.size()); + bool changedHere = op( _eo1[where], _eo2[where] ); + changed |= changedHere; } return changed; } @@ -154,17 +154,17 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; for (unsigned i=0; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) - { - _eo1[i] = _eo2[i]; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) + { + _eo1[i] = _eo2[i]; + hasChanged = true; + } } return hasChanged; } @@ -198,18 +198,18 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; unsigned where = eo::rng.random(_eo1.size()-1); for (unsigned i=where+1; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) ) - { - _eo1[i] = _eo2[i]; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) ) + { + _eo1[i] = _eo2[i]; + hasChanged = true; + } } return hasChanged; } diff --git a/eo/src/eoFlOrMonOp.h b/eo/src/eoFlOrMonOp.h index 102acc11..63dae9cb 100644 --- a/eo/src/eoFlOrMonOp.h +++ b/eo/src/eoFlOrMonOp.h @@ -39,7 +39,7 @@ * eoFlOrAllMutation applies the atom mutation to all components with given rate * eoFlOrKMutation applies the atom mutation to a fixed nb of components * - * Remark: the standard bit-flip mutation is an eoFlOrAllMutation + * Remark: the standard bit-flip mutation is an eoFlOrAllMutation * with atom mutation == bitflipping */ @@ -62,21 +62,21 @@ public : bool modified=false; for (unsigned i=0; i<_eo.size(); i++) if (eo::rng.flip(rate)) - if (atomMutation(_eo[i])) - modified = true; + if (atomMutation(_eo[i])) + modified = true; return modified; } /** inherited className() */ - virtual std::string className() const - { + virtual std::string className() const + { return "eoFlOrAllMutation(" + atomMutation.className() + ")"; } private: eoMonOp & atomMutation; // the atom mutation - double rate; // the mutation rate PER ATOM + double rate; // the mutation rate PER ATOM }; /** Applies an atomic mutation to a fixed @@ -100,21 +100,21 @@ public : bool modified=false; for (unsigned k=0; k & atomMutation; // the atom mutation }; diff --git a/eo/src/eoFlOrQuadOp.h b/eo/src/eoFlOrQuadOp.h index f9c0373c..91618aa5 100644 --- a/eo/src/eoFlOrQuadOp.h +++ b/eo/src/eoFlOrQuadOp.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFlOrQuadOp.h // (c) Marc Schoenauer - Maarten Keijzer 2000-2003 -/* +/* 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 @@ -35,7 +35,7 @@ /** Generic eoQuadOps on fixed length genotypes. * Contains exchange crossovers (1pt and uniform) - * and crossovers that applies an Atom crossover + * and crossovers that applies an Atom crossover * to all components with given rate, or * to a fixed prescribed nb of components */ @@ -63,8 +63,8 @@ public : bool changed = false; for ( unsigned i = 0; i < _eo1.size(); i++ ) { if ( rng.flip( rate ) ) { - bool changedHere = op( _eo1[i], _eo2[i] ); - changed |= changedHere; + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; } } return changed; @@ -100,16 +100,16 @@ public : { if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool changed = false; for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same { - unsigned where = eo::rng.random(_eo1.size()); - bool changedHere = op( _eo1[where], _eo2[where] ); - changed |= changedHere; + unsigned where = eo::rng.random(_eo1.size()); + bool changedHere = op( _eo1[where], _eo2[where] ); + changed |= changedHere; } return changed; } @@ -145,19 +145,19 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; for (unsigned i=0; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) - { - tmp = _eo1[i]; - _eo1[i] = _eo2[i]; - _eo2[i] = tmp; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) + { + tmp = _eo1[i]; + _eo1[i] = _eo2[i]; + _eo2[i] = tmp; + hasChanged = true; + } } return hasChanged; } @@ -190,20 +190,20 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; unsigned where = eo::rng.random(_eo1.size()-1); for (unsigned i=where+1; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) ) - { - tmp = _eo1[i]; - _eo1[i] = _eo2[i]; - _eo2[i] = tmp; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) ) + { + tmp = _eo1[i]; + _eo1[i] = _eo2[i]; + _eo2[i] = tmp; + hasChanged = true; + } } return hasChanged; } diff --git a/eo/src/eoFunctor.h b/eo/src/eoFunctor.h index e782328a..465f0bc4 100644 --- a/eo/src/eoFunctor.h +++ b/eo/src/eoFunctor.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFunctor.h // (c) Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -20,7 +20,7 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es mak@dhi.dk - CVS Info: $Date: 2004-12-01 09:22:48 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.7 2004-12-01 09:22:48 evomarc Exp $ $Author: evomarc $ + CVS Info: $Date: 2004-12-01 09:22:48 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.7 2004-12-01 09:22:48 evomarc Exp $ $Author: evomarc $ */ //----------------------------------------------------------------------------- @@ -87,12 +87,12 @@ public : /// tag to identify a procedure in compile time function selection @see functor_category static eoFunctorBase::procedure_tag functor_category() { - return eoFunctorBase::procedure_tag(); + return eoFunctorBase::procedure_tag(); } }; /** - Overloaded function that can help in the compile time detection + Overloaded function that can help in the compile time detection of the type of functor we are dealing with @see eoCounter, make_counter @@ -103,8 +103,8 @@ eoFunctorBase::procedure_tag functor_category(const eoF&) return eoFunctorBase::procedure_tag(); } -/** - Basic Unary Functor. Derive from this class when defining +/** + Basic Unary Functor. Derive from this class when defining any unary function. First template argument is the first_argument_type, second result_type. Argument and result types can be any type including void for @@ -124,12 +124,12 @@ public : /// tag to identify a procedure in compile time function selection @see functor_category static eoFunctorBase::unary_function_tag functor_category() { - return eoFunctorBase::unary_function_tag(); + return eoFunctorBase::unary_function_tag(); } }; /** - Overloaded function that can help in the compile time detection + Overloaded function that can help in the compile time detection of the type of functor we are dealing with @see eoCounter, make_counter */ @@ -140,8 +140,8 @@ eoFunctorBase::unary_function_tag functor_category(const eoUF&) } -/** - Basic Binary Functor. Derive from this class when defining +/** + Basic Binary Functor. Derive from this class when defining any binary function. First template argument is result_type, second is first_argument_type, third is second_argument_type. Argument and result types can be any type including void for @@ -153,7 +153,7 @@ class eoBF : public eoFunctorBase, public std::binary_function public : /// virtual dtor here so there is no need to define it in derived classes virtual ~eoBF() {} - + //typedef R result_type; //typedef A1 first_argument_type; //typedef A2 second_argument_type; @@ -164,12 +164,12 @@ public : /// tag to identify a procedure in compile time function selection @see functor_category static eoFunctorBase::binary_function_tag functor_category() { - return eoFunctorBase::binary_function_tag(); + return eoFunctorBase::binary_function_tag(); } }; /** - Overloaded function that can help in the compile time detection + Overloaded function that can help in the compile time detection of the type of functor we are dealing with @see eoCounter, make_counter */ diff --git a/eo/src/eoG3Replacement.h b/eo/src/eoG3Replacement.h index aab7866f..a235244f 100644 --- a/eo/src/eoG3Replacement.h +++ b/eo/src/eoG3Replacement.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoG3Replacement.h + eoG3Replacement.h (c) Maarten Keijzer, Marc Schoenauer, 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 @@ -52,34 +52,34 @@ class eoG3Replacement : public eoReplacement public: eoG3Replacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false)) : // split truncates the parents and returns eliminated parents - split(_howManyEliminatedParents, true), + split(_howManyEliminatedParents, true), // reduce truncates the offpsring and does not return eliminated guys - reduce(-_howManyEliminatedParents, false) + reduce(-_howManyEliminatedParents, false) {} - + void operator()(eoPop & _parents, eoPop & _offspring) { eoPop temp; split(_parents, temp); unsigned toKeep = temp.size(); // how many to keep from merged populations // merge temp into offspring - plus(temp, _offspring); // add temp to _offspring (a little inconsistent!) - + plus(temp, _offspring); // add temp to _offspring (a little inconsistent!) + // reduce merged - reduce(_offspring, temp); // temp dummy arg. will not be modified + reduce(_offspring, temp); // temp dummy arg. will not be modified // minimla check: if (_offspring.size() != toKeep) - { - std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl; - throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring"); - } + { + std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl; + throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring"); + } // and put back into _parents - plus(_offspring, _parents); + plus(_offspring, _parents); } private: - eoLinearTruncateSplit split; // few parents to truncate -> linear - eoTruncateSplit reduce; // supposedly many offspring to truncate + eoLinearTruncateSplit split; // few parents to truncate -> linear + eoTruncateSplit reduce; // supposedly many offspring to truncate eoPlus plus; }; diff --git a/eo/src/eoGaussRealWeightUp.h b/eo/src/eoGaussRealWeightUp.h index 0da27b34..47edc321 100644 --- a/eo/src/eoGaussRealWeightUp.h +++ b/eo/src/eoGaussRealWeightUp.h @@ -32,7 +32,7 @@ /** - * Update an inertia weight by assigning it a Gaussian randomized value + * Update an inertia weight by assigning it a Gaussian randomized value * (used for the velocity in particle swarm optimization). * * @ingroup Variators diff --git a/eo/src/eoGenContinue.h b/eo/src/eoGenContinue.h index fac89d5d..0d01bb0a 100644 --- a/eo/src/eoGenContinue.h +++ b/eo/src/eoGenContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoGenContinue.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -29,7 +29,7 @@ #include #include -/** +/** Generational continuator: continues until a number of generations is reached @ingroup Continuators @@ -41,68 +41,68 @@ public: /// Ctor for setting a eoGenContinue( unsigned long _totalGens) - : eoValueParam(0, "Generations", "Generations"), - repTotalGenerations( _totalGens ), - thisGenerationPlaceHolder(0), - thisGeneration(thisGenerationPlaceHolder) + : eoValueParam(0, "Generations", "Generations"), + repTotalGenerations( _totalGens ), + thisGenerationPlaceHolder(0), + thisGeneration(thisGenerationPlaceHolder) {}; - + /// Ctor for enabling the save/load the no. of generations counted eoGenContinue( unsigned long _totalGens, unsigned long& _currentGen) - : eoValueParam(0, "Generations", "Generations"), - repTotalGenerations( _totalGens ), - thisGenerationPlaceHolder(0), - thisGeneration(_currentGen) + : eoValueParam(0, "Generations", "Generations"), + repTotalGenerations( _totalGens ), + thisGenerationPlaceHolder(0), + thisGeneration(_currentGen) {}; - + /** Returns false when a certain number of generations is - * reached */ + * reached */ virtual bool operator() ( const eoPop& _vEO ) { (void)_vEO; thisGeneration++; value() = thisGeneration; - - if (thisGeneration >= repTotalGenerations) + + if (thisGeneration >= repTotalGenerations) { - eo::log << eo::logging << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n"; - return false; + eo::log << eo::logging << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n"; + return false; } return true; } - - /** Sets the number of generations to reach - and sets the current generation to 0 (the begin) - - @todo replace this by an "init" method + + /** Sets the number of generations to reach + and sets the current generation to 0 (the begin) + + @todo replace this by an "init" method */ - virtual void totalGenerations( unsigned long _tg ) { - repTotalGenerations = _tg; - thisGeneration = 0; - }; - + virtual void totalGenerations( unsigned long _tg ) { + repTotalGenerations = _tg; + thisGeneration = 0; + }; + /** Returns the number of generations to reach*/ - virtual unsigned long totalGenerations( ) - { - return repTotalGenerations; + virtual unsigned long totalGenerations( ) + { + return repTotalGenerations; }; - - + + virtual std::string className(void) const { return "eoGenContinue"; } /** Read from a stream * @param __is the istream to read from */ void readFrom (std :: istream & __is) { - + __is >> thisGeneration; /* Loading the number of generations counted */ } - + /** Print on a stream * @param __os the ostream to print on */ void printOn (std :: ostream & __os) const { - - __os << thisGeneration << std :: endl; /* Saving the number of generations counted */ + + __os << thisGeneration << std :: endl; /* Saving the number of generations counted */ } private: @@ -112,4 +112,3 @@ private: }; #endif - diff --git a/eo/src/eoGenOp.h b/eo/src/eoGenOp.h index c304ec64..f0d70c7b 100644 --- a/eo/src/eoGenOp.h +++ b/eo/src/eoGenOp.h @@ -53,7 +53,7 @@ the original population, is an instantiation of the next population and has often a selection function embedded in it to select new individuals. Note that the actual work is performed in the apply function. -AND that the apply function is responsible for invalidating +AND that the apply function is responsible for invalidating the object if necessary */ template @@ -72,8 +72,8 @@ class eoGenOp : public eoOp, public eoUF &, void> void operator()(eoPopulator& _pop) { - _pop.reserve( max_production() ); - apply(_pop); + _pop.reserve( max_production() ); + apply(_pop); } //protected : @@ -114,10 +114,10 @@ class eoBinGenOp : public eoGenOp public: eoBinGenOp(eoBinOp& _op) : op(_op) {} - unsigned max_production(void) { return 1; } + unsigned max_production(void) { return 1; } /** do the work: get 2 individuals from the population, modifies - only one (it's a eoBinOp) + only one (it's a eoBinOp) */ void apply(eoPopulator& _pop) { @@ -169,9 +169,9 @@ class eoQuadGenOp : public eoGenOp void apply(eoPopulator& _pop) { EOT& a = *_pop; - EOT& b = *++_pop; - - + EOT& b = *++_pop; + + if(op(a, b)) { a.invalidate(); diff --git a/eo/src/eoGeneralBreeder.h b/eo/src/eoGeneralBreeder.h index 34d9220d..dc598ba7 100644 --- a/eo/src/eoGeneralBreeder.h +++ b/eo/src/eoGeneralBreeder.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoGeneralBreeder.h +// eoGeneralBreeder.h // (c) Maarten Keijzer and Marc Schoenauer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -58,7 +58,7 @@ class eoGeneralBreeder: public eoBreed eoGeneralBreeder( eoSelectOne& _select, eoGenOp& _op, - double _rate=1.0, + double _rate=1.0, bool _interpret_as_rate = true) : select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {} @@ -71,7 +71,7 @@ class eoGeneralBreeder: public eoBreed eoGeneralBreeder( eoSelectOne& _select, eoGenOp& _op, - eoHowMany _howMany ) : + eoHowMany _howMany ) : select( _select ), op(_op), howMany(_howMany) {} /** The breeder: simply calls the genOp on a selective populator! @@ -87,10 +87,10 @@ class eoGeneralBreeder: public eoBreed eoSelectivePopulator it(_parents, _offspring, select); while (_offspring.size() < target) - { - op(it); - ++it; - } + { + op(it); + ++it; + } _offspring.resize(target); // you might have generated a few more } @@ -105,4 +105,3 @@ class eoGeneralBreeder: public eoBreed }; #endif - diff --git a/eo/src/eoInit.h b/eo/src/eoInit.h index c751b4a2..7b460d94 100644 --- a/eo/src/eoInit.h +++ b/eo/src/eoInit.h @@ -43,24 +43,24 @@ */ /** @{*/ /** - Base (name) class for Initialization of chromosomes, used in a population - contructor. It is derived from eoMonOp, so it can be used + Base (name) class for Initialization of chromosomes, used in a population + contructor. It is derived from eoMonOp, so it can be used inside the algorithm as well. - @see eoPop + @see eoPop */ template class eoInit : public eoUF { public: - /** className: Mandatory because of eoCombinedInit. + /** className: Mandatory because of eoCombinedInit. SHould be pure virtual, but then we should go over the whole * code to write the method for all derived classes ... MS 16/7/04 */ virtual std::string className(void) const { return "eoInit"; } }; -/** turning an eoInit into a generator +/** turning an eoInit into a generator * probably we should only use genrators - and suppress eoInit ??? * MS - July 2001 */ @@ -115,13 +115,13 @@ template class eoInitVariableLength: public eoInit { public: -typedef typename EOT::AtomType AtomType; +typedef typename EOT::AtomType AtomType; // /** Ctor from a generator */ // eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoF & _generator = Gen()) -// : offset(_minSize), extent(_maxSize - _minSize), -// repGenerator( eoInitGenerator(*(new eoInit)) ), -// generator(_generator) +// : offset(_minSize), extent(_maxSize - _minSize), +// repGenerator( eoInitGenerator(*(new eoInit)) ), +// generator(_generator) // { // if (_minSize >= _maxSize) // throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize"); @@ -170,11 +170,11 @@ class eoInitPermutation: public eoInit virtual void operator()(EOT& chrom) { - chrom.resize(chromSize); + chrom.resize(chromSize); for(unsigned idx=0;idx eoInitAdaptor changes the place in the hierarchy from eoInit to eoMonOp. This is mainly a type conversion, nothing else - + @see eoInit, eoMonOp */ template diff --git a/eo/src/eoInitializer.h b/eo/src/eoInitializer.h index 26cb61de..506fcf73 100644 --- a/eo/src/eoInitializer.h +++ b/eo/src/eoInitializer.h @@ -54,9 +54,9 @@ public : }; /** - Base (name) class for Initialization of algorithm PSO + Base (name) class for Initialization of algorithm PSO - @see eoInitializerBase eoUF apply + @see eoInitializerBase eoUF apply */ template class eoInitializer : public eoInitializerBase { @@ -115,9 +115,9 @@ public: private : /* - @param proc First evaluation - @param initVelo Initialization of the velocity - @param initBest Initialization of the best + @param proc First evaluation + @param initVelo Initialization of the velocity + @param initBest Initialization of the best */ eoUF& proc; eoVelocityInit < POT > & initVelo; @@ -145,4 +145,3 @@ class eoDummy : public eoUF #endif /** @} */ - diff --git a/eo/src/eoInt.h b/eo/src/eoInt.h index bc16728d..41c87724 100644 --- a/eo/src/eoInt.h +++ b/eo/src/eoInt.h @@ -17,7 +17,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: thomas.legrand@lifl.fr - todos@geneura.ugr.es, http://geneura.ugr.es + todos@geneura.ugr.es, http://geneura.ugr.es mkeijzer@dhi.dk */ diff --git a/eo/src/eoIntegerVelocity.h b/eo/src/eoIntegerVelocity.h index 190db1b0..b00b17bf 100644 --- a/eo/src/eoIntegerVelocity.h +++ b/eo/src/eoIntegerVelocity.h @@ -55,16 +55,16 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best - * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng */ eoIntegerVelocity (eoTopology < POT > & _topology, - const VelocityType & _c1, + const VelocityType & _c1, const VelocityType & _c2, const VelocityType & _c3, eoRealVectorBounds & _bounds, @@ -81,10 +81,10 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best - * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -105,9 +105,9 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology the topology to use - * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoIntegerVelocity (eoTopology < POT > & _topology, @@ -116,7 +116,7 @@ public: const VelocityType & _c3, eoRng & _gen = rng): topology(_topology), - c1 (_c1), + c1 (_c1), c2 (_c2), c3 (_c3), bounds(*(new eoRealVectorNoBounds(0))), @@ -167,30 +167,29 @@ public: { topology.updateNeighborhood(_po,_indice); } - + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & c1; // social/cognitive coefficient - const VelocityType & c2; // social/cognitive coefficient - const VelocityType & c3; // social/cognitive coefficient - - eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. - eoRealBoundModifier & bndsModifier; + const VelocityType & c1; // social/cognitive coefficient + const VelocityType & c2; // social/cognitive coefficient + const VelocityType & c3; // social/cognitive coefficient + + eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + eoRng & gen; // the random generator - eoRng & gen; // the random generator - // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOINTEGERVELOCITY_H */ - diff --git a/eo/src/eoInvalidateOps.h b/eo/src/eoInvalidateOps.h index ecc470ab..97dd39f5 100644 --- a/eo/src/eoInvalidateOps.h +++ b/eo/src/eoInvalidateOps.h @@ -57,7 +57,7 @@ class eoInvalidateMonOp : public eoMonOp return true; } - return false; + return false; } private: diff --git a/eo/src/eoLinearTopology.h b/eo/src/eoLinearTopology.h index b7c72416..813e99b9 100644 --- a/eo/src/eoLinearTopology.h +++ b/eo/src/eoLinearTopology.h @@ -48,7 +48,7 @@ public: /** * Build the topology made of _neighborhoodSize neighborhoods. - * @param _neighborhoodSize - The size of each neighborhood. + * @param _neighborhoodSize - The size of each neighborhood. */ eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} @@ -119,7 +119,7 @@ public: */ unsigned retrieveNeighborhoodByIndice(unsigned _indice) { - unsigned i=0; + unsigned i=0; for (i=0;i< neighborhoods.size();i++) { if (neighborhoods[i].contains(_indice)) @@ -131,7 +131,7 @@ public: } /** - * Update the neighborhood: update the particle's best fitness and the best particle + * Update the neighborhood: update the particle's best fitness and the best particle * of the corresponding neighborhood. */ void updateNeighborhood(POT & _po,unsigned _indice) @@ -139,9 +139,9 @@ public: // update the best fitness of the particle if (_po.fitness() > _po.best()) { - _po.best(_po.fitness()); - for(unsigned i=0;i<_po.size();i++) - _po.bestPositions[i]=_po[i]; + _po.best(_po.fitness()); + for(unsigned i=0;i<_po.size();i++) + _po.bestPositions[i]=_po[i]; } // update the best in its neighborhood @@ -166,27 +166,27 @@ public: /* - * Return the global best of the topology - */ - virtual POT & globalBest() + * Return the global best of the topology + */ + virtual POT & globalBest() { - POT gBest,tmp; - unsigned indGlobalBest=0; - if(neighborhoods.size()==1) - return neighborhoods[0].best(); - - gBest=neighborhoods[0].best(); - for(unsigned i=1;i > neighborhoods; + std::vector > neighborhoods; unsigned neighborhoodSize; // the size of each neighborhood - + bool isSetup; }; #endif /*EOLINEARTOPOLOGY_H_ */ - - - - - - - - diff --git a/eo/src/eoMGGReplacement.h b/eo/src/eoMGGReplacement.h index a625e1e8..e2eebbfa 100644 --- a/eo/src/eoMGGReplacement.h +++ b/eo/src/eoMGGReplacement.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoMGGReplacement.h + eoMGGReplacement.h (c) Maarten Keijzer, Marc Schoenauer, 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 @@ -52,18 +52,18 @@ class eoMGGReplacement : public eoReplacement { public: eoMGGReplacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false), - unsigned _tSize=2) : + unsigned _tSize=2) : // split truncates the parents and returns eliminated parents - split(_howManyEliminatedParents, true), + split(_howManyEliminatedParents, true), tSize(_tSize) { if (tSize < 2) - { + { eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; - tSize = 2; + tSize = 2; } } - + void operator()(eoPop & _parents, eoPop & _offspring) { eoPop temp; @@ -71,7 +71,7 @@ public: unsigned toKeep = temp.size(); // how many to keep from merged populations // minimal check if (toKeep < 2) - throw std::runtime_error("Not enough parents killed in eoMGGReplacement"); + throw std::runtime_error("Not enough parents killed in eoMGGReplacement"); // select best offspring typename eoPop::iterator it = _offspring.it_best_element(); @@ -82,21 +82,21 @@ public: // merge temp into offspring plus(temp, _offspring); - + // repeatedly add selected offspring to parents for (unsigned i=0; i split; // few parents to truncate -> linear + eoLinearTruncateSplit split; // few parents to truncate -> linear eoPlus plus; unsigned int tSize; }; diff --git a/eo/src/eoMerge.h b/eo/src/eoMerge.h index 01ada3f9..31da70f0 100644 --- a/eo/src/eoMerge.h +++ b/eo/src/eoMerge.h @@ -4,7 +4,7 @@ // eoMerge.h // Base class for elitist-merging classes // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,13 +36,13 @@ #include /** - * eoMerge: Base class for elitist replacement algorithms. + * eoMerge: Base class for elitist replacement algorithms. * Merges the old population (first argument), with the new generation * * Its signature is exactly - * that of the selection base eoSelect, but its purpose is to merge the + * that of the selection base eoSelect, but its purpose is to merge the * two populations into one (the second argument). - * Note that the algorithms assume that the second argument denotes the + * Note that the algorithms assume that the second argument denotes the * next generation. * * @ingroup Core @@ -55,7 +55,7 @@ template class eoMerge: public eoBF&, eoPop class eoElitism : public eoMerge @@ -66,42 +66,42 @@ public : { if (_interpret_as_rate) { - if ( (_rate<0) || (_rate>1) ) - throw std::logic_error("eoElitism: rate shoud be in [0,1]"); - rate = _rate; + if ( (_rate<0) || (_rate>1) ) + throw std::logic_error("eoElitism: rate shoud be in [0,1]"); + rate = _rate; } else { - if (_rate<0) - throw std::logic_error("Negative number of offspring in eoElitism!"); - combien = (unsigned int)_rate; - if (combien != _rate) - eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl; + if (_rate<0) + throw std::logic_error("Negative number of offspring in eoElitism!"); + combien = (unsigned int)_rate; + if (combien != _rate) + eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl; } } - + void operator()(const eoPop& _pop, eoPop& _offspring) { if ((combien == 0) && (rate == 0.0)) return; unsigned combienLocal; - if (combien == 0) // rate is specified + if (combien == 0) // rate is specified combienLocal = (unsigned int) (rate * _pop.size()); else combienLocal = combien; - + if (combienLocal > _pop.size()) throw std::logic_error("Elite larger than population"); - + std::vector result; _pop.nth_element(combienLocal, result); - + for (size_t i = 0; i < result.size(); ++i) { - _offspring.push_back(*result[i]); + _offspring.push_back(*result[i]); } } - + private : double rate; unsigned combien; @@ -139,4 +139,4 @@ template class eoPlus : public eoMerge //----------------------------------------------------------------------------- -#endif +#endif diff --git a/eo/src/eoMergeReduce.h b/eo/src/eoMergeReduce.h index 8524f1d8..b3cb5b99 100644 --- a/eo/src/eoMergeReduce.h +++ b/eo/src/eoMergeReduce.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoMergeReduce.h + eoMergeReduce.h (c) Maarten Keijzer, 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 @@ -34,7 +34,7 @@ #include #include //----------------------------------------------------------------------------- -/** +/** Replacement strategies that combine en eoMerge and an eoReduce. @class eoMergeReduce, the base (pure abstract) class @@ -43,7 +43,7 @@ Replacement strategies that combine en eoMerge and an eoReduce. */ /** -eoMergeReduce: abstract replacement strategy that is just an application of +eoMergeReduce: abstract replacement strategy that is just an application of an embedded merge, followed by an embedded reduce @ingroup Replacors */ @@ -59,7 +59,7 @@ class eoMergeReduce : public eoReplacement { merge(_parents, _offspring); // parents untouched, result in offspring reduce(_offspring, _parents.size()); - _parents.swap(_offspring); + _parents.swap(_offspring); } private : @@ -98,7 +98,7 @@ class eoCommaReplacement : public eoMergeReduce }; /** -EP type of replacement strategy: first add parents to population, +EP type of replacement strategy: first add parents to population, then truncate using EP tournament @ingroup Replacors */ diff --git a/eo/src/eoNDSorting.h b/eo/src/eoNDSorting.h index b0710b6e..6ab86c17 100644 --- a/eo/src/eoNDSorting.h +++ b/eo/src/eoNDSorting.h @@ -61,35 +61,35 @@ class eoNDSorting : public eoPerf2WorthCached void calculate_worths(const eoPop& _pop) { - // resize the worths beforehand - value().resize(_pop.size()); + // resize the worths beforehand + value().resize(_pop.size()); - typedef typename EOT::Fitness::fitness_traits traits; + typedef typename EOT::Fitness::fitness_traits traits; - switch (traits::nObjectives()) - { - case 1: - { - one_objective(_pop); - return; - } - case 2: - { - two_objectives(_pop); - return; - } - default : - { - m_objectives(_pop); - } - } + switch (traits::nObjectives()) + { + case 1: + { + one_objective(_pop); + return; + } + case 2: + { + two_objectives(_pop); + return; + } + default : + { + m_objectives(_pop); + } + } } private : /** used in fast nondominated sorting - DummyEO is just a storage place for fitnesses and - to store the original index + DummyEO is just a storage place for fitnesses and + to store the original index */ class DummyEO : public EO { @@ -98,8 +98,8 @@ private : void one_objective(const eoPop& _pop) { - unsigned i; - std::vector tmp_pop; + unsigned i; + std::vector tmp_pop; tmp_pop.resize(_pop.size()); // copy pop to dummy population (only need the fitnesses) @@ -109,14 +109,14 @@ private : tmp_pop[i].index = i; } - std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater()); + std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater()); for (i = 0; i < _pop.size(); ++i) { value()[tmp_pop[i].index] = _pop.size() - i; // set rank } - // no point in calculcating niche penalty, as every distinct fitness value has a distinct rank + // no point in calculcating niche penalty, as every distinct fitness value has a distinct rank } /** @@ -139,134 +139,134 @@ private : void two_objectives(const eoPop& _pop) { - unsigned i; - typedef typename EOT::Fitness::fitness_traits traits; - assert(traits::nObjectives() == 2); + unsigned i; + typedef typename EOT::Fitness::fitness_traits traits; + assert(traits::nObjectives() == 2); - std::vector sort1(_pop.size()); // index into population sorted on first objective + std::vector sort1(_pop.size()); // index into population sorted on first objective - for (i = 0; i < _pop.size(); ++i) - { - sort1[i] = i; - } + for (i = 0; i < _pop.size(); ++i) + { + sort1[i] = i; + } - std::sort(sort1.begin(), sort1.end(), Sorter(_pop)); + std::sort(sort1.begin(), sort1.end(), Sorter(_pop)); - // Ok, now the meat of the algorithm + // Ok, now the meat of the algorithm - unsigned last_front = 0; + unsigned last_front = 0; - double max1 = -1e+20; - for (i = 0; i < _pop.size(); ++i) - { - max1 = std::max(max1, _pop[i].fitness()[1]); - } + double max1 = -1e+20; + for (i = 0; i < _pop.size(); ++i) + { + max1 = std::max(max1, _pop[i].fitness()[1]); + } - max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound + max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound - unsigned prev_front = 0; - std::vector d; - d.resize(_pop.size(), max1); // initialize with the value max1 everywhere + unsigned prev_front = 0; + std::vector d; + d.resize(_pop.size(), max1); // initialize with the value max1 everywhere - std::vector > fronts(_pop.size()); // to store indices into the front + std::vector > fronts(_pop.size()); // to store indices into the front - for (i = 0; i < _pop.size(); ++i) - { - unsigned index = sort1[i]; + for (i = 0; i < _pop.size(); ++i) + { + unsigned index = sort1[i]; - // check for clones and delete them - if (i > 0) - { - unsigned prev = sort1[i-1]; - if ( _pop[index].fitness() == _pop[prev].fitness()) - { // it's a clone, give it the worst rank! + // check for clones and delete them + if (i > 0) + { + unsigned prev = sort1[i-1]; + if ( _pop[index].fitness() == _pop[prev].fitness()) + { // it's a clone, give it the worst rank! - if (nasty_declone_flag_that_only_is_implemented_for_two_objectives) - //declone - fronts.back().push_back(index); - else // assign it the rank of the previous - fronts[prev_front].push_back(index); - continue; - } - } + if (nasty_declone_flag_that_only_is_implemented_for_two_objectives) + //declone + fronts.back().push_back(index); + else // assign it the rank of the previous + fronts[prev_front].push_back(index); + continue; + } + } - double value2 = _pop[index].fitness()[1]; + double value2 = _pop[index].fitness()[1]; - if (traits::maximizing(1)) - value2 = max1 - value2; + if (traits::maximizing(1)) + value2 = max1 - value2; - // perform binary search using std::upper_bound, a log n operation for each member - std::vector::iterator it = - std::upper_bound(d.begin(), d.begin() + last_front, value2); + // perform binary search using std::upper_bound, a log n operation for each member + std::vector::iterator it = + std::upper_bound(d.begin(), d.begin() + last_front, value2); - unsigned front = unsigned(it - d.begin()); - if (front == last_front) ++last_front; + unsigned front = unsigned(it - d.begin()); + if (front == last_front) ++last_front; - assert(it != d.end()); + assert(it != d.end()); - *it = value2; //update d - fronts[front].push_back(index); // add it to the front + *it = value2; //update d + fronts[front].push_back(index); // add it to the front - prev_front = front; - } + prev_front = front; + } - // ok, and finally the niche penalty + // ok, and finally the niche penalty - for (i = 0; i < fronts.size(); ++i) - { - if (fronts[i].size() == 0) continue; + for (i = 0; i < fronts.size(); ++i) + { + if (fronts[i].size() == 0) continue; - // Now we have the indices to the current front in current_front, do the niching - std::vector niche_count = niche_penalty(fronts[i], _pop); + // Now we have the indices to the current front in current_front, do the niching + std::vector niche_count = niche_penalty(fronts[i], _pop); - // Check whether the derived class was nice - if (niche_count.size() != fronts[i].size()) - { - throw std::logic_error("eoNDSorting: niche and front should have the same size"); - } + // Check whether the derived class was nice + if (niche_count.size() != fronts[i].size()) + { + throw std::logic_error("eoNDSorting: niche and front should have the same size"); + } - double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); + double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); - for (unsigned j = 0; j < fronts[i].size(); ++j) - { - value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next - } + for (unsigned j = 0; j < fronts[i].size(); ++j) + { + value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next + } - } + } - // invert ranks to obtain a 'bigger is better' score - rank_to_worth(); + // invert ranks to obtain a 'bigger is better' score + rank_to_worth(); } class Sorter { - public: - Sorter(const eoPop& _pop) : pop(_pop) {} + public: + Sorter(const eoPop& _pop) : pop(_pop) {} - bool operator()(unsigned i, unsigned j) const - { - typedef typename EOT::Fitness::fitness_traits traits; + bool operator()(unsigned i, unsigned j) const + { + typedef typename EOT::Fitness::fitness_traits traits; - double diff = pop[i].fitness()[0] - pop[j].fitness()[0]; + double diff = pop[i].fitness()[0] - pop[j].fitness()[0]; - if (fabs(diff) < traits::tol()) - { - diff = pop[i].fitness()[1] - pop[j].fitness()[1]; + if (fabs(diff) < traits::tol()) + { + diff = pop[i].fitness()[1] - pop[j].fitness()[1]; - if (fabs(diff) < traits::tol()) - return false; + if (fabs(diff) < traits::tol()) + return false; - if (traits::maximizing(1)) - return diff > 0.; - return diff < 0.; - } + if (traits::maximizing(1)) + return diff > 0.; + return diff < 0.; + } - if (traits::maximizing(0)) - return diff > 0.; - return diff < 0.; - } + if (traits::maximizing(0)) + return diff > 0.; + return diff < 0.; + } - const eoPop& pop; + const eoPop& pop; }; void m_objectives(const eoPop& _pop) @@ -485,7 +485,7 @@ class eoNDSorting_II : public eoNDSorting for (i = 0; i < nc.size(); ++i) { - niche_count[i] += (max_dist + 1 - nc[i]); + niche_count[i] += (max_dist + 1 - nc[i]); } } diff --git a/eo/src/eoNeighborhood.h b/eo/src/eoNeighborhood.h index fa0edd3f..804dc107 100644 --- a/eo/src/eoNeighborhood.h +++ b/eo/src/eoNeighborhood.h @@ -47,22 +47,11 @@ public: virtual POT & best()=0; virtual void best(POT _particle)=0; - + /// Virtual dtor - virtual ~eoNeighborhood() {}; + virtual ~eoNeighborhood() {}; }; #endif /* EONEIGHBORHOOD_H_ */ - - - - - - - - - - - diff --git a/eo/src/eoObject.h b/eo/src/eoObject.h index 2e59f190..bac2f473 100644 --- a/eo/src/eoObject.h +++ b/eo/src/eoObject.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoObject.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -34,9 +34,9 @@ #include /* -eoObject used to be the base class for the whole hierarchy, but this has -changed. eoObject is used to define a name (#className#) -that is used when loading or saving the state. +eoObject used to be the base class for the whole hierarchy, but this has +changed. eoObject is used to define a name (#className#) +that is used when loading or saving the state. Previously, this object also defined a print and read interface, but it´s been moved to eoPrintable and eoPersistent. @@ -58,19 +58,18 @@ class eoObject public: /// Virtual dtor. They are needed in virtual class hierarchies. virtual ~eoObject() {} - - /** Return the class id. This should be redefined in each class. + + /** Return the class id. This should be redefined in each class. Only "leaf" classes can be non-virtual. - Maarten: removed the default implementation as this proved to - be too error-prone: I found several classes that had a typo in + Maarten: removed the default implementation as this proved to + be too error-prone: I found several classes that had a typo in className (like classname), which would print eoObject instead of - their own. Having it pure will force the implementor to provide a + their own. Having it pure will force the implementor to provide a name. */ - virtual std::string className() const = 0; + virtual std::string className() const = 0; }; #endif - diff --git a/eo/src/eoOneToOneBreeder.h b/eo/src/eoOneToOneBreeder.h index 2e593333..a4c18c0b 100644 --- a/eo/src/eoOneToOneBreeder.h +++ b/eo/src/eoOneToOneBreeder.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoOneToOneBreeder.h +// eoOneToOneBreeder.h // (c) Maarten Keijzer and Marc Schoenauer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -38,12 +38,12 @@ #include #include -/** eoOneToOneBreeder: transforms a population using +/** eoOneToOneBreeder: transforms a population using * - an operator that MODIFIES only one parent from the populator * (though it can use any number aside) and thus generates ONE offspring) * - a local replacement between the parent and its offspring * - * Typically, Differential Evolution (Storn and Price 94) and Deb et al's + * Typically, Differential Evolution (Storn and Price 94) and Deb et al's * G3 can be built on this * * @ingroup Combination @@ -54,16 +54,16 @@ class eoOneToOneBreeder: public eoBreed public: /** Ctor: * @param _op a general operator (must MODIFY only ONE parent) - * @param _eval an eoEvalFunc to evaluate the offspring + * @param _eval an eoEvalFunc to evaluate the offspring * @param _pReplace probability that the best of parent/offspring wins [1] * @param _howMany eoHowMany offpsring to generate [100%] */ eoOneToOneBreeder( eoGenOp& _op, - eoEvalFunc & _eval, - double _pReplace = 1.0, - eoHowMany _howMany = eoHowMany(1.0) ) : - op(_op), eval(_eval), select( false ), + eoEvalFunc & _eval, + double _pReplace = 1.0, + eoHowMany _howMany = eoHowMany(1.0) ) : + op(_op), eval(_eval), select( false ), pReplace(_pReplace), howMany(_howMany) {} @@ -77,34 +77,34 @@ class eoOneToOneBreeder: public eoBreed void operator()(const eoPop& _parents, eoPop& _offspring) { unsigned target = howMany(_parents.size()); - + _offspring.clear(); eoSelectivePopulator popit(_parents, _offspring, select); - + for (unsigned iParent=0; iParent leOffspring) // old parent better than offspring - if (rng.uniform() < pReplace) // if probability - leOffspring = theParent; // replace - // finally, go to next guy to handle - ++popit; - } + // do the tournament between parent and offspring + eval(leOffspring); // first need to evaluate the offspring + if (theParent > leOffspring) // old parent better than offspring + if (rng.uniform() < pReplace) // if probability + leOffspring = theParent; // replace + // finally, go to next guy to handle + ++popit; + } } /// The class name. @@ -119,4 +119,3 @@ class eoOneToOneBreeder: public eoBreed }; #endif - diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index bd9fe4e1..b6ad783c 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoOp.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -18,7 +18,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - CVS Info: $Date: 2004-08-10 17:19:46 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoOp.h,v 1.29 2004-08-10 17:19:46 jmerelo Exp $ $Author: jmerelo $ + CVS Info: $Date: 2004-08-10 17:19:46 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoOp.h,v 1.29 2004-08-10 17:19:46 jmerelo Exp $ $Author: jmerelo $ */ //----------------------------------------------------------------------------- @@ -171,13 +171,13 @@ public: */ bool operator()(EOT & _eo1, const EOT & _eo2) { - EOT eoTmp = _eo2; // a copy that can be modified + EOT eoTmp = _eo2; // a copy that can be modified // if the embedded eoQuadOp is not symmetrical, // the result might be biased - hence the flip ... if (eo::rng.flip(0.5)) - return quadOp(_eo1, eoTmp); // both are modified - that's all + return quadOp(_eo1, eoTmp); // both are modified - that's all else - return quadOp(eoTmp, _eo1); // both are modified - that's all + return quadOp(eoTmp, _eo1); // both are modified - that's all } private: diff --git a/eo/src/eoOpContainer.h b/eo/src/eoOpContainer.h index d295f0ce..e1f43bdf 100644 --- a/eo/src/eoOpContainer.h +++ b/eo/src/eoOpContainer.h @@ -100,7 +100,7 @@ public: void apply(eoPopulator& _pop) { - _pop.reserve( this->max_production() ); + _pop.reserve( this->max_production() ); position_type pos = _pop.tellp(); for (size_t i = 0; i < rates.size(); ++i) { @@ -118,10 +118,10 @@ public: // } // check for out of individuals and do nothing with that... // catch(eoPopulator::OutOfIndividuals&) - // { + // { // std::cout << "Warning: not enough individuals to handle\n"; // return ; - // } + // } } if (!_pop.exhausted()) @@ -156,7 +156,7 @@ public: try { (*ops[i])(_pop); - ++_pop; + ++_pop; } catch( typename eoPopulator::OutOfIndividuals&) {} @@ -166,4 +166,3 @@ public: #endif - diff --git a/eo/src/eoOpSelMason.h b/eo/src/eoOpSelMason.h index 791b2607..577b5b56 100644 --- a/eo/src/eoOpSelMason.h +++ b/eo/src/eoOpSelMason.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoOpSelMason.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,72 +36,72 @@ to the objects it builds, and then deallocate it when it gets out of scope */ template class eoOpSelMason: public eoFactory > { - + public: - typedef std::vector* > vOpP; - typedef map*, vOpP > MEV; + typedef std::vector* > vOpP; + typedef map*, vOpP > MEV; - /// @name ctors and dtors - //{@ - /// constructor - eoOpSelMason( eoOpFactory& _opFact): operatorFactory( _opFact ) {}; - - /// destructor - virtual ~eoOpSelMason() {}; - //@} + /// @name ctors and dtors + //{@ + /// constructor + eoOpSelMason( eoOpFactory& _opFact): operatorFactory( _opFact ) {}; - /** Factory methods: creates an object from an std::istream, reading from - it whatever is needed to create the object. The format is - opSelClassName\\ - rate 1 operator1\\ - rate 2 operator2\\ - ...\\ - Stores all operators built in a database (#allocMap#), so that somebody - can destroy them later. The Mason is in charge or destroying the operators, - since the built object can´t do it itself. The objects built must be destroyed - from outside, using the "destroy" method - */ - virtual eoOpSelector* make(std::istream& _is) { + /// destructor + virtual ~eoOpSelMason() {}; + //@} - std::string opSelName; - _is >> opSelName; - eoOpSelector* opSelectorP; - // Build the operator selector - if ( opSelName == "eoProportionalOpSel" ) { - opSelectorP = new eoProportionalOpSel(); - } + /** Factory methods: creates an object from an std::istream, reading from + it whatever is needed to create the object. The format is + opSelClassName\\ + rate 1 operator1\\ + rate 2 operator2\\ + ...\\ + Stores all operators built in a database (#allocMap#), so that somebody + can destroy them later. The Mason is in charge or destroying the operators, + since the built object can´t do it itself. The objects built must be destroyed + from outside, using the "destroy" method + */ + virtual eoOpSelector* make(std::istream& _is) { - // Temp std::vector for storing pointers - vOpP tmpPVec; - // read operator rate and name - while ( _is ) { - float rate; - _is >> rate; - if ( _is ) { - eoOp* op = operatorFactory.make( _is ); // This reads the rest of the line - // Add the operators to the selector, don´t pay attention to the IDs - opSelectorP->addOp( *op, rate ); - // Keep it in the store, to destroy later - tmpPVec.push_back( op ); - } // if - } // while + std::string opSelName; + _is >> opSelName; + eoOpSelector* opSelectorP; + // Build the operator selector + if ( opSelName == "eoProportionalOpSel" ) { + opSelectorP = new eoProportionalOpSel(); + } - // Put it in the map - allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) ); - - return opSelectorP; - }; + // Temp std::vector for storing pointers + vOpP tmpPVec; + // read operator rate and name + while ( _is ) { + float rate; + _is >> rate; + if ( _is ) { + eoOp* op = operatorFactory.make( _is ); // This reads the rest of the line + // Add the operators to the selector, don´t pay attention to the IDs + opSelectorP->addOp( *op, rate ); + // Keep it in the store, to destroy later + tmpPVec.push_back( op ); + } // if + } // while - ///@name eoObject methods - //@{ - /** Return the class id */ - virtual std::string className() const { return "eoOpSelMason"; } + // Put it in the map + allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) ); + + return opSelectorP; + }; + + ///@name eoObject methods + //@{ + /** Return the class id */ + virtual std::string className() const { return "eoOpSelMason"; } + + //@} - //@} - private: - map*,std::vector* > > allocMap; - eoOpFactory& operatorFactory; + map*,std::vector* > > allocMap; + eoOpFactory& operatorFactory; }; diff --git a/eo/src/eoOrderXover.h b/eo/src/eoOrderXover.h index 0c98990d..daaf52e0 100644 --- a/eo/src/eoOrderXover.h +++ b/eo/src/eoOrderXover.h @@ -10,7 +10,7 @@ #include #include -#include +#include /** * apply orderXover on two chromosomes. @@ -26,65 +26,65 @@ template class eoOrderXover: public eoQuadOp { public: - /// The class name. - virtual std::string className() const { return "eoOrderXover"; } + /// The class name. + virtual std::string className() const { return "eoOrderXover"; } + + /** + * @return true if the chromosome has changed + * @param _chrom1 The first chromosome which will be crossed with chrom2. + * @param _chrom2 The second chromosome which will be crossed with chrom1. + */ + bool operator()(Chrom& _chrom1, Chrom& _chrom2){ + + char direction=eo::rng.flip()? 1 : -1; + unsigned cut2= 1 + eo::rng.random(_chrom1.size()); + unsigned cut1= eo::rng.random(cut2); + Chrom tmp1= _chrom1; + Chrom tmp2= _chrom2; + + cross(tmp1, tmp2, _chrom1, direction, cut1, cut2); + cross(tmp2, tmp1, _chrom2, direction, cut1, cut2); + + _chrom1.invalidate(); + _chrom2.invalidate(); + + return true; + } - /** - * @return true if the chromosome has changed - * @param _chrom1 The first chromosome which will be crossed with chrom2. - * @param _chrom2 The second chromosome which will be crossed with chrom1. - */ - bool operator()(Chrom& _chrom1, Chrom& _chrom2){ - - char direction=eo::rng.flip()? 1 : -1; - unsigned cut2= 1 + eo::rng.random(_chrom1.size()); - unsigned cut1= eo::rng.random(cut2); - Chrom tmp1= _chrom1; - Chrom tmp2= _chrom2; - - cross(tmp1, tmp2, _chrom1, direction, cut1, cut2); - cross(tmp2, tmp1, _chrom2, direction, cut1, cut2); - - _chrom1.invalidate(); - _chrom2.invalidate(); - - return true; - } - private: - - /** - * @param _chrom1 The first parent chromosome. - * @param _chrom2 The second parent chromosome. - * @param _child The result chromosome. - * @param _direction The direction of the OrderXover (left: -1 or right: 1) - * @param _cut1 index of the first cut - * @param _cut2 index of the second cut - */ - void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){ - - unsigned size, id=0, from=0; - size= _chrom1.size(); - std::vector verif(size, false); - - for(unsigned i= _cut1; i<_cut2; i++){ - _child[id++]= _chrom1[i]; - verif[_chrom1[i] % size] = true; - } - - while(_chrom2[from] != _child[_cut2 - 1]) - from++; - - for(unsigned i=0; i verif(size, false); + + for(unsigned i= _cut1; i<_cut2; i++){ + _child[id++]= _chrom1[i]; + verif[_chrom1[i] % size] = true; + } + + while(_chrom2[from] != _child[_cut2 - 1]) + from++; + + for(unsigned i=0; i class eoInitializerBase : public eoFunctorBase }; /** - Base (name) class for Initialization of algorithm PSO + Base (name) class for Initialization of algorithm PSO - @see eoInitializerBase eoUF apply + @see eoInitializerBase eoUF apply */ template class eoParticleInitializer : public eoInitializerBase { @@ -99,34 +99,34 @@ template class eoParticleInitializer : public eoInitializerBase empty_pop; - - // evaluates using either the "sequential" evaluator ... - apply(proc, pop); - - // ... or the parallel one - procPara(empty_pop, pop); - - // no matter what is the eval operator, initializes the velocities and the particle's best + eoPop empty_pop; + + // evaluates using either the "sequential" evaluator ... + apply(proc, pop); + + // ... or the parallel one + procPara(empty_pop, pop); + + // no matter what is the eval operator, initializes the velocities and the particle's best apply < POT > (initVelo, pop); apply < POT > (initBest, pop); - + // finally setup the topology. We have now all we need to do so. - topology.setup(pop); + topology.setup(pop); } private : /* - @param proc First evaluation - @param initVelo Initialization of the velocity - @param initBest Initialization of the best - + @param proc First evaluation + @param initVelo Initialization of the velocity + @param initBest Initialization of the best + */ eoPop < POT > & pop; eoUF& proc; @@ -146,11 +146,10 @@ template class eoParticleInitializer : public eoInitializerBase class eoPeriodicContinue: public eoContinue { public: - - /** Constructor. The period is given in parameter. */ - eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) : - period (__period), counter (__init_counter) + + /** Constructor. The period is given in parameter. */ + eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) : + period (__period), counter (__init_counter) {} /** It returns 'true' only if the current number of generations modulo - the period doen't equal to zero. */ + the period doen't equal to zero. */ bool operator () (const eoPop & pop) { return ((++ counter) % period) != 0 ; } - + private: unsigned period; - + unsigned counter; }; #endif - diff --git a/eo/src/eoPersistent.cpp b/eo/src/eoPersistent.cpp index 63e906ca..c1334ebc 100644 --- a/eo/src/eoPersistent.cpp +++ b/eo/src/eoPersistent.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include diff --git a/eo/src/eoPersistent.h b/eo/src/eoPersistent.h index 7c2f609e..ed3f581e 100644 --- a/eo/src/eoPersistent.h +++ b/eo/src/eoPersistent.h @@ -6,7 +6,7 @@ // eoPersistent.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -48,14 +48,14 @@ class eoPersistent: public eoPrintable public: /// Virtual dtor. They are needed in virtual class hierarchies. virtual ~eoPersistent() {} - + /** * Read object. * @param _is A std::istream. * @throw runtime_std::exception If a valid object can't be read. */ virtual void readFrom(std::istream& _is) = 0; - + }; ///Standard input for all objects in the EO hierarchy diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index 5c63fb40..3ea53f46 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoPop.h +// eoPop.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,16 +36,16 @@ #include #include // for shuffle method -/** A std::vector of EO object, to be used in all algorithms +/** A std::vector of EO object, to be used in all algorithms * (selectors, operators, replacements, ...). * * We have no idea if a population can be * some other thing that a std::vector, but if somebody thinks of it, this concrete - * implementation can be moved to "generic" and an abstract Population + * implementation can be moved to "generic" and an abstract Population * interface be provided. * - * The template can be instantiated with anything that accepts a "size" - * and eoInit derived object. in the ctor. + * The template can be instantiated with anything that accepts a "size" + * and eoInit derived object. in the ctor. * EOT must also have a copy ctor, since temporaries are created and then * passed to the eoInit object * @@ -55,62 +55,62 @@ template class eoPop: public std::vector, public eoObject, public eoPersistent { public: - + using std::vector::size; using std::vector::resize; using std::vector::operator[]; using std::vector::begin; using std::vector::end; - + typedef typename EOT::Fitness Fitness; #if defined(__CUDACC__) typedef typename std::vector::iterator iterator; typedef typename std::vector::const_iterator const_iterator; #endif - /** Default ctor. Creates empty pop - */ - eoPop() : std::vector(), eoObject(), eoPersistent() {}; - - /** Ctor for the initialization of chromosomes - - @param _popSize total population size - @param _chromInit Initialization routine, produces EO's, needs to be an eoInit - */ + /** Default ctor. Creates empty pop + */ + eoPop() : std::vector(), eoObject(), eoPersistent() {}; + + /** Ctor for the initialization of chromosomes + + @param _popSize total population size + @param _chromInit Initialization routine, produces EO's, needs to be an eoInit + */ eoPop( unsigned _popSize, eoInit& _chromInit ) - :std::vector() + :std::vector() { resize(_popSize); - for ( unsigned i = 0; i < _popSize; i++ ) + for ( unsigned i = 0; i < _popSize; i++ ) { - _chromInit(operator[](i)); - } - }; + _chromInit(operator[](i)); + } + }; - /** appends random guys at end of pop. - Can be used to initialize it pop is empty - - @param _newPopSize total population size - @param _chromInit Initialization routine, produces EO's, needs to be an eoInit - */ + /** appends random guys at end of pop. + Can be used to initialize it pop is empty + + @param _newPopSize total population size + @param _chromInit Initialization routine, produces EO's, needs to be an eoInit + */ void append( unsigned _newPopSize, eoInit& _chromInit ) { unsigned oldSize = size(); if (_newPopSize < oldSize) - { - throw std::runtime_error("New size smaller than old size in pop.append"); - return; - } + { + throw std::runtime_error("New size smaller than old size in pop.append"); + return; + } if (_newPopSize == oldSize) - return; - resize(_newPopSize); // adjust the size + return; + resize(_newPopSize); // adjust the size for ( unsigned i = oldSize; i < _newPopSize; i++ ) - { - _chromInit(operator[](i)); - } + { + _chromInit(operator[](i)); + } }; - - + + /** Ctor from an std::istream; reads the population from a stream, each element should be in different lines @param _is the stream @@ -118,9 +118,9 @@ public: eoPop( std::istream& _is ) :std::vector() { readFrom( _is ); } - + /** Empty Dtor */ - virtual ~eoPop() {} + virtual ~eoPop() {} /// helper struct for getting a pointer @@ -130,16 +130,16 @@ public: bool operator()(const EOT* a, const EOT* b) const { return b->operator<(*a); } }; - /// helper struct for comparing (EA or PSO) - struct Cmp2 - { - bool operator()(const EOT & a,const EOT & b) const - { - return b.operator<(a); - } - }; - - + /// helper struct for comparing (EA or PSO) + struct Cmp2 + { + bool operator()(const EOT & a,const EOT & b) const + { + return b.operator<(a); + } + }; + + /** sort the population. Use this member to sort in order @@ -185,10 +185,10 @@ public: #if defined(__CUDACC__) eoPop::iterator it_best_element() { - eoPop:: iterator it = std::max_element(begin(), end()); + eoPop:: iterator it = std::max_element(begin(), end()); #else - typename eoPop::iterator it_best_element() { - typename eoPop::iterator it = std::max_element(begin(), end()); + typename eoPop::iterator it_best_element() { + typename eoPop::iterator it = std::max_element(begin(), end()); #endif return it; } @@ -199,7 +199,7 @@ public: #if defined(__CUDACC__) eoPop::const_iterator it = std::max_element(begin(), end()); #else - typename eoPop::const_iterator it = std::max_element(begin(), end()); + typename eoPop::const_iterator it = std::max_element(begin(), end()); #endif return (*it); } @@ -210,7 +210,7 @@ public: #if defined(__CUDACC__) eoPop::const_iterator it = std::min_element(begin(), end()); #else - typename eoPop::const_iterator it = std::min_element(begin(), end()); + typename eoPop::const_iterator it = std::min_element(begin(), end()); #endif return (*it); } @@ -221,9 +221,9 @@ public: { eoPop::iterator it = std::min_element(begin(), end()); #else - typename eoPop::iterator it_worse_element() + typename eoPop::iterator it_worse_element() { - typename eoPop::iterator it = std::min_element(begin(), end()); + typename eoPop::iterator it = std::min_element(begin(), end()); #endif return it; } @@ -232,25 +232,25 @@ public: slightly faster algorithm than sort to find all individuals that are better than the nth individual. INDIVIDUALS ARE MOVED AROUND in the pop. */ -#if defined(__CUDACC__) +#if defined(__CUDACC__) eoPop::iterator nth_element(int nth) { eoPop::iterator it = begin() + nth; #else - typename eoPop::iterator nth_element(int nth) + typename eoPop::iterator nth_element(int nth) { - typename eoPop::iterator it = begin() + nth; + typename eoPop::iterator it = begin() + nth; #endif std::nth_element(begin(), it, end(), std::greater()); return it; } struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } }; - + /** returns the fitness of the nth element */ Fitness nth_element_fitness(int which) const { // probably not the fastest way to do this, but what the heck - + std::vector fitness(size()); std::transform(begin(), end(), fitness.begin(), GetFitness()); @@ -259,15 +259,15 @@ public: return *it; } - /** const nth_element function, returns pointers to sorted individuals - * up the the nth + /** const nth_element function, returns pointers to sorted individuals + * up the the nth */ void nth_element(int which, std::vector& result) const { result.resize(size()); std::transform(begin(), end(), result.begin(), Ref()); - + typename std::vector::iterator it = result.begin() + which; std::nth_element(result.begin(), it, result.end(), Cmp()); @@ -278,28 +278,28 @@ public: { std::swap(static_cast& >(*this), static_cast& >(other)); } - + /** * Prints sorted pop but does NOT modify it! * - * @param _os A std::ostream. + * @param _os A std::ostream. */ - virtual void sortedPrintOn(std::ostream& _os) const + virtual void sortedPrintOn(std::ostream& _os) const { std::vector result; sort(result); _os << size() << '\n'; for (unsigned i = 0; i < size(); ++i) { - _os << *result[i] << std::endl; + _os << *result[i] << std::endl; } } /** * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A std::ostream. + * @param _os A std::ostream. */ - virtual void printOn(std::ostream& _os) const + virtual void printOn(std::ostream& _os) const { _os << size() << '\n'; std::copy( begin(), end(), std::ostream_iterator( _os, "\n") ); @@ -309,16 +309,16 @@ public: //@{ /** * Read object. The EOT class must have a ctor from a stream; - * @param _is A std::istream. + * @param _is A std::istream. */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { size_t sz; _is >> sz; resize(sz); - for (size_t i = 0; i < sz; ++i) { + for (size_t i = 0; i < sz; ++i) { operator[](i).readFrom( _is ); } } @@ -337,4 +337,3 @@ public: }; #endif - diff --git a/eo/src/eoPopEvalFunc.h b/eo/src/eoPopEvalFunc.h index 2753e957..aba74d9a 100644 --- a/eo/src/eoPopEvalFunc.h +++ b/eo/src/eoPopEvalFunc.h @@ -5,7 +5,7 @@ Abstract class for global evaluation of the population (c) GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,32 +30,32 @@ #include #include -/** eoPopEvalFunc: This abstract class is for GLOBAL evaluators +/** eoPopEvalFunc: This abstract class is for GLOBAL evaluators * of a population after variation. * It takes 2 populations (typically the parents and the offspring) * and is suppposed to evaluate them alltogether * - * Basic use: apply an embedded eoEvalFunc to the offspring + * Basic use: apply an embedded eoEvalFunc to the offspring * - * Time-varying fitness: apply the embedded eoEvalFunc to both + * Time-varying fitness: apply the embedded eoEvalFunc to both * offspring and parents * * Advanced uses: Co-evolution or "parisian" approach, or ... * - * Basic parallelization (synchronous standard evolution engine): + * Basic parallelization (synchronous standard evolution engine): * call the slaves and wait for the results * * @ingroup Evaluation */ template -class eoPopEvalFunc : public eoBF & , eoPop &, void> +class eoPopEvalFunc : public eoBF & , eoPop &, void> {}; ///////////////////////////////////////////////////////////// // eoPopLoopEval ///////////////////////////////////////////////////////////// -/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies +/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies * a private eoEvalFunc to all offspring * * @ingroup Evaluation @@ -81,9 +81,9 @@ private: // eoTimeVaryingLoopEval ///////////////////////////////////////////////////////////// -/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies +/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies * a private eoEvalFunc to all offspring AND ALL PARENTS - * as the fitness is supposed here to vary + * as the fitness is supposed here to vary * * @ingroup Evaluation */ @@ -105,4 +105,3 @@ private: }; #endif - diff --git a/eo/src/eoPopulator.h b/eo/src/eoPopulator.h index eaf8f841..104aafe5 100644 --- a/eo/src/eoPopulator.h +++ b/eo/src/eoPopulator.h @@ -209,4 +209,3 @@ private: }; #endif - diff --git a/eo/src/eoPrintable.cpp b/eo/src/eoPrintable.cpp index a68536a5..ec6e3246 100644 --- a/eo/src/eoPrintable.cpp +++ b/eo/src/eoPrintable.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif //----------------------------------------------------------------------------- // eoPrintable.cpp @@ -14,9 +14,8 @@ //----------------------------------------------------------------------------- std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ) { - _o.printOn(_os); - return _os; + _o.printOn(_os); + return _os; } //----------------------------------------------------------------------------- - diff --git a/eo/src/eoPrintable.h b/eo/src/eoPrintable.h index 9d419047..1f2404a8 100644 --- a/eo/src/eoPrintable.h +++ b/eo/src/eoPrintable.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoPrintable.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -37,7 +37,7 @@ some objects (for instance, a #eoFactory# or a random number generator. /** Base class for objects that can print themselves -(#printOn#). Besides, this file defines the standard output for all the objects; +(#printOn#). Besides, this file defines the standard output for all the objects; if the objects define printOn there's no need to define "operator<<". @ingroup Core @@ -47,7 +47,7 @@ class eoPrintable public: /// Virtual dtor. They are needed in virtual class hierarchies. virtual ~eoPrintable() {} - + /** * Write object. It's called printOn since it prints the object on a stream. * @param _os A std::ostream. @@ -60,4 +60,3 @@ class eoPrintable std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ); #endif - diff --git a/eo/src/eoPropGAGenOp.h b/eo/src/eoPropGAGenOp.h index 44ccc7a5..5d2fd79c 100644 --- a/eo/src/eoPropGAGenOp.h +++ b/eo/src/eoPropGAGenOp.h @@ -33,36 +33,36 @@ // class eoSGAGenOp /////////////////////////////////////////////////////////////////////////////// -/** - * eoPropGAGenOp (for Simple GA, but Proportional) - * choice between Crossover, mutation or cloining +/** + * eoPropGAGenOp (for Simple GA, but Proportional) + * choice between Crossover, mutation or cloining * with respect to given relatve weights * * @ingroup Combination */ -template +template class eoPropGAGenOp : public eoGenOp { public: - - /** Ctor from + + /** Ctor from * * weight of clone * * crossover (with weight) * * mutation (with weight) */ - eoPropGAGenOp(double _wClone, eoQuadOp& _cross, double _wCross, - eoMonOp& _mut, double _wMut) + eoPropGAGenOp(double _wClone, eoQuadOp& _cross, double _wCross, + eoMonOp& _mut, double _wMut) : wClone(_wClone), cross(_cross), wCross(_wCross), - mut(_mut), - wMut(_wMut) + mut(_mut), + wMut(_wMut) { propOp.add(cross, wCross); // the crossover - with weight wCross propOp.add(mut, wMut); // mutation with weight wMut propOp.add(monClone, wClone); } - + /** do the job: delegate to op */ virtual void apply(eoPopulator& _pop) { diff --git a/eo/src/eoProportionalCombinedOp.h b/eo/src/eoProportionalCombinedOp.h index 892c9b47..123c634b 100644 --- a/eo/src/eoProportionalCombinedOp.h +++ b/eo/src/eoProportionalCombinedOp.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoCombinedOp.h // (c) GeNeura Team, 1998, Marc Schoenauer, 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 @@ -105,7 +105,7 @@ public: virtual bool operator()(EOT & _indi) { unsigned what = rng.roulette_wheel(rates); // choose one op - return (*ops[what])(_indi); // apply it + return (*ops[what])(_indi); // apply it } protected: std::vector*> ops; @@ -139,20 +139,20 @@ virtual void add(eoBinOp & _op, const double _rate, bool _verbose=false) // compute the relative rates in percent - to warn the user! if (_verbose) { - double total = 0; - unsigned i; - for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %" << std::endl; + for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %" << std::endl; } } virtual void operator()(EOT & _indi1, const EOT & _indi2) { unsigned what = rng.roulette_wheel(rates); // choose one op index - return (*ops[what])(_indi1, _indi2); // apply it + return (*ops[what])(_indi1, _indi2); // apply it } private: std::vector*> ops; @@ -216,7 +216,7 @@ public: virtual bool operator()(EOT & _indi1, EOT & _indi2) { unsigned what = rng.roulette_wheel(rates); // choose one op index - return (*ops[what])(_indi1, _indi2); // apply it + return (*ops[what])(_indi1, _indi2); // apply it } private: std::vector*> ops; diff --git a/eo/src/eoProportionalSelect.h b/eo/src/eoProportionalSelect.h index bd788048..daa4428d 100644 --- a/eo/src/eoProportionalSelect.h +++ b/eo/src/eoProportionalSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoProportionalSelect.h // (c) GeNeura Team, 1998 - EEAAX 1999, Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,18 +35,18 @@ #include /** eoProportionalSelect: select an individual proportional to her stored fitness - value - - Changed the algorithm to make use of a cumulative array of fitness scores, + value + + Changed the algorithm to make use of a cumulative array of fitness scores, This changes the algorithm from O(n) per call to O(log n) per call. (MK) @ingroup Selectors */ -template class eoProportionalSelect: public eoSelectOne +template class eoProportionalSelect: public eoSelectOne { public: /// Sanity check - eoProportionalSelect(const eoPop& pop = eoPop()) + eoProportionalSelect(const eoPop& pop = eoPop()) { if (minimizing_fitness()) throw std::logic_error("eoProportionalSelect: minimizing fitness"); @@ -55,23 +55,23 @@ public: void setup(const eoPop& _pop) { if (_pop.size() == 0) return; - + cumulative.resize(_pop.size()); cumulative[0] = _pop[0].fitness(); - for (unsigned i = 1; i < _pop.size(); ++i) + for (unsigned i = 1; i < _pop.size(); ++i) { - cumulative[i] = _pop[i].fitness() + cumulative[i-1]; + cumulative[i] = _pop[i].fitness() + cumulative[i-1]; } } - - /** do the selection, + + /** do the selection, */ - const EOT& operator()(const eoPop& _pop) + const EOT& operator()(const eoPop& _pop) { if (cumulative.size() == 0) setup(_pop); - - double fortune = rng.uniform() * cumulative.back(); + + double fortune = rng.uniform() * cumulative.back(); typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune); return _pop[result - cumulative.begin()]; } diff --git a/eo/src/eoRandomRealWeightUp.h b/eo/src/eoRandomRealWeightUp.h index b929504c..81521b51 100644 --- a/eo/src/eoRandomRealWeightUp.h +++ b/eo/src/eoRandomRealWeightUp.h @@ -31,7 +31,7 @@ //----------------------------------------------------------------------------- /** - * Update an inertia weight by assigning it an (uniform) random value. + * Update an inertia weight by assigning it an (uniform) random value. * The weight is a basic feature to evaluate the velocity of a particle in * swarm optimization. * diff --git a/eo/src/eoRandomSelect.h b/eo/src/eoRandomSelect.h index 6d99f17e..065f050f 100644 --- a/eo/src/eoRandomSelect.h +++ b/eo/src/eoRandomSelect.h @@ -35,7 +35,7 @@ #include #include -/** eoRandomSelect: a selection method that selects ONE individual randomly +/** eoRandomSelect: a selection method that selects ONE individual randomly * * @ingroup Selectors */ @@ -91,4 +91,3 @@ private: }; #endif - diff --git a/eo/src/eoRanking.h b/eo/src/eoRanking.h index ec812006..5e734291 100644 --- a/eo/src/eoRanking.h +++ b/eo/src/eoRanking.h @@ -55,10 +55,10 @@ public: { typename eoPop::const_iterator it; for (it=_pop.begin(); it<_pop.end(); it++) - { - if (_eo == &(*it)) - return it-_pop.begin(); - } + { + if (_eo == &(*it)) + return it-_pop.begin(); + } throw std::runtime_error("Not found in eoLinearRanking"); } @@ -74,33 +74,33 @@ public: unsigned int pSizeMinusOne = pSize-1; if (pSize <= 1) - throw std::runtime_error("Cannot do ranking with population of size <= 1"); + throw std::runtime_error("Cannot do ranking with population of size <= 1"); // value() refers to the std::vector of worthes (we're in an eoParamvalue) value().resize(pSize); double beta = (2-pressure)/pSize; - if (exponent == 1.0) // no need for exponetial then - { - double alpha = (2*pressure-2)/(pSize*pSizeMinusOne); - for (unsigned i=0; i 1/[P(P-1)/2] - } - } - else // exponent != 1 - { - double gamma = (2*pressure-2)/pSize; - for (unsigned i=0; i 1/[P(P-1)/2] + } + } + else // exponent != 1 + { + double gamma = (2*pressure-2)/pSize; + for (unsigned i=0; i -class eoRankingSelect: public eoRouletteWorthSelect +template +class eoRankingSelect: public eoRouletteWorthSelect { public: /** Ctor: * @param _p the selective pressure, should be in [1,2] (2 is the default) * @param _e exponent (1 == linear) */ - eoRankingSelect(double _p = 2.0, double _e=1.0): + eoRankingSelect(double _p = 2.0, double _e=1.0): eoRouletteWorthSelect(ranking), ranking(_p, _e) {} private : - eoRanking ranking; // derived from eoPerf2Worth + eoRanking ranking; // derived from eoPerf2Worth }; #endif diff --git a/eo/src/eoRealBoundModifier.h b/eo/src/eoRealBoundModifier.h index e9d21c4c..9a9e032b 100644 --- a/eo/src/eoRealBoundModifier.h +++ b/eo/src/eoRealBoundModifier.h @@ -56,8 +56,8 @@ public: void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) { - (void)_bnds; - (void)_i; + (void)_bnds; + (void)_i; } }; @@ -70,26 +70,26 @@ public: * - t, the current iteration, is given with an eoValueParam * - Nt is the stopping criteria <=> the total number of iterations * - alpha a coefficient - * + * */ class eoExpDecayingBoundModifier: public eoRealBoundModifier { public: - - /** - * Constructor - * @param _stopCriteria - The total number of iterations - * @param _alpha - * @param _genCounter - An eoValueParam that gives the current iteration - */ + + /** + * Constructor + * @param _stopCriteria - The total number of iterations + * @param _alpha + * @param _genCounter - An eoValueParam that gives the current iteration + */ eoExpDecayingBoundModifier (unsigned _stopCriteria, double _alpha, eoValueParam & _genCounter): - stopCriteria(_stopCriteria), - alpha(_alpha), - genCounter(_genCounter){} - - + stopCriteria(_stopCriteria), + alpha(_alpha), + genCounter(_genCounter){} + + void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) { double newMaxBound=(1-pow((double)genCounter.value()/stopCriteria,alpha))*_bnds.maximum(_i); diff --git a/eo/src/eoReduce.h b/eo/src/eoReduce.h index 7b51d586..7cca6199 100644 --- a/eo/src/eoReduce.h +++ b/eo/src/eoReduce.h @@ -4,7 +4,7 @@ // eoReduce.h // Base class for population-merging classes // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -39,7 +39,7 @@ /** * eoReduce: .reduce the new generation to the specified size At the moment, limited to truncation - with 2 different methods, - one that sorts the whole population, and one that repeatidely kills + one that sorts the whole population, and one that repeatidely kills the worst. Ideally, we should be able to choose at run-time!!! @ingroup Replacors @@ -47,7 +47,7 @@ template class eoReduce: public eoBF&, unsigned, void> {}; -/** truncation method using sort +/** truncation method using sort @ingroup Replacors */ template class eoTruncate : public eoReduce @@ -56,15 +56,15 @@ template class eoTruncate : public eoReduce { if (_newgen.size() == _newsize) return; - if (_newgen.size() < _newsize) - throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); - + if (_newgen.size() < _newsize) + throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); + _newgen.sort(); _newgen.resize(_newsize); } }; -/** random truncation +/** random truncation @ingroup Replacors * */ template class eoRandomReduce : public eoReduce @@ -73,16 +73,16 @@ template class eoRandomReduce : public eoReduce { if (_newgen.size() == _newsize) return; - if (_newgen.size() < _newsize) - throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n"); + if (_newgen.size() < _newsize) + throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n"); - // shuffle the population, then trucate - _newgen.shuffle(); - _newgen.resize(_newsize); + // shuffle the population, then trucate + _newgen.shuffle(); + _newgen.resize(_newsize); } }; -/** +/** EP truncation method (some global stochastic tournament + sort) Softer selective pressure than pure truncate @ingroup Replacors @@ -90,15 +90,15 @@ Softer selective pressure than pure truncate template class eoEPReduce : public eoReduce { public: -typedef typename EOT::Fitness Fitness; +typedef typename EOT::Fitness Fitness; eoEPReduce(unsigned _t_size ): t_size(_t_size) { if (t_size < 2) - { + { eo::log << eo::warnings << "Warning: EP tournament size should be >= 2. Adjusted" << std::endl; - t_size = 2; + t_size = 2; } } @@ -108,60 +108,60 @@ typedef typename EOT::Fitness Fitness; typedef std::pair::iterator> EPpair; struct Cmp { bool operator()(const EPpair a, const EPpair b) const - { + { if (b.first == a.first) - return (*b.second < *a.second); - return b.first < a.first; + return (*b.second < *a.second); + return b.first < a.first; } }; - - + + void operator()(eoPop& _newgen, unsigned _newsize) { unsigned int presentSize = _newgen.size(); - + if (presentSize == _newsize) return; - if (presentSize < _newsize) - throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); - std::vector scores(presentSize); - for (unsigned i=0; i competitor.fitness()) - scores[i].first += 1; - else if (fit == competitor.fitness()) - scores[i].first += 0.5; - } - } + if (presentSize < _newsize) + throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); + std::vector scores(presentSize); + for (unsigned i=0; i competitor.fitness()) + scores[i].first += 1; + else if (fit == competitor.fitness()) + scores[i].first += 0.5; + } + } - // now we have the scores - typename std::vector::iterator it = scores.begin() + _newsize; + // now we have the scores + typename std::vector::iterator it = scores.begin() + _newsize; std::nth_element(scores.begin(), it, scores.end(), Cmp()); - // sort(scores.begin(), scores.end(), Cmp()); - unsigned j; -// std::cout << "Les scores apres tri\n"; -// for (j=0; j tmPop; - for (j=0; j<_newsize; j++) - { - tmPop.push_back(*scores[j].second); - } - _newgen.swap(tmPop); - // erase does not work, but I'm sure there is a way in STL to mark - // and later delete all inside a std::vector ?????? - // this would avoid all copies here + // sort(scores.begin(), scores.end(), Cmp()); + unsigned j; +// std::cout << "Les scores apres tri\n"; +// for (j=0; j tmPop; + for (j=0; j<_newsize; j++) + { + tmPop.push_back(*scores[j].second); + } + _newgen.swap(tmPop); + // erase does not work, but I'm sure there is a way in STL to mark + // and later delete all inside a std::vector ?????? + // this would avoid all copies here -// it = scores.begin() + _newsize; -// while (it < scores.end()) -// _newgen.erase(it->second); +// it = scores.begin() + _newsize; +// while (it < scores.end()) +// _newgen.erase(it->second); } private: unsigned t_size; @@ -171,7 +171,7 @@ private: To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement) @ingroup Replacors */ -template +template class eoLinearTruncate : public eoReduce { void operator()(eoPop& _newgen, unsigned _newsize) @@ -183,8 +183,8 @@ class eoLinearTruncate : public eoReduce throw std::logic_error("eoLinearTruncate: Cannot truncate to a larger size!\n"); for (unsigned i=0; i::iterator it = _newgen.it_worse_element(); - _newgen.erase(it); + typename eoPop::iterator it = _newgen.it_worse_element(); + _newgen.erase(it); } } }; @@ -193,7 +193,7 @@ class eoLinearTruncate : public eoReduce To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) @ingroup Replacors */ -template +template class eoDetTournamentTruncate : public eoReduce { public: @@ -201,9 +201,9 @@ public: t_size(_t_size) { if (t_size < 2) - { + { eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncate adjusted to 2" << std::endl; - t_size = 2; + t_size = 2; } } @@ -212,8 +212,8 @@ public: unsigned oldSize = _newgen.size(); if (_newsize == 0) { - _newgen.resize(0); - return; + _newgen.resize(0); + return; } if (oldSize == _newsize) return; @@ -223,15 +223,15 @@ public: // Now OK to erase some losers for (unsigned i=0; i(_newgen, t_size); - //OLDCODE _newgen.erase(&eo); - - // Jeroen Eggermont stdc++v3 patch - // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T - // Because eo already contained a fuction using eoPop::iterator's we will use the following - - _newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) ); - + //OLDCODE EOT & eo = inverse_deterministic_tournament(_newgen, t_size); + //OLDCODE _newgen.erase(&eo); + + // Jeroen Eggermont stdc++v3 patch + // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T + // Because eo already contained a fuction using eoPop::iterator's we will use the following + + _newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) ); + } } private: @@ -242,7 +242,7 @@ private: To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) @ingroup Replacors */ -template +template class eoStochTournamentTruncate : public eoReduce { public: @@ -250,14 +250,14 @@ public: t_rate(_t_rate) { if (t_rate <= 0.5) - { + { eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 0.51" << std::endl; - t_rate = 0.51; + t_rate = 0.51; } if (t_rate > 1) { eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 1" << std::endl; - t_rate = 1; + t_rate = 1; } } @@ -266,8 +266,8 @@ public: unsigned oldSize = _newgen.size(); if (_newsize == 0) { - _newgen.resize(0); - return; + _newgen.resize(0); + return; } if (oldSize == _newsize) return; @@ -276,16 +276,16 @@ public: // Now OK to erase some losers for (unsigned i=0; i(_newgen, t_rate); - //OLDCODE _newgen.erase(&eo); - - // Jeroen Eggermont stdc++v3 patch - // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T - // Because eo already contained a fuction using eoPop::iterator's we will use the following - - _newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) ); - - + //OLDCODE EOT & eo = inverse_stochastic_tournament(_newgen, t_rate); + //OLDCODE _newgen.erase(&eo); + + // Jeroen Eggermont stdc++v3 patch + // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T + // Because eo already contained a fuction using eoPop::iterator's we will use the following + + _newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) ); + + } } diff --git a/eo/src/eoReduceMerge.h b/eo/src/eoReduceMerge.h index 2e653018..02933b40 100644 --- a/eo/src/eoReduceMerge.h +++ b/eo/src/eoReduceMerge.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoReduceMerge.h + eoReduceMerge.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -41,8 +41,8 @@ * @{ */ -/** -eoReduceMerge: Replacement strategies that start by reducing the parents, +/** +eoReduceMerge: Replacement strategies that start by reducing the parents, then merge with the offspring This is the way to do SSGA: the offspring gets inserted in the population @@ -63,10 +63,10 @@ class eoReduceMerge : public eoReplacement void operator()(eoPop& _parents, eoPop& _offspring) { - if (_parents.size() < _offspring.size()) - throw std::logic_error("eoReduceMerge: More offspring than parents!\n"); - reduce(_parents, _parents.size() - _offspring.size()); - merge(_offspring, _parents); + if (_parents.size() < _offspring.size()) + throw std::logic_error("eoReduceMerge: More offspring than parents!\n"); + reduce(_parents, _parents.size() - _offspring.size()); + merge(_offspring, _parents); } private : @@ -74,10 +74,10 @@ class eoReduceMerge : public eoReplacement eoMerge& merge; }; -/** +/** SSGA replace worst. Is an eoReduceMerge. */ -template +template class eoSSGAWorseReplacement : public eoReduceMerge { public : @@ -88,15 +88,15 @@ class eoSSGAWorseReplacement : public eoReduceMerge eoPlus plus; }; -/** +/** SSGA deterministic tournament replacement. Is an eoReduceMerge. */ -template +template class eoSSGADetTournamentReplacement : public eoReduceMerge { public : - eoSSGADetTournamentReplacement(unsigned _t_size) : - eoReduceMerge(truncate, plus), truncate(_t_size) {} + eoSSGADetTournamentReplacement(unsigned _t_size) : + eoReduceMerge(truncate, plus), truncate(_t_size) {} private : eoDetTournamentTruncate truncate; @@ -104,16 +104,16 @@ class eoSSGADetTournamentReplacement : public eoReduceMerge }; /** SSGA stochastic tournament replacement. Is an eoReduceMerge. -It much cleaner to insert directly the offspring in the parent population, -but it is NOT equivalent in case of more than 1 offspring as already -replaced could be removed , which is not possible in the eoReduceMerge +It much cleaner to insert directly the offspring in the parent population, +but it is NOT equivalent in case of more than 1 offspring as already +replaced could be removed , which is not possible in the eoReduceMerge So what the heck ! */ -template +template class eoSSGAStochTournamentReplacement : public eoReduceMerge { public : - eoSSGAStochTournamentReplacement(double _t_rate) : - eoReduceMerge(truncate, plus), truncate(_t_rate) {} + eoSSGAStochTournamentReplacement(double _t_rate) : + eoReduceMerge(truncate, plus), truncate(_t_rate) {} private : eoStochTournamentTruncate truncate; diff --git a/eo/src/eoReduceMergeReduce.h b/eo/src/eoReduceMergeReduce.h index 41629267..17721f73 100644 --- a/eo/src/eoReduceMergeReduce.h +++ b/eo/src/eoReduceMergeReduce.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoReduceMergeReduce.h + eoReduceMergeReduce.h (c) Maarten Keijzer, Marc Schoenauer, 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 @@ -49,13 +49,13 @@ template class eoReduceMergeReduce : public eoReplacement { public: - eoReduceMergeReduce(eoHowMany _howManyElite, - bool _strongElitism, - eoHowMany _howManyReducedParents, - eoReduce & _reduceParents, - eoHowMany _howManyReducedOffspring, - eoReduce & _reduceOffspring, - eoReduce & _reduceFinal) : + eoReduceMergeReduce(eoHowMany _howManyElite, + bool _strongElitism, + eoHowMany _howManyReducedParents, + eoReduce & _reduceParents, + eoHowMany _howManyReducedOffspring, + eoReduce & _reduceOffspring, + eoReduce & _reduceFinal) : howManyElite(_howManyElite), strongElitism(_strongElitism), howManyReducedParents(_howManyReducedParents), @@ -64,7 +64,7 @@ public: reduceOffspring(_reduceOffspring), reduceFinal(_reduceFinal) {} - + void operator()(eoPop & _parents, eoPop & _offspring) { eoPop temp; @@ -72,66 +72,66 @@ public: unsigned int offSize = _offspring.size(); unsigned int elite = howManyElite(finalPopSize); - if (elite) // some parents MUST be saved somewhere - { - temp.resize(elite); - _parents.nth_element(elite); - std::copy(_parents.begin(), _parents.begin()+elite, temp.begin()); - _parents.erase(_parents.begin(), _parents.begin()+elite); - } + if (elite) // some parents MUST be saved somewhere + { + temp.resize(elite); + _parents.nth_element(elite); + std::copy(_parents.begin(), _parents.begin()+elite, temp.begin()); + _parents.erase(_parents.begin(), _parents.begin()+elite); + } // the reduce steps. First the parents unsigned reducedParentSize = howManyReducedParents(_parents.size()); if (!reducedParentSize) - _parents.clear(); + _parents.clear(); else if (reducedParentSize != _parents.size()) - reduceParents(_parents, reducedParentSize); + reduceParents(_parents, reducedParentSize); // then the offspring unsigned reducedOffspringSize = howManyReducedOffspring(offSize); if (!reducedOffspringSize) - throw std::runtime_error("No offspring left after reduction!"); + throw std::runtime_error("No offspring left after reduction!"); if (reducedOffspringSize != offSize) // need reduction - reduceOffspring(_offspring, reducedOffspringSize); + reduceOffspring(_offspring, reducedOffspringSize); // now merge reduced populations _parents.resize(reducedParentSize + _offspring.size()); - std::copy(_offspring.begin(), _offspring.end(), - _parents.begin()+reducedParentSize); + std::copy(_offspring.begin(), _offspring.end(), + _parents.begin()+reducedParentSize); // reduce the resulting population // size depstd::ends on elitism if (elite && strongElitism) - { - if (_parents.size() != finalPopSize-elite) - reduceFinal(_parents, finalPopSize-elite); - // and put back the elite - unsigned oldPSize = _parents.size(); - _parents.resize(_parents.size()+elite); - std::copy(temp.begin(), temp.end(), _parents.begin()+oldPSize); - } - else - { // only reduce final pop to right size - if (_parents.size() != finalPopSize) - reduceFinal(_parents, finalPopSize); - if (elite) // then treat weak elitism - { - unsigned toSave = 0; - _parents.sort(); - EOT & eoLimit = _parents[elite-1]; - unsigned index=0; - while ( (temp[index++] > eoLimit) && (index < temp.size()) ) - toSave++; - if (toSave) - for (unsigned i=0; i eoLimit) && (index < temp.size()) ) + toSave++; + if (toSave) + for (unsigned i=0; i weak estd::listism + eoHowMany howManyElite; // if 0, no elitism at all + bool strongElitism; // if false -> weak estd::listism eoHowMany howManyReducedParents; // if 0, no parent in final replacement eoHowMany howManyReducedOffspring; // if 0, std::runtime_error // the reducers diff --git a/eo/src/eoReduceSplit.h b/eo/src/eoReduceSplit.h index db119032..ce22d027 100644 --- a/eo/src/eoReduceSplit.h +++ b/eo/src/eoReduceSplit.h @@ -4,7 +4,7 @@ // eoReduceSplit.h // Base class for population-reducing classes - retaining the poor losers // (c) GeNeura Team, 1998, Marc Schoenauer, 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 @@ -47,16 +47,16 @@ template class eoReduceSplit: public eoBF&, eoPop &, {}; /** deterministic truncation method using sort */ -template +template class eoTruncateSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the jonb */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -67,13 +67,13 @@ public: unsigned newsize = popSize - eliminated; if (newsize < 0) throw std::logic_error("eoTruncateSplit: Cannot truncate to a larger size!\n"); - + _newgen.nth_element(newsize); // save poor losers if necessary if (returnEliminated) for (unsigned i=0; i +template class eoLinearTruncateSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoLinearTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the job */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -111,10 +111,10 @@ public: _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i::iterator it = _newgen.it_worse_element(); - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + typename eoPop::iterator it = _newgen.it_worse_element(); + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } } @@ -124,16 +124,16 @@ private: }; /** random truncation - batch version */ -template +template class eoRandomSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoRandomSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the job */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -150,7 +150,7 @@ public: // save poor losers if necessary if (returnEliminated) for (unsigned i=0; i +template class eoLinearRandomSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoLinearRandomSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the job */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -187,11 +187,11 @@ public: _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i::iterator it = _newgen.begin()+loser; - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + unsigned loser=random(_newgen.size()); + typename eoPop::iterator it = _newgen.begin()+loser; + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } return ; } @@ -205,22 +205,22 @@ private: /** a ReduceSplit class based on a repeated deterministic (reverse!) tournament To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) */ -template +template class eoDetTournamentTruncateSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ - eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany, - bool _returnEliminated = false): - t_size(_t_size), howMany(_howMany), - returnEliminated(_returnEliminated) + eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany, + bool _returnEliminated = false): + t_size(_t_size), howMany(_howMany), + returnEliminated(_returnEliminated) { if (t_size < 2) - { + { eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; - t_size = 2; + t_size = 2; } } @@ -240,10 +240,10 @@ public: _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size); - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + typename eoPop::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size); + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } } @@ -256,27 +256,27 @@ private: /** a ReduceSplit class based on a repeated deterministic (reverse!) tournament To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) */ -template +template class eoStochTournamentTruncateSplit : public eoReduce { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ - eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany, - bool _returnEliminated = false): - t_rate(_t_rate), howMany(_howMany), - returnEliminated(_returnEliminated) + eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany, + bool _returnEliminated = false): + t_rate(_t_rate), howMany(_howMany), + returnEliminated(_returnEliminated) { if (t_rate <= 0.5) - { + { eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51" << std::endl; - t_rate = 0.51; + t_rate = 0.51; } if (t_rate > 1) { eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 1" << std::endl; - t_rate = 1; + t_rate = 1; } } @@ -285,7 +285,7 @@ public: //BUG??? void operator()(eoPop& _newgen, unsigned _newsize) { /* old version - if (!_eliminated.size()) // nothing to do + if (!_eliminated.size()) // nothing to do return; unsigned oldSize = _newgen.size(); unsigned newSize = oldSize - _eliminated.size(); @@ -308,10 +308,10 @@ end of old version */ _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i<_eliminated.size(); i++) { - typename eoPop::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate); - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + typename eoPop::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate); + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } } diff --git a/eo/src/eoReplacement.h b/eo/src/eoReplacement.h index 2c2d8984..033d441c 100644 --- a/eo/src/eoReplacement.h +++ b/eo/src/eoReplacement.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoReplacement.h + eoReplacement.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,9 +36,9 @@ #include //----------------------------------------------------------------------------- -/** +/** --- -The eoMergeReduce, combination of eoMerge and eoReduce, can be found +The eoMergeReduce, combination of eoMerge and eoReduce, can be found in file eoMergeReduce.h The eoReduceMergeReduce that reduces the parents and the offspring, @@ -47,15 +47,15 @@ population, can be found in eoReduceMergeReduce.h LOG --- -Removed the const before first argument: though it makes too many classes -with the same interface, it allows to minimize the number of actual copies +Removed the const before first argument: though it makes too many classes +with the same interface, it allows to minimize the number of actual copies by choosing the right destination I also removed the enforced "swap" in the eoEasyAlgo and hence the generational -replacement gets a class of its own that only does the swap (instead of the +replacement gets a class of its own that only does the swap (instead of the eoNoReplacement that did nothing, relying on the algo to swap popualtions). MS 12/12/2000 - @see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge + @see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge @class eoReplacement, base (pure abstract) class @class eoGenerationalReplacement, as it says ... @@ -67,7 +67,7 @@ MS 12/12/2000 NOTE: two eoPop as arguments the resulting population should be in the first argument (replace -parents by offspring)! The second argument can contain any rubbish +parents by offspring)! The second argument can contain any rubbish @ingroup Replacors */ @@ -91,10 +91,10 @@ class eoGenerationalReplacement : public eoReplacement } }; -/** -eoWeakElitistReplacement: a wrapper for other replacement procedures. -Copies in the new pop the best individual from the old pop, -AFTER normal replacement, if the best of the new pop is worse than the best +/** +eoWeakElitistReplacement: a wrapper for other replacement procedures. +Copies in the new pop the best individual from the old pop, +AFTER normal replacement, if the best of the new pop is worse than the best of the old pop. Removes the worse individual from the new pop. This could be changed by adding a selector there... @@ -114,11 +114,11 @@ public : void operator()(eoPop& _pop, eoPop& _offspring) { const EOT oldChamp = _pop.best_element(); - replace(_pop, _offspring); // "normal" replacement, parents are the new + replace(_pop, _offspring); // "normal" replacement, parents are the new if (_pop.best_element() < oldChamp) // need to do something { - typename eoPop::iterator itPoorGuy = _pop.it_worse_element(); - (*itPoorGuy) = oldChamp; + typename eoPop::iterator itPoorGuy = _pop.it_worse_element(); + (*itPoorGuy) = oldChamp; } } private: diff --git a/eo/src/eoRingTopology.h b/eo/src/eoRingTopology.h index 74705ac1..6bad13cd 100644 --- a/eo/src/eoRingTopology.h +++ b/eo/src/eoRingTopology.h @@ -3,10 +3,10 @@ //----------------------------------------------------------------------------- // eoRingTopology.h // (c) INRIA Futurs DOLPHIN 2007 -/* +/* Clive Canape - Thomas Legrand - + Thomas Legrand + 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 @@ -48,7 +48,7 @@ template < class POT > class eoRingTopology:public eoTopology public: /** - * The only Ctor. + * The only Ctor. * @param _neighborhoodSize - The size of each neighborhood. */ eoRingTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} @@ -68,16 +68,16 @@ public: int k = neighborhoodSize/2; for (unsigned i=0;i < _pop.size();i++) { - eoSocialNeighborhood currentNghd; - currentNghd.best(_pop[i]); - for (unsigned j=0; j < neighborhoodSize; j++) - { - currentNghd.put((_pop.size()+i-k+j)%_pop.size()); - if(_pop[(_pop.size()+i-k+j)%_pop.size()].fitness() > currentNghd.best().fitness()) + eoSocialNeighborhood currentNghd; + currentNghd.best(_pop[i]); + for (unsigned j=0; j < neighborhoodSize; j++) + { + currentNghd.put((_pop.size()+i-k+j)%_pop.size()); + if(_pop[(_pop.size()+i-k+j)%_pop.size()].fitness() > currentNghd.best().fitness()) currentNghd.best(_pop[(_pop.size()+i-k+j)%_pop.size()]); } - neighborhoods.push_back(currentNghd); - } + neighborhoods.push_back(currentNghd); + } isSetup=true; } else @@ -90,7 +90,7 @@ public: */ } } - + /** * Retrieves the neighboorhood of a particle. * @return _indice - The particle indice (in the population) @@ -109,20 +109,20 @@ public: */ void updateNeighborhood(POT & _po,unsigned _indice) { - //this->printOn();exit(0); + //this->printOn();exit(0); // update the best fitness of the particle if (_po.fitness() > _po.best()) { _po.best(_po.fitness()); for(unsigned i=0;i<_po.size();i++) - _po.bestPositions[i]=_po[i]; + _po.bestPositions[i]=_po[i]; } // update the global best if the given particle is "better" for (unsigned i=-neighborhoodSize+1; i < neighborhoodSize; i++) - { - unsigned indi = (_po.size()+_indice+i)%_po.size(); - if (_po.fitness() > neighborhoods[indi].best().fitness()) - neighborhoods[indi].best(_po); + { + unsigned indi = (_po.size()+_indice+i)%_po.size(); + if (_po.fitness() > neighborhoods[indi].best().fitness()) + neighborhoods[indi].best(_po); } } @@ -132,9 +132,9 @@ public: * @param _indice - The indice of a particle in the population * @return POT & - The best particle in the neighborhood of the particle whose indice is _indice */ - POT & best (unsigned _indice) + POT & best (unsigned _indice) { - unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); + unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); return (neighborhoods[theGoodNhbd].best()); } @@ -155,35 +155,35 @@ public: std::cout << "}" << std::endl; } } - + /* - * Return the global best of the topology - */ - virtual POT & globalBest() + * Return the global best of the topology + */ + virtual POT & globalBest() { - POT gBest,tmp; - unsigned indGlobalBest=0; - if(neighborhoods.size()==1) - return neighborhoods[0].best(); - - gBest=neighborhoods[0].best(); - for(unsigned i=1;i > neighborhoods; - unsigned neighborhoodSize; + unsigned neighborhoodSize; bool isSetup; }; /** @example t-eoRingTopology.cpp diff --git a/eo/src/eoSGA.h b/eo/src/eoSGA.h index d17d743d..b31dff04 100644 --- a/eo/src/eoSGA.h +++ b/eo/src/eoSGA.h @@ -58,7 +58,7 @@ public : eoQuadOp& _cross, float _crate, eoMonOp& _mutate, float _mrate, eoEvalFunc& _eval, - eoContinue& _cont) + eoContinue& _cont) : cont(_cont), mutate(_mutate), mutationRate(_mrate), @@ -73,34 +73,34 @@ public : do { - select(_pop, offspring); + select(_pop, offspring); - unsigned i; + unsigned i; - for (i=0; i<_pop.size()/2; i++) - { - if ( rng.flip(crossoverRate) ) - { - // this crossover generates 2 offspring from two parents - if (cross(offspring[2*i], offspring[2*i+1])) + for (i=0; i<_pop.size()/2; i++) + { + if ( rng.flip(crossoverRate) ) + { + // this crossover generates 2 offspring from two parents + if (cross(offspring[2*i], offspring[2*i+1])) { offspring[2*i].invalidate(); offspring[2*i+1].invalidate(); } } - } + } - for (i=0; i < offspring.size(); i++) - { - if (rng.flip(mutationRate) ) - { - if (mutate(offspring[i])) + for (i=0; i < offspring.size(); i++) + { + if (rng.flip(mutationRate) ) + { + if (mutate(offspring[i])) offspring[i].invalidate(); - } - } + } + } - _pop.swap(offspring); - apply(eval, _pop); + _pop.swap(offspring); + apply(eval, _pop); } while (cont(_pop)); } diff --git a/eo/src/eoSGAGenOp.h b/eo/src/eoSGAGenOp.h index 922a46ca..f08b2104 100644 --- a/eo/src/eoSGAGenOp.h +++ b/eo/src/eoSGAGenOp.h @@ -33,40 +33,40 @@ // class eoSGAGenOp /////////////////////////////////////////////////////////////////////////////// -/** - * eoSGAGenOp (for Simple GA) mimicks the usual crossover with proba pCross + +/** + * eoSGAGenOp (for Simple GA) mimicks the usual crossover with proba pCross + * mutation with proba pMut inside an eoGeneralOp - * It does it exactly as class eoSGATransform, i.e. only accepts + * It does it exactly as class eoSGATransform, i.e. only accepts * quadratic crossover and unary mutation * It was introduced for didactic reasons, but seems to be popular :-) * * @ingroup Combination */ - template + template class eoSGAGenOp : public eoGenOp { public: - + /** Ctor from crossover (with proba) and mutation (with proba) * Builds the sequential op that first applies a proportional choice * between the crossover and nothing (cloning), then the mutation */ - eoSGAGenOp(eoQuadOp& _cross, double _pCross, - eoMonOp& _mut, double _pMut) + eoSGAGenOp(eoQuadOp& _cross, double _pCross, + eoMonOp& _mut, double _pMut) : cross(_cross), pCross(_pCross), - mut(_mut), - pMut(_pMut) + mut(_mut), + pMut(_pMut) { // the crossover - with probability pCross propOp.add(cross, pCross); // crossover, with proba pcross propOp.add(quadClone, 1-pCross); // nothing, with proba 1-pcross - + // now the sequential - op.add(propOp, 1.0); // always do combined crossover + op.add(propOp, 1.0); // always do combined crossover op.add(mut, pMut); // then mutation, with proba pmut } - + /** do the job: delegate to op */ virtual void apply(eoPopulator& _pop) { diff --git a/eo/src/eoSGATransform.h b/eo/src/eoSGATransform.h index 57d5ea81..55b5e5ed 100644 --- a/eo/src/eoSGATransform.h +++ b/eo/src/eoSGATransform.h @@ -38,7 +38,7 @@ #include /** eoSGATransform: transforms a population using genetic operators. - * It does it exactly as class eoSGA, i.e. only accepts + * It does it exactly as class eoSGA, i.e. only accepts * quadratic crossover and unary mutation * It is here mainly for tutorial reasons * @@ -47,13 +47,13 @@ template class eoSGATransform : public eoTransform { public: - + /// Default constructor. - eoSGATransform(eoQuadOp& _cross, double _cProba, - eoMonOp& _mutate, double _mProba) + eoSGATransform(eoQuadOp& _cross, double _cProba, + eoMonOp& _mutate, double _mProba) : cross(_cross), crossoverProba(_cProba), - mutate(_mutate), + mutate(_mutate), mutationProba(_mProba) {} @@ -61,29 +61,29 @@ template class eoSGATransform : public eoTransform * Transforms a population. * @param _pop The population to be transformed. */ - void operator()(eoPop& _pop) + void operator()(eoPop& _pop) { unsigned i; - - for (i=0; i<_pop.size()/2; i++) + + for (i=0; i<_pop.size()/2; i++) { - if ( rng.flip(crossoverProba) ) - { - // this crossover generates 2 offspring from two parents - cross(_pop[2*i], _pop[2*i+1]); - } + if ( rng.flip(crossoverProba) ) + { + // this crossover generates 2 offspring from two parents + cross(_pop[2*i], _pop[2*i+1]); + } } - for (i=0; i < _pop.size(); i++) + for (i=0; i < _pop.size(); i++) { - if (rng.flip(mutationProba) ) - { - mutate(_pop[i]); - } - + if (rng.flip(mutationProba) ) + { + mutate(_pop[i]); + } + } }; - + private: eoInvalidateQuadOp cross; double crossoverProba; @@ -93,7 +93,7 @@ template class eoSGATransform : public eoTransform /** eoDynSGATransform: transforms a population using genetic operators. * It is the Dynamic version of the above eoSGATransform - * i.e. the operators probabilities can be passed as an eoValueParam, + * i.e. the operators probabilities can be passed as an eoValueParam, * and hence can be modified from outside * It is here mainly for tutorial reasons * @@ -102,23 +102,23 @@ template class eoSGATransform : public eoTransform template class eoDynSGATransform : public eoTransform { public: - + /// Default constructor - receives values - eoDynSGATransform(eoQuadOp& _cross, double _cProba, - eoMonOp& _mutate, double _mProba) + eoDynSGATransform(eoQuadOp& _cross, double _cProba, + eoMonOp& _mutate, double _mProba) : cross(_cross), crossoverProbaHolder(_cProba), crossoverProba(crossoverProbaHolder), - mutate(_mutate), + mutate(_mutate), mutationProbaHolder(_mProba), mutationProba(mutationProbaHolder) {} /// This constructor receives pointers // these will usually be some eoValueParam.value() // hence the ...Holder data will bever be used in this case - eoDynSGATransform(eoQuadOp& _cross, double* _cProbaRef, - eoMonOp& _mutate, double* _mProbaRef) + eoDynSGATransform(eoQuadOp& _cross, double* _cProbaRef, + eoMonOp& _mutate, double* _mProbaRef) : cross(_cross), crossoverProbaHolder(0), crossoverProba(*_cProbaRef), - mutate(_mutate), + mutate(_mutate), mutationProbaHolder(0), mutationProba(*_mProbaRef) {} @@ -126,34 +126,34 @@ template class eoDynSGATransform : public eoTransform * Transforms a population. * @param _pop The population to be transformed. */ - void operator()(eoPop& _pop) + void operator()(eoPop& _pop) { unsigned i; - - for (i=0; i<_pop.size()/2; i++) + + for (i=0; i<_pop.size()/2; i++) { - if ( rng.flip(crossoverProba) ) - { - // this crossover generates 2 offspring from two parents - cross(_pop[2*i], _pop[2*i+1]); - } + if ( rng.flip(crossoverProba) ) + { + // this crossover generates 2 offspring from two parents + cross(_pop[2*i], _pop[2*i+1]); + } } - for (i=0; i < _pop.size(); i++) + for (i=0; i < _pop.size(); i++) { - if (rng.flip(mutationProba) ) - { - mutate(_pop[i]); - } - + if (rng.flip(mutationProba) ) + { + mutate(_pop[i]); + } + } }; // accessors - mainly for EASEA - double & PCrossHandle() { return crossoverProba;} + double & PCrossHandle() { return crossoverProba;} double & PMutHandle() { return mutationProba;} private: - // difference with eoSGATransform: the operator probabilities + // difference with eoSGATransform: the operator probabilities // they can be passed by reference or by value. // hence we need here to use a reference, and to eventually store a value eoInvalidateQuadOp cross; diff --git a/eo/src/eoSIGContinue.cpp b/eo/src/eoSIGContinue.cpp index 4bc4ca24..2f126ea9 100644 --- a/eo/src/eoSIGContinue.cpp +++ b/eo/src/eoSIGContinue.cpp @@ -1,34 +1,34 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoSIGContinue.cpp -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either 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 - Johann Dréo - Caner Candan + Johann Dréo + Caner Candan */ //----------------------------------------------------------------------------- #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include #include diff --git a/eo/src/eoSIGContinue.h b/eo/src/eoSIGContinue.h index 36546fb0..d7db55d3 100644 --- a/eo/src/eoSIGContinue.h +++ b/eo/src/eoSIGContinue.h @@ -1,28 +1,28 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoSIGContinue.h -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either 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 - Johann Dréo - Caner Candan + Johann Dréo + Caner Candan */ //----------------------------------------------------------------------------- // the same thing can probably be done in MS environement, but I hoave no way @@ -75,8 +75,8 @@ public: { if (call_func) { - _fct(_sig); - call_func = false; + _fct(_sig); + call_func = false; } return true; diff --git a/eo/src/eoSTLFunctor.h b/eo/src/eoSTLFunctor.h index c21f161c..04f96f9c 100644 --- a/eo/src/eoSTLFunctor.h +++ b/eo/src/eoSTLFunctor.h @@ -29,7 +29,7 @@ #include "eoFunctor.h" -/** @addtogroup Utilities +/** @addtogroup Utilities * @{ */ @@ -121,4 +121,3 @@ class eoSTLBF : public std::binary_function /** @} */ #endif - diff --git a/eo/src/eoScalarFitness.h b/eo/src/eoScalarFitness.h index aa8d57a1..f3a3a4bb 100644 --- a/eo/src/eoScalarFitness.h +++ b/eo/src/eoScalarFitness.h @@ -63,8 +63,8 @@ class eoScalarFitness bool operator<(const eoScalarFitness& other) const { return Compare()(value, other.value); } - /// Comparison, using less by default - // needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006 + /// Comparison, using less by default + // needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006 bool operator<(const ScalarType& other) const { return Compare()(value, other); } diff --git a/eo/src/eoScalarFitnessAssembled.cpp b/eo/src/eoScalarFitnessAssembled.cpp index a30289ab..58f7615f 100644 --- a/eo/src/eoScalarFitnessAssembled.cpp +++ b/eo/src/eoScalarFitnessAssembled.cpp @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoScalarFitnessAssembled.cpp // Marc Wintermantel & Oliver Koenig @@ -11,16 +11,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@inria.fr mak@dhi.dk @@ -29,13 +29,10 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include "eoScalarFitnessAssembled.h" // need to allocate the static variables of class eoScalarFitnessAssembledTraits std::vector eoScalarFitnessAssembledTraits::TermDescriptions; - - - diff --git a/eo/src/eoScalarFitnessAssembled.h b/eo/src/eoScalarFitnessAssembled.h index f84a805d..95168ec6 100644 --- a/eo/src/eoScalarFitnessAssembled.h +++ b/eo/src/eoScalarFitnessAssembled.h @@ -110,8 +110,8 @@ public: {} eoScalarFitnessAssembled( size_type _n, - const ScalarType& _val, - const std::string& _descr="Unnamed variable" ) + const ScalarType& _val, + const std::string& _descr="Unnamed variable" ) : baseVector(_n, _val), feasible(true), failed(false), msg("") { @@ -225,10 +225,10 @@ public: //! Comparison with ScalarTypes. Explicit definition needed to compile with VS 8.0 bool operator<(ScalarType x) const{ - eoScalarFitnessAssembled ScalarFitness(x); - return this->operator<(ScalarFitness); + eoScalarFitnessAssembled ScalarFitness(x); + return this->operator<(ScalarFitness); } - + // implementation of the other operators bool operator>( const eoScalarFitnessAssembled& y ) const { return y < *this; } @@ -239,7 +239,7 @@ public: bool operator>=(const eoScalarFitnessAssembled& y ) const { return !(*this < y); } }; -/** +/** * @example t-eoFitnessAssembledEA.cpp */ @@ -282,4 +282,3 @@ std::istream& operator>>(std::istream& is, eoScalarFitnessAssembled -/** +/** Timed continuator: continues until a number of seconds is used @ingroup Continuators @@ -44,29 +44,29 @@ public: virtual bool operator() ( const eoPop& _vEO ) { time_t now = time(0); time_t diff = now - start; - + if (diff >= seconds) return false; // stop return true; } - + virtual std::string className(void) const { return "eoSecondsElapsedContinue"; } /** REad from a stream * @param __is the ostream to read from */ void readFrom (std :: istream & __is) { - - __is >> start >> seconds; + + __is >> start >> seconds; } - + /** Print on a stream * @param __os the ostream to print on */ void printOn (std :: ostream & __os) const { - - __os << start << ' ' << seconds << std :: endl; + + __os << start << ' ' << seconds << std :: endl; } }; @@ -74,4 +74,3 @@ public: */ #endif - diff --git a/eo/src/eoSelect.h b/eo/src/eoSelect.h index ea5c8592..aae33843 100644 --- a/eo/src/eoSelect.h +++ b/eo/src/eoSelect.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelect.h + eoSelect.h (c) Maarten Keijzer, 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 @@ -30,7 +30,7 @@ #include //----------------------------------------------------------------------------- -/** +/** eoSelect selects a number of individuals from the first argument and puts it in the second. To emphasize that it should not try to enlarge the population, the second argument is an eoPopRange, a simple struct diff --git a/eo/src/eoSelectFactory.h b/eo/src/eoSelectFactory.h index 59d2306a..9dc19dab 100644 --- a/eo/src/eoSelectFactory.h +++ b/eo/src/eoSelectFactory.h @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- // EOFactory.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -41,52 +41,52 @@ eoSelect objects */ template< class EOT> class eoSelectFactory: public eoFactory > { - + public: - - /// @name ctors and dtors - //{@ - /// constructor - eoSelectFactory( ) {} - - /// destructor - virtual ~eoSelectFactory() {} - //@} - /** Another factory methods: creates an object from an std::istream, reading from - it whatever is needed to create the object. Usually, the format for the std::istream will be\\ - objectType parameter1 parameter2 ... parametern\\ - */ - virtual eoSelect* make(std::istream& _is) { - eoSelect * selectPtr; - std::string objectTypeStr; - _is >> objectTypeStr; - // All selectors have a rate, the proportion of the original population - float rate; - _is >> rate; - if ( objectTypeStr == "eoTournament") { - // another parameter is necessary - unsigned tSize; - _is >> tSize; - selectPtr = new eoTournament( rate, tSize ); - } else { - if ( objectTypeStr == "eoRandomSelect" ) { - selectPtr = new eoRandomSelect( rate ); - } else { - throw std::runtime_error( "Incorrect selector type" ); - } - } - return selectPtr; - } + /// @name ctors and dtors + //{@ + /// constructor + eoSelectFactory( ) {} - ///@name eoObject methods - //@{ - void printOn( std::ostream& _os ) const {}; - void readFrom( std::istream& _is ){}; + /// destructor + virtual ~eoSelectFactory() {} + //@} + + /** Another factory methods: creates an object from an std::istream, reading from + it whatever is needed to create the object. Usually, the format for the std::istream will be\\ + objectType parameter1 parameter2 ... parametern\\ + */ + virtual eoSelect* make(std::istream& _is) { + eoSelect * selectPtr; + std::string objectTypeStr; + _is >> objectTypeStr; + // All selectors have a rate, the proportion of the original population + float rate; + _is >> rate; + if ( objectTypeStr == "eoTournament") { + // another parameter is necessary + unsigned tSize; + _is >> tSize; + selectPtr = new eoTournament( rate, tSize ); + } else { + if ( objectTypeStr == "eoRandomSelect" ) { + selectPtr = new eoRandomSelect( rate ); + } else { + throw std::runtime_error( "Incorrect selector type" ); + } + } + return selectPtr; + } + + ///@name eoObject methods + //@{ + void printOn( std::ostream& _os ) const {}; + void readFrom( std::istream& _is ){}; + + /** className is inherited */ + //@} - /** className is inherited */ - //@} - }; diff --git a/eo/src/eoSelectFromWorth.h b/eo/src/eoSelectFromWorth.h index e338ea31..a2fd5ed2 100644 --- a/eo/src/eoSelectFromWorth.h +++ b/eo/src/eoSelectFromWorth.h @@ -194,7 +194,7 @@ public: eoSelectFromWorth::setup(_pop); total = 0.0; for (worthIterator it = perf2Worth.value().begin(); - it& _pop) { // cout << "On affiche les worths\n"; // for (unsigned i=0; - // i //----------------------------------------------------------------------------- -/** eoSelectMany selects many individuals using eoSelectOne as it's +/** eoSelectMany selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectMany needs an eoSelectOne in its ctor It will use an eoHowMnay to determine the number of guys to select, @@ -48,12 +48,12 @@ class eoSelectMany : public eoSelect { public: /// init - eoSelectMany(eoSelectOne& _select, - double _rate, bool _interpret_as_rate = true) + eoSelectMany(eoSelectOne& _select, + double _rate, bool _interpret_as_rate = true) : select(_select), howMany(_rate, _interpret_as_rate) {} // Ctor with eoHowMany - eoSelectMany(eoSelectOne& _select, eoHowMany _howMany) + eoSelectMany(eoSelectOne& _select, eoHowMany _howMany) : select(_select), howMany(_howMany) {} /** @@ -65,15 +65,15 @@ class eoSelectMany : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { unsigned target = howMany(_source.size()); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; eoHowMany howMany; diff --git a/eo/src/eoSelectNumber.h b/eo/src/eoSelectNumber.h index 52cee662..f6f094ef 100644 --- a/eo/src/eoSelectNumber.h +++ b/eo/src/eoSelectNumber.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectNumber.h + eoSelectNumber.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -32,7 +32,7 @@ #include //----------------------------------------------------------------------------- -/** eoSelectNumber selects many individuals using eoSelectOne as it's +/** eoSelectNumber selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectNumber needs an eoSelectOne in its ctor It will select a fixed number of individuals and pushes them to @@ -45,7 +45,7 @@ class eoSelectNumber : public eoSelect { public: /// init - eoSelectNumber(eoSelectOne& _select, unsigned _nb_to_select = 1) + eoSelectNumber(eoSelectOne& _select, unsigned _nb_to_select = 1) : select(_select), nb_to_select(_nb_to_select) {} /** @@ -57,15 +57,15 @@ class eoSelectNumber : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { size_t target = static_cast(nb_to_select); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; unsigned nb_to_select; diff --git a/eo/src/eoSelectOne.h b/eo/src/eoSelectOne.h index 3b27a4e3..5afdd140 100644 --- a/eo/src/eoSelectOne.h +++ b/eo/src/eoSelectOne.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectOne.h + eoSelectOne.h (c) Maarten Keijzer, 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 @@ -50,7 +50,7 @@ class eoSelectOne : public eoUF&, const EOT&> /// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this) virtual void setup(const eoPop& _pop) { - (void)_pop; + (void)_pop; } }; /** @example t-selectOne.cpp diff --git a/eo/src/eoSelectPerc.h b/eo/src/eoSelectPerc.h index d4aacfda..131a3d59 100644 --- a/eo/src/eoSelectPerc.h +++ b/eo/src/eoSelectPerc.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectPerc.h + eoSelectPerc.h (c) Maarten Keijzer, 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 @@ -32,7 +32,7 @@ #include //----------------------------------------------------------------------------- -/** eoSelectPerc selects many individuals using eoSelectOne as it's +/** eoSelectPerc selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectPerc needs an eoSelectOne in its ctor It will select floor(rate*pop.size()) individuals and pushes them to @@ -45,11 +45,11 @@ class eoSelectPerc : public eoSelect { public: /// init - eoSelectPerc(eoSelectOne& _select, float _rate = 1.0) + eoSelectPerc(eoSelectOne& _select, float _rate = 1.0) : select(_select), rate(_rate) {} /** - The implementation selects a percentage + The implementation selects a percentage @param _source the source population @param _dest the resulting population (size of this population is the number of times eoSelectOne is called. It empties the destination and adds the selection into it) @@ -57,15 +57,15 @@ class eoSelectPerc : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { size_t target = static_cast(floor(rate * _source.size())); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; float rate; diff --git a/eo/src/eoSequentialSelect.h b/eo/src/eoSequentialSelect.h index a30c9248..1a1f02e4 100644 --- a/eo/src/eoSequentialSelect.h +++ b/eo/src/eoSequentialSelect.h @@ -58,13 +58,13 @@ template class eoSequentialSelect: public eoSelectOne not very elegant, maybe ... */ eoSequentialSelect(bool _ordered = true) - : ordered(_ordered), current(std::numeric_limits::max()) {} + : ordered(_ordered), current(std::numeric_limits::max()) {} void setup(const eoPop& _pop) { eoPters.resize(_pop.size()); if (ordered) // probably we could have a marker to avoid re-sorting - _pop.sort(eoPters); + _pop.sort(eoPters); else _pop.shuffle(eoPters); current=0; @@ -118,10 +118,10 @@ template class eoEliteSequentialSelect: public eoSelectOne throw std::runtime_error("Trying eoEliteSequentialSelect with only one individual!"); for (unsigned i=1; i<_pop.size(); i++) if (*eoPters[i]>*best) - { - ibest = i; - best = eoPters[ibest]; - } + { + ibest = i; + best = eoPters[ibest]; + } // and put it upfront const EOT *ptmp = eoPters[0]; eoPters[0]=best; diff --git a/eo/src/eoSharing.h b/eo/src/eoSharing.h index b2a58653..170a03b9 100644 --- a/eo/src/eoSharing.h +++ b/eo/src/eoSharing.h @@ -33,7 +33,7 @@ * Goldberg and Richardson's basic sharing */ -/** A helper class for Sharing - to hold distances +/** A helper class for Sharing - to hold distances * * @ingroup Selectors * */ @@ -60,16 +60,16 @@ class dMatrix : public std::vector { unsigned index=0; for (unsigned i=0; ioperator[](index++) << " " ; - _os << std::endl; - } + { + for (unsigned j=0; joperator[](index++) << " " ; + _os << std::endl; + } _os << std::endl; } private: - unsigned rSize; // row size (== number of columns!) + unsigned rSize; // row size (== number of columns!) }; @@ -89,8 +89,8 @@ public: /* Ctor requires a distance - cannot have a default distance! */ eoSharing(double _nicheSize, eoDistance & _dist) : eoPerf2Worth("Sharing"), - nicheSize(_nicheSize), - dist(_dist) + nicheSize(_nicheSize), + dist(_dist) {} /** Computes shared fitnesses @@ -98,33 +98,33 @@ public: void operator()(const eoPop& _pop) { unsigned i, j, - pSize=_pop.size(); + pSize=_pop.size(); if (pSize <= 1) - throw std::runtime_error("Apptempt to do sharing with population of size 1"); + throw std::runtime_error("Apptempt to do sharing with population of size 1"); value().resize(pSize); - std::vector sim(pSize); // to hold the similarities + std::vector sim(pSize); // to hold the similarities dMatrix distMatrix(pSize); // to hold the distances // compute the similarities (wrong name for distMatrix, I know) distMatrix(0,0)=1; for (i=1; inicheSize ? 0 : 1-(d/nicheSize) ); - } - } + { + distMatrix(i,i)=1; + for (j=0; jnicheSize ? 0 : 1-(d/nicheSize) ); + } + } for (i=0; i & dist; // specific distance + eoDistance & dist; // specific distance }; diff --git a/eo/src/eoSharingSelect.h b/eo/src/eoSharingSelect.h index d9b56568..0754cdd0 100644 --- a/eo/src/eoSharingSelect.h +++ b/eo/src/eoSharingSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSharingSelect.h // (c) GeNeura Team, 1998, Maarten Keijzer 2000, 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 @@ -31,28 +31,28 @@ #include #include -/** eoSharingSelect: select an individual by roulette wheel - * on its SHARED fitness. It is an eoRouletteWorthSelect, +/** eoSharingSelect: select an individual by roulette wheel + * on its SHARED fitness. It is an eoRouletteWorthSelect, * i.e. a selector using a std::vector of worthes * rather than the raw fitness (see eoSelectFromWorth.h) - * It uses an internal eoSharing object which is + * It uses an internal eoSharing object which is * an eoPerf2Worth * @ingroup Selectors */ -template -class eoSharingSelect: public eoRouletteWorthSelect +template +class eoSharingSelect: public eoRouletteWorthSelect { public: /** Ctor: * @param _sigma the sigma_share * @param _dist the distance object to use */ - eoSharingSelect(double _sigma, eoDistance & _dist): + eoSharingSelect(double _sigma, eoDistance & _dist): eoRouletteWorthSelect(sharing), sharing(_sigma, _dist) {} private : - eoSharing sharing; // derived from eoPerf2Worth + eoSharing sharing; // derived from eoPerf2Worth }; /** @example t-eoSharing.cpp */ diff --git a/eo/src/eoShiftMutation.h b/eo/src/eoShiftMutation.h index d1a13268..a9b71d66 100644 --- a/eo/src/eoShiftMutation.h +++ b/eo/src/eoShiftMutation.h @@ -4,7 +4,7 @@ // eoShiftMutation.h // (c) GeNeura Team, 2000 - EEAAX 2000 - Maarten Keijzer 2000 // (c) INRIA Futurs - Dolphin Team - Thomas Legrand 2007 -/* +/* 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 @@ -20,7 +20,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - thomas.legrand@lifl.fr + thomas.legrand@lifl.fr Marc.Schoenauer@polytechnique.fr mak@dhi.dk */ @@ -40,13 +40,13 @@ template class eoShiftMutation: public eoMonOp { public: - + typedef typename EOT::AtomType GeneType; - + /// CTor eoShiftMutation(){} - - + + /// The class name. virtual std::string className() const { return "eoShiftMutation"; } @@ -57,36 +57,35 @@ template class eoShiftMutation: public eoMonOp */ bool operator()(EOT& _eo) { - - unsigned i, j, from, to; + + unsigned i, j, from, to; GeneType tmp; - + // generate two different indices i=eo::rng.random(_eo.size()); - do j = eo::rng.random(_eo.size()); while (i == j); - + do j = eo::rng.random(_eo.size()); while (i == j); + // indexes from=std::min(i,j); to=std::max(i,j); // keep the first component to change - tmp=_eo[to]; - + tmp=_eo[to]; + // shift for(unsigned int k=to ; k > from ; k--) - _eo[k]=_eo[k-1]; - + _eo[k]=_eo[k-1]; + // shift the first component _eo[from]=tmp; return true; } - + }; /** @example t-eoShiftMutation.cpp - */ + */ //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoSigBinaryFlight.h b/eo/src/eoSigBinaryFlight.h index a172484a..dccf2e5f 100644 --- a/eo/src/eoSigBinaryFlight.h +++ b/eo/src/eoSigBinaryFlight.h @@ -19,7 +19,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: thomas.legrand@lifl.fr - clive.canape@inria.fr + clive.canape@inria.fr */ //----------------------------------------------------------------------------- @@ -33,14 +33,14 @@ /** - * Binary flight for particle swarm optimization based on the sigmoid function. Velocities are expected to be "double" + * Binary flight for particle swarm optimization based on the sigmoid function. Velocities are expected to be "double" * Consider Pi to be the i-th position of a particle and Vi to be the i-th velocity of the same particle : - * if rand[0;1] < sig(Vi) (Vi <=> double) - * Pi=1 - * else - * Pi=0 + * if rand[0;1] < sig(Vi) (Vi <=> double) + * Pi=1 + * else + * Pi=0 * - * @ingroup Variators + * @ingroup Variators */ template < class POT > class eoSigBinaryFlight:public eoBinaryFlight < POT > { @@ -65,7 +65,7 @@ public: /** * Apply the sigmoid binary flight to a particle. - * + * */ void operator () (POT & _po) { @@ -85,8 +85,8 @@ public: } private : - unsigned slope; - + unsigned slope; + }; diff --git a/eo/src/eoSimpleEDA.h b/eo/src/eoSimpleEDA.h index c2a75672..afbf152f 100644 --- a/eo/src/eoSimpleEDA.h +++ b/eo/src/eoSimpleEDA.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSimpleEDA.h // (c) Marc Schoenauer, Maarten Keijzer, 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 @@ -35,8 +35,8 @@ #include /** A very simple Estimation of Distribution Algorithm - * - * The algorithm that evolves a probability distribution + * + * The algorithm that evolves a probability distribution * on the spaces of populations with the loop * generate a population from the current distribution * evaluate that population @@ -53,19 +53,19 @@ template class eoSimpleEDA: public eoEDA * plus an eoEval and eoContinue of course. */ eoSimpleEDA(eoDistribUpdater& _update, - eoEvalFunc& _eval, - unsigned _popSize, - eoContinue& _continuator - ) : + eoEvalFunc& _eval, + unsigned _popSize, + eoContinue& _continuator + ) : update(_update), eval(_eval), popSize(_popSize), continuator(_continuator) {} - /** The algorithm: - * generate pop from distrib, - * evaluate pop, + /** The algorithm: + * generate pop from distrib, + * evaluate pop, * update distrib */ virtual void operator()(eoDistribution& _distrib) @@ -75,18 +75,18 @@ template class eoSimpleEDA: public eoEDA { try { - apply(_distrib, pop); // re-init. of _pop from distrib + apply(_distrib, pop); // re-init. of _pop from distrib - apply(eval, pop); // eval of current population + apply(eval, pop); // eval of current population + + update(_distrib, pop); // updates distrib from _pop - update(_distrib, pop); // updates distrib from _pop - } catch (std::exception& e) { - std::string s = e.what(); - s.append( " in eoSimpleEDA"); - throw std::runtime_error( s ); + std::string s = e.what(); + s.append( " in eoSimpleEDA"); + throw std::runtime_error( s ); } } while ( continuator( pop ) ); } @@ -95,7 +95,7 @@ template class eoSimpleEDA: public eoEDA eoDistribUpdater & update; eoEvalFunc& eval; - + unsigned popSize; eoContinue& continuator; @@ -104,4 +104,3 @@ template class eoSimpleEDA: public eoEDA //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoSocialNeighborhood.h b/eo/src/eoSocialNeighborhood.h index cb8dd9f9..944031f9 100644 --- a/eo/src/eoSocialNeighborhood.h +++ b/eo/src/eoSocialNeighborhood.h @@ -52,7 +52,7 @@ public: } /** - * Return true if the neighborhood contains the indice (= that means "contains the + * Return true if the neighborhood contains the indice (= that means "contains the * particle whose indice is _oneIndice") * @param _oneIndice - The indice of the particle in its population. */ @@ -123,4 +123,3 @@ protected: #endif /* EOSOCIALNEIGHBORHOOD_H_ */ - diff --git a/eo/src/eoStandardFlight.h b/eo/src/eoStandardFlight.h index 0c8008be..228839eb 100644 --- a/eo/src/eoStandardFlight.h +++ b/eo/src/eoStandardFlight.h @@ -49,7 +49,7 @@ public: /** Constructor without bounds. - * + * */ eoStandardFlight ():bnds (*(new eoRealVectorNoBounds(0))){} diff --git a/eo/src/eoStandardVelocity.h b/eo/src/eoStandardVelocity.h index e2b6deb1..62abd487 100644 --- a/eo/src/eoStandardVelocity.h +++ b/eo/src/eoStandardVelocity.h @@ -38,7 +38,7 @@ /** Standard velocity performer for particle swarm optimization. Derivated from abstract eoVelocity, * At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) -* lbest depends on the topology evolved, when using eoStarTopology, lbest corresponds to the +* lbest depends on the topology evolved, when using eoStarTopology, lbest corresponds to the * global. Otherwise, lbest is a "local best", i.e the best in a neighborhood. * * @ingroup Variators @@ -56,15 +56,15 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng */ eoStandardVelocity (eoTopology < POT > & _topology, - const VelocityType & _w, + const VelocityType & _w, const VelocityType & _c1, const VelocityType & _c2, eoRealVectorBounds & _bounds, @@ -82,9 +82,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -106,8 +106,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoStandardVelocity (eoTopology < POT > & _topology, @@ -167,30 +167,29 @@ public: { topology.updateNeighborhood(_po,_indice); } - + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & omega; // social/cognitive coefficient - const VelocityType & c1; // social/cognitive coefficient - const VelocityType & c2; // social/cognitive coefficient - - eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. - eoRealBoundModifier & bndsModifier; + const VelocityType & omega; // social/cognitive coefficient + const VelocityType & c1; // social/cognitive coefficient + const VelocityType & c2; // social/cognitive coefficient + + eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + eoRng & gen; // the random generator - eoRng & gen; // the random generator - // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOSTANDARDVELOCITY_H */ - diff --git a/eo/src/eoStarTopology.h b/eo/src/eoStarTopology.h index d491800c..02df64a9 100644 --- a/eo/src/eoStarTopology.h +++ b/eo/src/eoStarTopology.h @@ -91,9 +91,9 @@ public: // update the best fitness of the particle if (_po.fitness() > _po.best()) { - _po.best(_po.fitness()); - for(unsigned i=0;i<_po.size();i++) - _po.bestPositions[i]=_po[i]; + _po.best(_po.fitness()); + for(unsigned i=0;i<_po.size();i++) + _po.bestPositions[i]=_po[i]; } // update the global best if the given particle is "better" if (_po.fitness() > neighborhood.best().fitness()) @@ -109,14 +109,14 @@ public: * @return POT & - The best particle in the neighborhood of the particle whose indice is _indice */ POT & best (unsigned _indice) {return (neighborhood.best());} - + /* - * Return the global best of the topology - */ - - virtual POT & globalBest(const eoPop& _pop) + * Return the global best of the topology + */ + + virtual POT & globalBest(const eoPop& _pop) { - return neighborhood.best(); + return neighborhood.best(); } @@ -139,11 +139,3 @@ protected: }; #endif /*EOSTARTOPOLOGY_H_ */ - - - - - - - - diff --git a/eo/src/eoSteadyFitContinue.h b/eo/src/eoSteadyFitContinue.h index 7e5c8e21..229d93bc 100644 --- a/eo/src/eoSteadyFitContinue.h +++ b/eo/src/eoSteadyFitContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSteadyFitContinue.h // (c) GeNeura Team, 1999, Marc Schoenauer, 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 @@ -28,9 +28,9 @@ #include #include -/** +/** A continuator: does a minimum number of generations, then - stops whenever a given number of generations takes place without improvement + stops whenever a given number of generations takes place without improvement @ingroup Continuators */ @@ -45,10 +45,10 @@ public: : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGens), steadyState(false), thisGenerationPlaceHolder(0), thisGeneration(thisGenerationPlaceHolder){}; - + /// Ctor for enabling the save/load the no. of generations counted eoSteadyFitContinue( unsigned long _minGens, unsigned long _steadyGen, - unsigned long& _currentGen) + unsigned long& _currentGen) : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGen), steadyState(_currentGen>_minGens), thisGenerationPlaceHolder(0), thisGeneration(_currentGen){}; @@ -57,54 +57,54 @@ public: * reached withtout improvement */ virtual bool operator() ( const eoPop& _vEO ) { thisGeneration++; - + Fitness bestCurrentFitness = _vEO.nth_element_fitness(0); - if (steadyState) { // already after MinGenenerations + if (steadyState) { // already after MinGenenerations if (bestCurrentFitness > bestSoFar) { - bestSoFar = bestCurrentFitness; - lastImprovement = thisGeneration; + bestSoFar = bestCurrentFitness; + lastImprovement = thisGeneration; } else { - if (thisGeneration - lastImprovement > repSteadyGenerations) { - eo::log << eo::progress << "STOP in eoSteadyFitContinue: Done " << repSteadyGenerations - << " generations without improvement\n"; - return false; - } - } - } else { // not yet in steady state + if (thisGeneration - lastImprovement > repSteadyGenerations) { + eo::log << eo::progress << "STOP in eoSteadyFitContinue: Done " << repSteadyGenerations + << " generations without improvement\n"; + return false; + } + } + } else { // not yet in steady state if (thisGeneration > repMinGenerations) { // go to steady state - steadyState = true; - bestSoFar = bestCurrentFitness; - lastImprovement = thisGeneration; + steadyState = true; + bestSoFar = bestCurrentFitness; + lastImprovement = thisGeneration; eo::log << eo::progress << "eoSteadyFitContinue: Done the minimum number of generations\n"; } } return true; } - /** Sets the parameters (minimum nb of gen. + steady nb of gen.) + /** Sets the parameters (minimum nb of gen. + steady nb of gen.) and sets the current generation to 0 (the begin) - + @todo replace thi by an init method ? */ - virtual void totalGenerations( unsigned long _mg, unsigned long _sg ) { - repMinGenerations = _mg; + virtual void totalGenerations( unsigned long _mg, unsigned long _sg ) { + repMinGenerations = _mg; repSteadyGenerations = _sg; reset(); }; - /// Resets the state after it's been reached + /// Resets the state after it's been reached virtual void reset () { steadyState=false; thisGeneration = 0; } /** accessors*/ - virtual unsigned long minGenerations( ) - { return repMinGenerations; }; - virtual unsigned long steadyGenerations( ) - { return repSteadyGenerations; }; - + virtual unsigned long minGenerations( ) + { return repMinGenerations; }; + virtual unsigned long steadyGenerations( ) + { return repSteadyGenerations; }; + virtual std::string className(void) const { return "eoSteadyFitContinue"; } private: unsigned long repMinGenerations; @@ -117,4 +117,3 @@ private: }; #endif - diff --git a/eo/src/eoStochTournamentSelect.h b/eo/src/eoStochTournamentSelect.h index 952041e1..65004129 100644 --- a/eo/src/eoStochTournamentSelect.h +++ b/eo/src/eoStochTournamentSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoStochTournamentSelect.h // (c) GeNeura Team, 1998 - EEAAX 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,9 +31,9 @@ #include // stochastic_tournament /** eoStochTournamentSelect: a selection method that selects ONE individual by - binary stochastic tournament - -MS- 24/10/99 - + binary stochastic tournament + -MS- 24/10/99 + @ingroup Selectors */ template class eoStochTournamentSelect: public eoSelectOne @@ -41,7 +41,7 @@ template class eoStochTournamentSelect: public eoSelectOne public: /// - eoStochTournamentSelect(double _Trate = 1.0 ) : eoSelectOne(), Trate(_Trate) + eoStochTournamentSelect(double _Trate = 1.0 ) : eoSelectOne(), Trate(_Trate) { // consistency checks if (Trate < 0.5) { @@ -53,16 +53,15 @@ template class eoStochTournamentSelect: public eoSelectOne Trate = 1; } } - + /** Perform the stochastic tournament */ - virtual const EOT& operator()(const eoPop& pop) + virtual const EOT& operator()(const eoPop& pop) { return stochastic_tournament(pop, Trate); } - + private: double Trate; }; #endif - diff --git a/eo/src/eoStochasticUniversalSelect.h b/eo/src/eoStochasticUniversalSelect.h index 003c7012..fb1669ec 100644 --- a/eo/src/eoStochasticUniversalSelect.h +++ b/eo/src/eoStochasticUniversalSelect.h @@ -59,7 +59,7 @@ public: cumulative[0] = _pop[0].fitness(); for (unsigned i = 1; i < _pop.size(); ++i) { - cumulative[i] = _pop[i].fitness() + cumulative[i-1]; + cumulative[i] = _pop[i].fitness() + cumulative[i-1]; } indices.reserve(_pop.size()); @@ -72,19 +72,19 @@ public: while (indices.size() < _pop.size()) { - while (cumulative[i] < fortune) {i++;} // linear search is good enough as we average one step each time + while (cumulative[i] < fortune) {i++;} // linear search is good enough as we average one step each time - indices.push_back(i); - fortune += step; - if (fortune >= cumulative.back()) { // start at the beginning - fortune -= cumulative.back(); - i = 0; - } + indices.push_back(i); + fortune += step; + if (fortune >= cumulative.back()) { // start at the beginning + fortune -= cumulative.back(); + i = 0; + } } // shuffle for (int i = indices.size() - 1; i > 0; --i) { - int j = rng.random(i+1); - std::swap(indices[i], indices[j]); + int j = rng.random(i+1); + std::swap(indices[i], indices[j]); } } diff --git a/eo/src/eoSurviveAndDie.h b/eo/src/eoSurviveAndDie.h index 3650a536..63cf2219 100644 --- a/eo/src/eoSurviveAndDie.h +++ b/eo/src/eoSurviveAndDie.h @@ -59,8 +59,8 @@ class eoSurviveAndDie : public eoBF &, eoPop &, void> { public: eoSurviveAndDie(double _survive, double _die, bool _interpret_as_rate = true): - howmanySurvive(_survive, _interpret_as_rate), - howmanyDie(_die, _interpret_as_rate) + howmanySurvive(_survive, _interpret_as_rate), + howmanyDie(_die, _interpret_as_rate) {} protected: @@ -90,33 +90,33 @@ public: void operator()(eoPop & _pop, eoPop & _luckyGuys) { - unsigned pSize = _pop.size(); - unsigned nbSurvive = howmanySurvive(pSize); - // first, save the best into _luckyGuys - if (nbSurvive) - { - _pop.nth_element(nbSurvive); - // copy best - _luckyGuys.resize(nbSurvive); - std::copy(_pop.begin(), _pop.begin()+nbSurvive, _luckyGuys.begin()); - // erase them from pop - _pop.erase(_pop.begin(), _pop.begin()+nbSurvive); - } - unsigned nbRemaining = _pop.size(); + unsigned pSize = _pop.size(); + unsigned nbSurvive = howmanySurvive(pSize); + // first, save the best into _luckyGuys + if (nbSurvive) + { + _pop.nth_element(nbSurvive); + // copy best + _luckyGuys.resize(nbSurvive); + std::copy(_pop.begin(), _pop.begin()+nbSurvive, _luckyGuys.begin()); + // erase them from pop + _pop.erase(_pop.begin(), _pop.begin()+nbSurvive); + } + unsigned nbRemaining = _pop.size(); - // carefull, we can have a rate of 1 if we want to kill all remaining - unsigned nbDie = std::min(howmanyDie(pSize), pSize-nbSurvive); - if (nbDie > nbRemaining) - throw std::logic_error("eoDeterministicSurviveAndDie: Too many to kill!\n"); + // carefull, we can have a rate of 1 if we want to kill all remaining + unsigned nbDie = std::min(howmanyDie(pSize), pSize-nbSurvive); + if (nbDie > nbRemaining) + throw std::logic_error("eoDeterministicSurviveAndDie: Too many to kill!\n"); - if (!nbDie) - { - return; - } - // else - // kill the worse nbDie - _pop.nth_element(nbRemaining-nbDie); - _pop.resize(nbRemaining-nbDie); + if (!nbDie) + { + return; + } + // else + // kill the worse nbDie + _pop.nth_element(nbRemaining-nbDie); + _pop.resize(nbRemaining-nbDie); } }; @@ -139,45 +139,45 @@ class eoDeterministicSaDReplacement : public eoReplacement public: /** Constructor with reduce */ eoDeterministicSaDReplacement(eoReduce& _reduceGlobal, - double _surviveParents, double _dieParents=0, - double _surviveOffspring=0, double _dieOffspring=0, - bool _interpret_as_rate = true ) : - reduceGlobal(_reduceGlobal), - sAdParents(_surviveParents, _dieParents, _interpret_as_rate), - sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) + double _surviveParents, double _dieParents=0, + double _surviveOffspring=0, double _dieOffspring=0, + bool _interpret_as_rate = true ) : + reduceGlobal(_reduceGlobal), + sAdParents(_surviveParents, _dieParents, _interpret_as_rate), + sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) {} /** Constructor with default truncate used as reduce */ eoDeterministicSaDReplacement( - double _surviveParents, double _dieParents=0, - double _surviveOffspring=0, double _dieOffspring=0, - bool _interpret_as_rate = true ) : - reduceGlobal(truncate), - sAdParents(_surviveParents, _dieParents, _interpret_as_rate), - sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) + double _surviveParents, double _dieParents=0, + double _surviveOffspring=0, double _dieOffspring=0, + bool _interpret_as_rate = true ) : + reduceGlobal(truncate), + sAdParents(_surviveParents, _dieParents, _interpret_as_rate), + sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) {} void operator()(eoPop& _parents, eoPop& _offspring) { - unsigned pSize = _parents.size(); // target number of individuals + unsigned pSize = _parents.size(); // target number of individuals - eoPop luckyParents; // to hold the absolute survivors - sAdParents(_parents, luckyParents); + eoPop luckyParents; // to hold the absolute survivors + sAdParents(_parents, luckyParents); - eoPop luckyOffspring; // to hold the absolute survivors - sAdOffspring(_offspring, luckyOffspring); + eoPop luckyOffspring; // to hold the absolute survivors + sAdOffspring(_offspring, luckyOffspring); - unsigned survivorSize = luckyOffspring.size() + luckyParents.size(); - if (survivorSize > pSize) - throw std::logic_error("eoGeneralReplacement: More survivors than parents!\n"); + unsigned survivorSize = luckyOffspring.size() + luckyParents.size(); + if (survivorSize > pSize) + throw std::logic_error("eoGeneralReplacement: More survivors than parents!\n"); - plus(_parents, _offspring); // all that remain in _offspring + plus(_parents, _offspring); // all that remain in _offspring - reduceGlobal(_offspring, pSize - survivorSize); - plus(luckyParents, _offspring); - plus(luckyOffspring, _offspring); + reduceGlobal(_offspring, pSize - survivorSize); + plus(luckyParents, _offspring); + plus(luckyOffspring, _offspring); - _parents.swap(_offspring); + _parents.swap(_offspring); } @@ -195,4 +195,3 @@ private : /** @} */ #endif - diff --git a/eo/src/eoSwapMutation.h b/eo/src/eoSwapMutation.h index 63169a9b..58d3cf60 100644 --- a/eo/src/eoSwapMutation.h +++ b/eo/src/eoSwapMutation.h @@ -4,7 +4,7 @@ // eoSwapMutation.h // (c) GeNeura Team, 2000 - EEAAX 2000 - Maarten Keijzer 2000 // (c) INRIA Futurs - Dolphin Team - Thomas Legrand 2007 -/* +/* 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 @@ -20,7 +20,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - thomas.legrand@lifl.fr + thomas.legrand@lifl.fr Marc.Schoenauer@polytechnique.fr mak@dhi.dk */ @@ -40,15 +40,15 @@ template class eoSwapMutation: public eoMonOp { public: - + /// CTor - eoSwapMutation(const unsigned _howManySwaps=1): howManySwaps(_howManySwaps) + eoSwapMutation(const unsigned _howManySwaps=1): howManySwaps(_howManySwaps) { - // consistency check - if(howManySwaps < 1) - throw std::runtime_error("Invalid number of swaps in eoSwapMutation"); + // consistency check + if(howManySwaps < 1) + throw std::runtime_error("Invalid number of swaps in eoSwapMutation"); } - + /// The class name. virtual std::string className() const { return "eoSwapMutation"; } @@ -58,26 +58,25 @@ template class eoSwapMutation: public eoMonOp */ bool operator()(Chrom& chrom) { - unsigned i, j; - - for(unsigned int swap = 0; swap < howManySwaps; swap++) + unsigned i, j; + + for(unsigned int swap = 0; swap < howManySwaps; swap++) { - // generate two different indices - i=eo::rng.random(chrom.size()); - do j = eo::rng.random(chrom.size()); while (i == j); - - // swap - std::swap(chrom[i],chrom[j]); - } + // generate two different indices + i=eo::rng.random(chrom.size()); + do j = eo::rng.random(chrom.size()); while (i == j); + + // swap + std::swap(chrom[i],chrom[j]); + } return true; } - + private: - unsigned int howManySwaps; + unsigned int howManySwaps; }; /** @example t-eoSwapMutation.cpp */ //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoSyncEasyPSO.h b/eo/src/eoSyncEasyPSO.h index aa1c9130..f05f15f6 100644 --- a/eo/src/eoSyncEasyPSO.h +++ b/eo/src/eoSyncEasyPSO.h @@ -34,15 +34,15 @@ //----------------------------------------------------------------------------- /** An easy-to-use synchronous particle swarm algorithm; you can use any particle, -* any flight, any topology... +* any flight, any topology... * * The main steps are : -* - perform a first evaluation of the population -* - for each generation -* - evaluate ALL the velocities -* -- perform the fligth of ALL the particles -* -- evaluate ALL the particles -* -- update the neighborhoods +* - perform a first evaluation of the population +* - for each generation +* - evaluate ALL the velocities +* -- perform the fligth of ALL the particles +* -- evaluate ALL the particles +* -- update the neighborhoods * * @ingroup Algorithms */ @@ -55,7 +55,7 @@ public: * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoSyncEasyPSO ( @@ -117,11 +117,11 @@ public: {} - /** Another constructor without initializer + /** Another constructor without initializer * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoSyncEasyPSO ( @@ -176,7 +176,7 @@ public: velocity (_velocity), flight (_flight) {} - + /// Apply a few iteration of flight to the population (=swarm). virtual void operator () (eoPop < POT > &_pop) { @@ -185,7 +185,7 @@ public: { // initializes the topology, velocity, best particle(s) init(); - + // just to use a loop eval eoPop empty_pop; @@ -229,29 +229,29 @@ private: eoFlight < POT > &flight; // if the eval does not need to be used, use the dummy eval instance - class eoDummyEval : public eoEvalFunc - { - public: - void operator()(POT &) - {} - } - dummyEval; + class eoDummyEval : public eoEvalFunc + { + public: + void operator()(POT &) + {} + } + dummyEval; + + class eoDummyFlight:public eoFlight < POT > + { + public: + eoDummyFlight () {} + void operator () (POT & _po) {} + }dummyFlight; + + // if the initializer does not need to be used, use the dummy one instead + class eoDummyInitializer:public eoInitializerBase < POT > + { + public: + eoDummyInitializer () {} + void operator () (POT & _po) {} + }dummyInit; - class eoDummyFlight:public eoFlight < POT > - { - public: - eoDummyFlight () {} - void operator () (POT & _po) {} - }dummyFlight; - - // if the initializer does not need to be used, use the dummy one instead - class eoDummyInitializer:public eoInitializerBase < POT > - { - public: - eoDummyInitializer () {} - void operator () (POT & _po) {} - }dummyInit; - }; /** @example t-eoSyncEasyPSO.cpp */ diff --git a/eo/src/eoTopology.h b/eo/src/eoTopology.h index 24bfe851..a12bf43d 100644 --- a/eo/src/eoTopology.h +++ b/eo/src/eoTopology.h @@ -70,9 +70,9 @@ public: virtual POT & best (unsigned ) = 0; - /* - * Return the global best of the topology - */ + /* + * Return the global best of the topology + */ virtual POT & globalBest() = 0; @@ -84,11 +84,3 @@ public: #endif /*EOTOPOLOGY_H_ */ - - - - - - - - diff --git a/eo/src/eoTransform.h b/eo/src/eoTransform.h index 67dd712a..f8823382 100644 --- a/eo/src/eoTransform.h +++ b/eo/src/eoTransform.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTransform.h + eoTransform.h (c) Maarten Keijzer, 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 @@ -30,7 +30,7 @@ #include //----------------------------------------------------------------------------- -/** +/** eoTransform transforms a population by applying genetic operators on it. @ingroup Combination diff --git a/eo/src/eoTruncSelect.h b/eo/src/eoTruncSelect.h index 8f75e215..e46b39bc 100644 --- a/eo/src/eoTruncSelect.h +++ b/eo/src/eoTruncSelect.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTruncSelect.h + eoTruncSelect.h (c) Maarten Keijzer, Marc Schoenauer, 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 @@ -35,7 +35,7 @@ //----------------------------------------------------------------------------- /** eoTruncSelect selects individuals after truncating the population - * using eoSelectOne as it's mechanism. + * using eoSelectOne as it's mechanism. * Therefore eoSelectMany needs an eoSelectOne in its ctor * It will use an eoHowMnay to determine the number of guys to keep, * @@ -46,9 +46,9 @@ class eoTruncSelect : public eoSelect { public: /** Ctor: from an eoSelect (and an eoMany to tell how many are kept for selectino */ - eoTruncSelect(eoSelectOne& _select, eoHowMany _howMany) + eoTruncSelect(eoSelectOne& _select, eoHowMany _howMany) : select(_select), howMany(_howMany) {} - + /** The implementation repeatidly selects an individual @@ -58,15 +58,15 @@ class eoTruncSelect : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { unsigned target = howMany(_source.size()); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; eoHowMany howMany; diff --git a/eo/src/eoTruncatedSelectMany.h b/eo/src/eoTruncatedSelectMany.h index 5e999459..1b3bad72 100644 --- a/eo/src/eoTruncatedSelectMany.h +++ b/eo/src/eoTruncatedSelectMany.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTruncatedSelectMany.h + eoTruncatedSelectMany.h (c) Maarten Keijzer, Marc Schoenauer, 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 @@ -35,7 +35,7 @@ #include //----------------------------------------------------------------------------- -/** eoTruncatedSelectMany selects many individuals using eoSelectOne as it's +/** eoTruncatedSelectMany selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectMany needs an eoSelectOne in its ctor It will use an eoHowMnay to determine the number of guys to select, @@ -43,10 +43,10 @@ And it will only perform selection from the top guys in the population. - It is NOT a special case of eoSelectMany because it needs to SORT + It is NOT a special case of eoSelectMany because it needs to SORT the population to discard the worst guys before doing the selection - However, the same result can be obtained by embedding an + However, the same result can be obtained by embedding an eoTruncatedSelectOne into an eoSelectMany ... @ingroup Selectors @@ -56,19 +56,19 @@ class eoTruncatedSelectMany : public eoSelect { public: /// Ctor - eoTruncatedSelectMany(eoSelectOne& _select, - double _rateGenitors, double _rateFertile, - bool _interpret_as_rateG = true, - bool _interpret_as_rateF = true) - : select(_select), - howManyGenitors(_rateGenitors, _interpret_as_rateG), - howManyFertile(_rateFertile, _interpret_as_rateF) {} + eoTruncatedSelectMany(eoSelectOne& _select, + double _rateGenitors, double _rateFertile, + bool _interpret_as_rateG = true, + bool _interpret_as_rateF = true) + : select(_select), + howManyGenitors(_rateGenitors, _interpret_as_rateG), + howManyFertile(_rateFertile, _interpret_as_rateF) {} // Ctor with eoHowManys - eoTruncatedSelectMany(eoSelectOne& _select, - eoHowMany _howManyGenitors, eoHowMany _howManyFertile) + eoTruncatedSelectMany(eoSelectOne& _select, + eoHowMany _howManyGenitors, eoHowMany _howManyFertile) : select(_select), howManyGenitors(_howManyGenitors), - howManyFertile(_howManyFertile) {} + howManyFertile(_howManyFertile) {} /** The implementation repeatidly selects an individual @@ -87,33 +87,33 @@ class eoTruncatedSelectMany : public eoSelect //revert to standard selection (see eoSelectMany) if no truncation if (nbFertile == _source.size()) { - select.setup(_source); - - for (size_t i = 0; i < _dest.size(); ++i) - _dest[i] = select(_source); + select.setup(_source); + + for (size_t i = 0; i < _dest.size(); ++i) + _dest[i] = select(_source); } else { // at the moment, brute force (rush rush, no good) // what we would need otherwise is a std::vector class // and selectors that act on such a thing - eoPop tmpPop = _source; // hum hum, could be a pain in the ass + eoPop tmpPop = _source; // hum hum, could be a pain in the ass - tmpPop.sort(); // maybe we could only do partial sort? - tmpPop.resize(nbFertile); // only the best guys here now - tmpPop.shuffle(); // as some selectors are order-sensitive + tmpPop.sort(); // maybe we could only do partial sort? + tmpPop.resize(nbFertile); // only the best guys here now + tmpPop.shuffle(); // as some selectors are order-sensitive - select.setup(tmpPop); - - for (size_t i = 0; i < _dest.size(); ++i) - _dest[i] = select(tmpPop); + select.setup(tmpPop); + + for (size_t i = 0; i < _dest.size(); ++i) + _dest[i] = select(tmpPop); } } - + private : - eoSelectOne& select; // selector for one guy - eoHowMany howManyGenitors; // number of guys to select - eoHowMany howManyFertile; // number of fertile guys + eoSelectOne& select; // selector for one guy + eoHowMany howManyGenitors; // number of guys to select + eoHowMany howManyFertile; // number of fertile guys }; #endif diff --git a/eo/src/eoTruncatedSelectOne.h b/eo/src/eoTruncatedSelectOne.h index c0fed203..e86cce81 100644 --- a/eo/src/eoTruncatedSelectOne.h +++ b/eo/src/eoTruncatedSelectOne.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTruncatedSelectOne.h + eoTruncatedSelectOne.h (c) Maarten Keijzer, Marc Schoenauer, 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 @@ -35,7 +35,7 @@ #include //----------------------------------------------------------------------------- -/** eoTruncatedSelectOne selects one individual using eoSelectOne as it's +/** eoTruncatedSelectOne selects one individual using eoSelectOne as it's mechanism. Therefore eoTruncatedSelectOne needs an eoSelectOne in its ctor It will perform selection only from the top guys in the population. @@ -47,17 +47,17 @@ class eoTruncatedSelectOne : public eoSelectOne { public: /** Ctor from rate and bool */ - eoTruncatedSelectOne(eoSelectOne& _select, - double _rateFertile, - bool _interpret_as_rateF = true) - : select(_select), + eoTruncatedSelectOne(eoSelectOne& _select, + double _rateFertile, + bool _interpret_as_rateF = true) + : select(_select), howManyFertile(_rateFertile, _interpret_as_rateF), tmpPop(), actualPop(tmpPop) {} /** Ctor with eoHowMany */ - eoTruncatedSelectOne(eoSelectOne& _select, - eoHowMany _howManyFertile) + eoTruncatedSelectOne(eoSelectOne& _select, + eoHowMany _howManyFertile) : select(_select), howManyFertile(_howManyFertile), tmpPop(), actualPop(tmpPop) {} @@ -69,19 +69,19 @@ public: unsigned fertile = howManyFertile(_source.size()); if (fertile == _source.size()) // noting to do, all are fertile { - actualPop = _source; + actualPop = _source; } else { - // copy only best ferile to actualPop - tmpPop.resize(fertile); - std::vector result; - _source.nth_element(fertile, result); - for (unsigned i=0; i result; + _source.nth_element(fertile, result); + for (unsigned i=0; i& _pop) + const EOT& operator()(const eoPop& _pop) { return select(actualPop); } private : - eoSelectOne& select; // selector for one guy - eoHowMany howManyFertile; // number of fertile guys - eoPop tmpPop; // intermediate population - fertile guys - eoPop & actualPop; // to avoid copies when 100% fertility + eoSelectOne& select; // selector for one guy + eoHowMany howManyFertile; // number of fertile guys + eoPop tmpPop; // intermediate population - fertile guys + eoPop & actualPop; // to avoid copies when 100% fertility }; #endif diff --git a/eo/src/eoVariableInertiaWeightedVelocity.h b/eo/src/eoVariableInertiaWeightedVelocity.h index d281b39d..a926feee 100644 --- a/eo/src/eoVariableInertiaWeightedVelocity.h +++ b/eo/src/eoVariableInertiaWeightedVelocity.h @@ -56,9 +56,9 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -82,9 +82,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -106,8 +106,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoVariableInertiaWeightedVelocity (eoTopology < POT > & _topology, @@ -126,7 +126,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - update the weight with the weightUpdater (use the dummy updater if there's no updater provided) @@ -181,19 +181,18 @@ public: protected: eoTopology < POT > & topology; - eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 - - eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. + eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 + + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealBoundModifier & bndsModifier; - + VelocityType weight; - eoRng & gen; // the random generator + eoRng & gen; // the random generator // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOVARIABLEINERTIAWEIGHTEDVELOCITY_H*/ - diff --git a/eo/src/eoVariableLengthCrossover.h b/eo/src/eoVariableLengthCrossover.h index 5ad6de05..510fc9b0 100644 --- a/eo/src/eoVariableLengthCrossover.h +++ b/eo/src/eoVariableLengthCrossover.h @@ -66,7 +66,7 @@ public: { mask.resize(_size1 + _size2); for (unsigned i=0; i<_size1+_size2; i++) - mask[i]=eo::rng.flip(rate); + mask[i]=eo::rng.flip(rate); } /** the operator() simply returns the mask booleans in turn */ @@ -98,12 +98,12 @@ public : /** default ctor: requires bounds on number of genes + a rate */ eoVlAtomExchangeQuadOp(unsigned _Min, unsigned _Max, - eoAtomExchange& _atomExchange): + eoAtomExchange& _atomExchange): Min(_Min), Max(_Max), atomExchange(_atomExchange) {} bool operator()(EOT & _eo1, EOT & _eo2) { - EOT tmp1, tmp2; // empty individuals + EOT tmp1, tmp2; // empty individuals unsigned index=0; // main loop: until sizes are OK, do only simulated exchange unsigned i, i1, i2; @@ -113,47 +113,47 @@ public : // simulate crossover i1=i2=0; for (i=0; i<_eo1.size(); i++) - { - if (atomExchange(i, _eo1[i])) - i1++; - else - i2++; - } + { + if (atomExchange(i, _eo1[i])) + i1++; + else + i2++; + } for (i=0; i<_eo2.size(); i++) - { - if (atomExchange(i, _eo2[i])) - i2++; - else - i1++; - } + { + if (atomExchange(i, _eo2[i])) + i2++; + else + i1++; + } index++; } while ( ( (i1Max) || (i2>Max) ) - && (index<10000) ); + (i1>Max) || (i2>Max) ) + && (index<10000) ); if (index >= 10000) { eo::log << eo::warnings << "Warning: impossible to generate individual of the right size in 10000 trials" << std::endl; - return false; + return false; } // here we know we have the right sizes: do the actual exchange for (i=0; i<_eo1.size(); i++) - { - if (atomExchange(i, _eo1[i])) - tmp1.push_back(_eo1[i]); - else - tmp2.push_back(_eo1[i]); - } + { + if (atomExchange(i, _eo1[i])) + tmp1.push_back(_eo1[i]); + else + tmp2.push_back(_eo1[i]); + } for (i=0; i<_eo2.size(); i++) - { - if (atomExchange(i, _eo2[i])) - tmp2.push_back(_eo2[i]); - else - tmp1.push_back(_eo2[i]); - } + { + if (atomExchange(i, _eo2[i])) + tmp2.push_back(_eo2[i]); + else + tmp1.push_back(_eo2[i]); + } // and put everything back in place _eo1.swap(tmp1); _eo2.swap(tmp2); - return true; // should we test that? Yes, but no time now + return true; // should we test that? Yes, but no time now } /** the inherited className */ @@ -190,11 +190,11 @@ public : bool changed = false; for ( unsigned i = 0; i < minsize; i ++ ) { if ( rng.flip( rate ) ) { - bool changedHere = op( _eo1[i], _eo2[i] ); - changed |= changedHere; + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; } } - return changed; // should we test that? Yes, but no time now + return changed; // should we test that? Yes, but no time now } virtual std::string className() const @@ -237,34 +237,34 @@ public : unsigned index=0; do { for (i=0; i<_eo1.size(); i++) - { - if (eo::rng.flip(rate)) - tmp1.push_back(_eo1[i]); - else - tmp2.push_back(_eo1[i]); - // here we should look for _eo1[i] inside _eo2 and erase it if found! - } + { + if (eo::rng.flip(rate)) + tmp1.push_back(_eo1[i]); + else + tmp2.push_back(_eo1[i]); + // here we should look for _eo1[i] inside _eo2 and erase it if found! + } for (i=0; i<_eo2.size(); i++) - { - if (eo::rng.flip(rate)) - tmp1.push_back(_eo2[i]); - else - tmp2.push_back(_eo2[i]); - } + { + if (eo::rng.flip(rate)) + tmp1.push_back(_eo2[i]); + else + tmp2.push_back(_eo2[i]); + } index++; } while ( ( (tmp1.size()Max) || (tmp2.size()>Max) ) - && (index<10000) ); + (tmp1.size()>Max) || (tmp2.size()>Max) ) + && (index<10000) ); //! @todo FIXME bad hardcoded limit, should use an algorithm that guarantee a correct size in a finite number of tries if (index >= 10000) { eo::log << eo::warnings << "Warning: impossible to generate individual of the right size in 10000 trials" << std::endl; - return false; + return false; } _eo1.swap(tmp1); _eo2.swap(tmp2); - return true; // should we test that? + return true; // should we test that? } private: unsigned Min, Max; @@ -300,47 +300,47 @@ public : unsigned index=0; do { for (i=0; i<_eo1.size(); i++) - { - if (eo::rng.flip(rate)) - { - tmp1.push_back(_eo1[i]); - tmpIsTwo = false; - } - else - tmpIsOne=false; - // we should look for _eo1[i] inside _eo2 and erase it there if found! - } + { + if (eo::rng.flip(rate)) + { + tmp1.push_back(_eo1[i]); + tmpIsTwo = false; + } + else + tmpIsOne=false; + // we should look for _eo1[i] inside _eo2 and erase it there if found! + } for (i=0; i<_eo2.size(); i++) - { - if (! eo::rng.flip(rate)) - { - tmp1.push_back(_eo2[i]); - tmpIsOne = false; - } - else - tmpIsTwo = false; - } + { + if (! eo::rng.flip(rate)) + { + tmp1.push_back(_eo2[i]); + tmpIsOne = false; + } + else + tmpIsTwo = false; + } index++; } while ( ( (tmp1.size()Max) ) - && (index<10000) ); + && (index<10000) ); // this while condition is not optimal, as it may take some time, see the FIXME above if (index >= 10000) { eo::log << eo::warnings << "Warning: impossible to generate individual of the right size in 10000 trials" << std::endl; - return false; + return false; } _eo1.swap(tmp1); if (tmpIsTwo) { - // _eo1.fitness(_eo2.fitness()); NO FITNESS EXISTS HERE! - return false; + // _eo1.fitness(_eo2.fitness()); NO FITNESS EXISTS HERE! + return false; } - if (tmpIsOne) // already has the right fitness - { // WRONG: NO FITNESS EXISTS HERE! - return false; + if (tmpIsOne) // already has the right fitness + { // WRONG: NO FITNESS EXISTS HERE! + return false; } - return true; // there were some modifications... + return true; // there were some modifications... } private: @@ -350,4 +350,3 @@ private: /** @} */ #endif - diff --git a/eo/src/eoVariableLengthMutation.h b/eo/src/eoVariableLengthMutation.h index aad778ba..542541d7 100644 --- a/eo/src/eoVariableLengthMutation.h +++ b/eo/src/eoVariableLengthMutation.h @@ -66,7 +66,7 @@ public : bool operator()(EOT & _eo) { if (_eo.size() >= nMax) - return false; // unmodifed + return false; // unmodifed AtomType atom; atomInit(atom); unsigned pos = rng.random(_eo.size()+1); @@ -100,7 +100,7 @@ public: eoUniformGeneChooser(){} unsigned operator()(EOT & _eo) { - return eo::rng.random(_eo.size()); + return eo::rng.random(_eo.size()); } virtual std::string className() const { return "eoUniformGeneChooser"; } }; @@ -137,7 +137,7 @@ public : bool operator()(EOT & _eo) { if (_eo.size() <= nMin) - return false; // unmodifed + return false; // unmodifed unsigned pos = chooser(_eo); _eo.erase(_eo.begin()+pos); return true; @@ -158,4 +158,3 @@ private: /** @} */ #endif - diff --git a/eo/src/eoVector.h b/eo/src/eoVector.h index 0e1b6d91..fce05d11 100644 --- a/eo/src/eoVector.h +++ b/eo/src/eoVector.h @@ -82,9 +82,9 @@ public: // with the copy Ctor void value(const std::vector& _v) { - if (_v.size() != size()) // safety check + if (_v.size() != size()) // safety check { - if (size()) // NOT an initial empty std::vector + if (size()) // NOT an initial empty std::vector eo::log << eo::warnings << "Warning: Changing size in eoVector assignation" << std::endl; resize(_v.size()); } diff --git a/eo/src/eoVectorParticle.h b/eo/src/eoVectorParticle.h index 4736639a..25cfcc9f 100644 --- a/eo/src/eoVectorParticle.h +++ b/eo/src/eoVectorParticle.h @@ -124,14 +124,14 @@ public: { velocities.resize (_size); } - + /// to avoid conflicts between EA and PSO bool operator<(const eoVectorParticle& _eo) const { - if (_eo.best() > this->best()) - return true; - else - return false; + if (_eo.best() > this->best()) + return true; + else + return false; } /** @@ -139,10 +139,10 @@ public: */ virtual void printOn(std::ostream& os) const { - PO::printOn(os); - os << ' '; - os << size() << ' '; - std::copy(bestPositions.begin(), bestPositions.end(), std::ostream_iterator(os, " ")); + PO::printOn(os); + os << ' '; + os << size() << ' '; + std::copy(bestPositions.begin(), bestPositions.end(), std::ostream_iterator(os, " ")); } /* public attributes */ diff --git a/eo/src/eoVelocity.h b/eo/src/eoVelocity.h index 5d4bdcd2..753c6af2 100644 --- a/eo/src/eoVelocity.h +++ b/eo/src/eoVelocity.h @@ -71,11 +71,10 @@ public: } } - - + + virtual eoTopology & getTopology () = 0; }; #endif /*EOVELOCITY_H_H */ - diff --git a/eo/src/eoVelocityInit.h b/eo/src/eoVelocityInit.h index 4a096f4c..8c57a689 100644 --- a/eo/src/eoVelocityInit.h +++ b/eo/src/eoVelocityInit.h @@ -64,7 +64,7 @@ public: init (p); return (p); } - + private: eoVelocityInit < POT > &init; }; @@ -144,4 +144,3 @@ private: #endif /*EOVELOCITYINIT_H */ /** @} */ - diff --git a/eo/src/eoWeightUpdater.h b/eo/src/eoWeightUpdater.h index 65619016..d4970eca 100644 --- a/eo/src/eoWeightUpdater.h +++ b/eo/src/eoWeightUpdater.h @@ -30,7 +30,7 @@ //----------------------------------------------------------------------------- /** - * Abstract class for (inertia) weight updater (particle swarm optimization). + * Abstract class for (inertia) weight updater (particle swarm optimization). * Used inside classes extending eoVelocity. * * @ingroup Core diff --git a/eo/src/es.h b/eo/src/es.h index 17545f3e..d5dffc2f 100644 --- a/eo/src/es.h +++ b/eo/src/es.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // es.h // (c) GeNeura Team 1998 - Maarten Keijzer 2000 - 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 @@ -20,21 +20,21 @@ Contact: Marc.Schoenauer@polytechnique.fr mak@dhi.dk - todos@geneura.ugr.es, http://geneura.ugr.es + todos@geneura.ugr.es, http://geneura.ugr.es */ //----------------------------------------------------------------------------- #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #ifndef _es_h #define _es_h // contains the include specific to real representations, i.e. in src/es dir //----------------------------------------------------------------------------- - + // the genotypes - from plain std::vector to full correlated mutation #include #include diff --git a/eo/src/es/CMAParams.cpp b/eo/src/es/CMAParams.cpp index 1ded097d..131edb72 100644 --- a/eo/src/es/CMAParams.cpp +++ b/eo/src/es/CMAParams.cpp @@ -1,4 +1,3 @@ - /* * C++ification of Nikolaus Hansen's original C-source code for the * CMA-ES @@ -7,7 +6,7 @@ * the LGPL. Original copyright of Nikolaus Hansen can be found below * * - * + * */ /* --------------------------------------------------------- */ @@ -30,7 +29,7 @@ * 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. - * + * * */ /* --- Changes : --- * 03/03/21: argument const double *rgFunVal of @@ -54,138 +53,138 @@ using namespace std; namespace eo { CMAParams::CMAParams(eoParser& parser, unsigned dimensionality) { - + string section = "CMA parameters"; - + n = parser.createParam(dimensionality, "dimensionality", "Dimensionality (N) of the problem", 'N', section, dimensionality == 0).value(); - + maxgen = parser.createParam( - 1000, - "max-gen", - "Maximum number of generations that the system will run (needed for damping)", - 'M', - section).value(); - - + 1000, + "max-gen", + "Maximum number of generations that the system will run (needed for damping)", + 'M', + section).value(); + + if (n == 0) { - return; + return; } - + defaults(n, maxgen); - + /* handle lambda */ lambda = parser.createParam( - lambda, - "lambda", - "Number of offspring", - 'l', - section).value(); + lambda, + "lambda", + "Number of offspring", + 'l', + section).value(); if (lambda < 2) { - lambda = 4+(int)(3*log((double) n)); - cerr << "Too small lambda specified, setting it to " << lambda << endl; + lambda = 4+(int)(3*log((double) n)); + cerr << "Too small lambda specified, setting it to " << lambda << endl; } - + /* handle mu */ mu = parser.createParam( - mu, - "mu", - "Population size", - 'm', - section).value(); + mu, + "mu", + "Population size", + 'm', + section).value(); if (mu >= lambda) { - mu = lambda/2; - cerr << "Mu set larger/equal to lambda, setting it to " << mu << endl; + mu = lambda/2; + cerr << "Mu set larger/equal to lambda, setting it to " << mu << endl; } - + /* handle selection weights */ - + int weight_type = parser.createParam( - 0, - "weighting", - "Weighting scheme (for 'selection'): 0 = logarithmic, 1 = equal, 2 = linear", - 'w', - section).value(); + 0, + "weighting", + "Weighting scheme (for 'selection'): 0 = logarithmic, 1 = equal, 2 = linear", + 'w', + section).value(); switch (weight_type) { - case 1: - { - for (unsigned i = 0; i < weights.size(); ++i) { - weights[i] = mu - i; - } - } - case 2: - { - weights = 1.; - } - default : - { - for (unsigned i = 0; i < weights.size(); ++i) { - weights[i] = log(mu+1.)-log(i+1.); - } - } - + case 1: + { + for (unsigned i = 0; i < weights.size(); ++i) { + weights[i] = mu - i; + } + } + case 2: + { + weights = 1.; + } + default : + { + for (unsigned i = 0; i < weights.size(); ++i) { + weights[i] = log(mu+1.)-log(i+1.); + } + } + } /* Normalize weights and set mu_eff */ double sumw = weights.sum(); mueff = sumw * sumw / (weights * weights).sum(); weights /= sumw; - + /* most of the rest depends on mu_eff, so needs to be set again */ - + /* set the others using Nikolaus logic. If you want to tweak, you can parameterize over these defaults */ mucov = mueff; ccumsig = (mueff + 2.) / (n + mueff + 3.); ccumcov = 4. / (n + 4); - + double t1 = 2. / ((n+1.4142)*(n+1.4142)); double t2 = (2.*mucov-1.) / ((n+2.)*(n+2.)+mucov); t2 = (t2 > 1) ? 1 : t2; t2 = (1./mucov) * t1 + (1.-1./mucov) * t2; - + ccov = t2; damp = 1 + std::max(0.3,(1.-(double)n/(double)maxgen)) - * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ - / ccumsig; - + * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ + / ccumsig; + vector mins(1,0.0); mins = parser.createParam( - mins, - "min-stdev", - "Array of minimum stdevs, last one will apply for all remaining axes", - 0, - section).value(); - + mins, + "min-stdev", + "Array of minimum stdevs, last one will apply for all remaining axes", + 0, + section).value(); + if (mins.size() > n) mins.resize(n); if (mins.size()) { - minStdevs = mins.back(); - for (unsigned i = 0; i < mins.size(); ++i) { - minStdevs[i] = mins[i]; - } + minStdevs = mins.back(); + for (unsigned i = 0; i < mins.size(); ++i) { + minStdevs[i] = mins[i]; + } } - + vector inits(1,0.3); inits = parser.createParam( - inits, - "init-stdev", - "Array of initial stdevs, last one will apply for all remaining axes", - 0, - section).value(); - + inits, + "init-stdev", + "Array of initial stdevs, last one will apply for all remaining axes", + 0, + section).value(); + if (inits.size() > n) inits.resize(n); if (inits.size()) { - initialStdevs = inits.back(); - for (unsigned i = 0; i < inits.size(); ++i) { - initialStdevs[i] = inits[i]; - } + initialStdevs = inits.back(); + for (unsigned i = 0; i < inits.size(); ++i) { + initialStdevs[i] = inits[i]; + } } - + } void CMAParams::defaults(unsigned n_, unsigned maxgen_) { @@ -194,39 +193,39 @@ void CMAParams::defaults(unsigned n_, unsigned maxgen_) { lambda = 4+(int)(3*log((double) n)); mu = lambda / 2; - + weights.resize(mu); - + for (unsigned i = 0; i < weights.size(); ++i) { - weights[i] = log(mu+1.)-log(i+1.); + weights[i] = log(mu+1.)-log(i+1.); } - + /* Normalize weights and set mu_eff */ double sumw = weights.sum(); mueff = sumw * sumw / (weights * weights).sum(); weights /= sumw; - + mucov = mueff; ccumsig *= (mueff + 2.) / (n + mueff + 3.); ccumcov = 4. / (n + 4); - + double t1 = 2. / ((n+1.4142)*(n+1.4142)); double t2 = (2.*mucov-1.) / ((n+2.)*(n+2.)+mucov); t2 = (t2 > 1) ? 1 : t2; t2 = (1./mucov) * t1 + (1.-1./mucov) * t2; - + ccov = t2; damp = 1 + std::max(0.3,(1.-(double)n/maxgen)) - * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ - / ccumsig; + * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ + / ccumsig; minStdevs.resize(n); minStdevs = 0.0; - + initialStdevs.resize(n); initialStdevs = 0.3; - + } diff --git a/eo/src/es/CMAParams.h b/eo/src/es/CMAParams.h index f59d6c92..90586904 100644 --- a/eo/src/es/CMAParams.h +++ b/eo/src/es/CMAParams.h @@ -1,12 +1,12 @@ /* * C++ification of Nikolaus Hansen's original C-source code for the - * CMA-ES. + * CMA-ES. * * Copyright (C) 1996, 2003, Nikolaus Hansen - * (C) 2005, Maarten Keijzer + * (C) 2005, Maarten Keijzer + * + * License: LGPL * - * License: LGPL - * */ #ifndef CMAPARAMS_H__ @@ -18,25 +18,25 @@ class eoParser; namespace eo { class CMAParams { - + public: - + CMAParams() { /* Call this and all values need to be set by hand */ } CMAParams(eoParser& parser, unsigned dimensionality = 0); // 0 dimensionality -> user needs to set it - + void defaults(unsigned n_, unsigned maxgen_); /* apply all defaults using n and maxgen */ - + unsigned n; unsigned maxgen; - + unsigned lambda; /* -> mu */ unsigned mu; /* -> weights, lambda */ - + std::valarray weights; /* <- mu, -> mueff -> mucov -> ccov */ double mueff; /* <- weights */ - + double mucov; - + double damp; /* <- ccumsig, maxeval, lambda */ double ccumsig; /* -> damp, <- N */ double ccumcov; @@ -49,4 +49,3 @@ class CMAParams { } // namespace eo #endif - diff --git a/eo/src/es/CMAState.cpp b/eo/src/es/CMAState.cpp index f44fdf5d..32855243 100644 --- a/eo/src/es/CMAState.cpp +++ b/eo/src/es/CMAState.cpp @@ -10,11 +10,11 @@ * algorithm: * * - Numerical issues are now treated 'before' going into the eigenvector decomposition - * (this was done out of convenience) + * (this was done out of convenience) * - dMaxSignifiKond (smallest x such that x == x + 1.0) replaced by - * numeric_limits::epsilon() (smallest x such that 1.0 != 1.0 + x) - * - * + * numeric_limits::epsilon() (smallest x such that 1.0 != 1.0 + x) + * + * */ /* --------------------------------------------------------- */ @@ -37,7 +37,7 @@ * 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. - * + * * */ /* --- Changes : --- * 03/03/21: argument const double *rgFunVal of @@ -66,289 +66,289 @@ using namespace std; namespace eo { - + struct CMAStateImpl { - + CMAParams p; - + lower_triangular_matrix C; // Covariance matrix square_matrix B; // Eigen vectors (in columns) valarray d; // eigen values (diagonal matrix) valarray pc; // Evolution path valarray ps; // Evolution path for stepsize; - + vector mean; // current mean to sample around double sigma; // global step size - + unsigned gen; vector fitnessHistory; - - + + CMAStateImpl(const CMAParams& params_, const vector& m, double sigma_) : - p(params_), - C(p.n), B(p.n), d(p.n), pc(p.n), ps(p.n), mean(m), sigma(sigma_), - gen(0), fitnessHistory(3) + p(params_), + C(p.n), B(p.n), d(p.n), pc(p.n), ps(p.n), mean(m), sigma(sigma_), + gen(0), fitnessHistory(3) { - double trace = (p.initialStdevs * p.initialStdevs).sum(); - /* Initialize covariance structure */ - for (unsigned i = 0; i < p.n; ++i) - { - B[i][i] = 1.; - d[i] = p.initialStdevs[i] * sqrt(p.n / trace); - C[i][i] = d[i] * d[i]; - pc[i] = 0.; - ps[i] = 0.; - } - + double trace = (p.initialStdevs * p.initialStdevs).sum(); + /* Initialize covariance structure */ + for (unsigned i = 0; i < p.n; ++i) + { + B[i][i] = 1.; + d[i] = p.initialStdevs[i] * sqrt(p.n / trace); + C[i][i] = d[i] * d[i]; + pc[i] = 0.; + ps[i] = 0.; + } + } void sample(vector& v) { - unsigned n = p.n; - v.resize(n); - - vector tmp(n); - for (unsigned i = 0; i < n; ++i) - tmp[i] = d[i] * rng.normal(); - - /* add mutation (sigma * B * (D*z)) */ - for (unsigned i = 0; i < n; ++i) { - double sum = 0; - for (unsigned j = 0; j < n; ++j) { - sum += B[i][j] * tmp[j]; - } - v[i] = mean[i] + sigma * sum; - } + unsigned n = p.n; + v.resize(n); + + vector tmp(n); + for (unsigned i = 0; i < n; ++i) + tmp[i] = d[i] * rng.normal(); + + /* add mutation (sigma * B * (D*z)) */ + for (unsigned i = 0; i < n; ++i) { + double sum = 0; + for (unsigned j = 0; j < n; ++j) { + sum += B[i][j] * tmp[j]; + } + v[i] = mean[i] + sigma * sum; + } } - + void reestimate(const vector* >& pop, double muBest, double muWorst) { - - assert(pop.size() == p.mu); - - unsigned n = p.n; - fitnessHistory[gen % fitnessHistory.size()] = muBest; // needed for divergence check - - vector oldmean = mean; - valarray BDz(n); - - /* calculate xmean and rgBDz~N(0,C) */ - for (unsigned i = 0; i < n; ++i) { - mean[i] = 0.; - for (unsigned j = 0; j < pop.size(); ++j) { - mean[i] += p.weights[j] * (*pop[j])[i]; - } - BDz[i] = sqrt(p.mueff)*(mean[i] - oldmean[i])/sigma; - } + assert(pop.size() == p.mu); - vector tmp(n); - /* calculate z := D^(-1) * B^(-1) * rgBDz into rgdTmp */ - for (unsigned i = 0; i < n; ++i) { - double sum = 0.0; - for (unsigned j = 0; j < n; ++j) { - sum += B[j][i] * BDz[j]; - } - tmp[i] = sum / d[i]; - } + unsigned n = p.n; - /* cumulation for sigma (ps) using B*z */ - for (unsigned i = 0; i < n; ++i) { - double sum = 0.0; - for (unsigned j = 0; j < n; ++j) - sum += B[i][j] * tmp[j]; - - ps[i] = (1. - p.ccumsig) * ps[i] + sqrt(p.ccumsig * (2. - p.ccumsig)) * sum; - } + fitnessHistory[gen % fitnessHistory.size()] = muBest; // needed for divergence check - /* calculate norm(ps)^2 */ - double psxps = (ps * ps).sum(); + vector oldmean = mean; + valarray BDz(n); - - double chiN = sqrt((double) p.n) * (1. - 1./(4.*p.n) + 1./(21.*p.n*p.n)); - /* cumulation for covariance matrix (pc) using B*D*z~N(0,C) */ - double hsig = sqrt(psxps) / sqrt(1. - pow(1.-p.ccumsig, 2.*gen)) / chiN < 1.5 + 1./(p.n-0.5); - - pc = (1. - p.ccumcov) * pc + hsig * sqrt(p.ccumcov * (2. - p.ccumcov)) * BDz; - - /* stop initial phase (MK, this was not reachable in the org code, deleted) */ + /* calculate xmean and rgBDz~N(0,C) */ + for (unsigned i = 0; i < n; ++i) { + mean[i] = 0.; + for (unsigned j = 0; j < pop.size(); ++j) { + mean[i] += p.weights[j] * (*pop[j])[i]; + } + BDz[i] = sqrt(p.mueff)*(mean[i] - oldmean[i])/sigma; + } - /* remove momentum in ps, if ps is large and fitness is getting worse */ + vector tmp(n); + /* calculate z := D^(-1) * B^(-1) * rgBDz into rgdTmp */ + for (unsigned i = 0; i < n; ++i) { + double sum = 0.0; + for (unsigned j = 0; j < n; ++j) { + sum += B[j][i] * BDz[j]; + } + tmp[i] = sum / d[i]; + } - if (gen >= fitnessHistory.size()) { + /* cumulation for sigma (ps) using B*z */ + for (unsigned i = 0; i < n; ++i) { + double sum = 0.0; + for (unsigned j = 0; j < n; ++j) + sum += B[i][j] * tmp[j]; - // find direction from muBest and muWorst (muBest == muWorst handled seperately - double direction = muBest < muWorst? -1.0 : 1.0; - - unsigned now = gen % fitnessHistory.size(); - unsigned prev = (gen-1) % fitnessHistory.size(); - unsigned prevprev = (gen-2) % fitnessHistory.size(); + ps[i] = (1. - p.ccumsig) * ps[i] + sqrt(p.ccumsig * (2. - p.ccumsig)) * sum; + } - bool fitnessWorsens = (muBest == muWorst) || // <- increase norm also when population has converged (this deviates from Hansen's scheme) - ( (direction * fitnessHistory[now] < direction * fitnessHistory[prev]) - && - (direction * fitnessHistory[now] < direction * fitnessHistory[prevprev])); - - if(psxps/p.n > 1.5 + 10.*sqrt(2./p.n) && fitnessWorsens) { - double tfac = sqrt((1 + std::max(0., log(psxps/p.n))) * p.n / psxps); - ps *= tfac; - psxps *= tfac*tfac; - } - } + /* calculate norm(ps)^2 */ + double psxps = (ps * ps).sum(); - /* update of C */ - /* Adapt_C(t); not used anymore */ - if (p.ccov != 0.) { - //flgEigensysIsUptodate = 0; - /* update covariance matrix */ - for (unsigned i = 0; i < n; ++i) { - vector::iterator c_row = C[i]; - for (unsigned j = 0; j <= i; ++j) { - c_row[j] = - (1 - p.ccov) * c_row[j] - + - p.ccov * (1./p.mucov) * pc[i] * pc[j] - + - (1-hsig) * p.ccumcov * (2. - p.ccumcov) * c_row[j]; - - /*C[i][j] = (1 - p.ccov) * C[i][j] - + sp.ccov * (1./sp.mucov) - * (rgpc[i] * rgpc[j] - + (1-hsig)*sp.ccumcov*(2.-sp.ccumcov) * C[i][j]); */ - for (unsigned k = 0; k < p.mu; ++k) { /* additional rank mu update */ - c_row[j] += p.ccov * (1-1./p.mucov) * p.weights[k] - * ( (*pop[k])[i] - oldmean[i]) - * ( (*pop[k])[j] - oldmean[j]) - / sigma / sigma; - - // * (rgrgx[index[k]][i] - rgxold[i]) - // * (rgrgx[index[k]][j] - rgxold[j]) - // / sigma / sigma; - } - } - } - } + double chiN = sqrt((double) p.n) * (1. - 1./(4.*p.n) + 1./(21.*p.n*p.n)); + /* cumulation for covariance matrix (pc) using B*D*z~N(0,C) */ + double hsig = sqrt(psxps) / sqrt(1. - pow(1.-p.ccumsig, 2.*gen)) / chiN < 1.5 + 1./(p.n-0.5); - /* update of sigma */ - sigma *= exp(((sqrt(psxps)/chiN)-1.)/p.damp); - /* calculate eigensystem, must be done by caller */ - //cmaes_UpdateEigensystem(0); + pc = (1. - p.ccumcov) * pc + hsig * sqrt(p.ccumcov * (2. - p.ccumcov)) * BDz; - - /* treat minimal standard deviations and numeric problems - * Note that in contrast with the original code, some numerical issues are treated *before* we - * go into the eigenvalue calculation */ - - treatNumericalIssues(muBest, muWorst); + /* stop initial phase (MK, this was not reachable in the org code, deleted) */ - gen++; // increase generation + /* remove momentum in ps, if ps is large and fitness is getting worse */ + + if (gen >= fitnessHistory.size()) { + + // find direction from muBest and muWorst (muBest == muWorst handled seperately + double direction = muBest < muWorst? -1.0 : 1.0; + + unsigned now = gen % fitnessHistory.size(); + unsigned prev = (gen-1) % fitnessHistory.size(); + unsigned prevprev = (gen-2) % fitnessHistory.size(); + + bool fitnessWorsens = (muBest == muWorst) || // <- increase norm also when population has converged (this deviates from Hansen's scheme) + ( (direction * fitnessHistory[now] < direction * fitnessHistory[prev]) + && + (direction * fitnessHistory[now] < direction * fitnessHistory[prevprev])); + + if(psxps/p.n > 1.5 + 10.*sqrt(2./p.n) && fitnessWorsens) { + double tfac = sqrt((1 + std::max(0., log(psxps/p.n))) * p.n / psxps); + ps *= tfac; + psxps *= tfac*tfac; + } + } + + /* update of C */ + /* Adapt_C(t); not used anymore */ + if (p.ccov != 0.) { + //flgEigensysIsUptodate = 0; + + /* update covariance matrix */ + for (unsigned i = 0; i < n; ++i) { + vector::iterator c_row = C[i]; + for (unsigned j = 0; j <= i; ++j) { + c_row[j] = + (1 - p.ccov) * c_row[j] + + + p.ccov * (1./p.mucov) * pc[i] * pc[j] + + + (1-hsig) * p.ccumcov * (2. - p.ccumcov) * c_row[j]; + + /*C[i][j] = (1 - p.ccov) * C[i][j] + + sp.ccov * (1./sp.mucov) + * (rgpc[i] * rgpc[j] + + (1-hsig)*sp.ccumcov*(2.-sp.ccumcov) * C[i][j]); */ + for (unsigned k = 0; k < p.mu; ++k) { /* additional rank mu update */ + c_row[j] += p.ccov * (1-1./p.mucov) * p.weights[k] + * ( (*pop[k])[i] - oldmean[i]) + * ( (*pop[k])[j] - oldmean[j]) + / sigma / sigma; + + // * (rgrgx[index[k]][i] - rgxold[i]) + // * (rgrgx[index[k]][j] - rgxold[j]) + // / sigma / sigma; + } + } + } + } + + /* update of sigma */ + sigma *= exp(((sqrt(psxps)/chiN)-1.)/p.damp); + /* calculate eigensystem, must be done by caller */ + //cmaes_UpdateEigensystem(0); + + + /* treat minimal standard deviations and numeric problems + * Note that in contrast with the original code, some numerical issues are treated *before* we + * go into the eigenvalue calculation */ + + treatNumericalIssues(muBest, muWorst); + + gen++; // increase generation } void treatNumericalIssues(double best, double worst) { - - /* treat stdevs */ - for (unsigned i = 0; i < p.n; ++i) { - if (sigma * sqrt(C[i][i]) < p.minStdevs[i]) { - // increase stdev - sigma *= exp(0.05+1./p.damp); - break; - } - } - - /* treat convergence */ - if (best == worst) { - sigma *= exp(0.2 + 1./p.damp); - } - - /* Jede Hauptachse i testen, ob x == x + 0.1 * sigma * rgD[i] * B[i] */ - /* Test if all the means are not numerically out of whack with our coordinate system*/ - for (unsigned axis = 0; axis < p.n; ++axis) { - double fac = 0.1 * sigma * d[axis]; - unsigned coord; - for (coord = 0; coord < p.n; ++coord) { - if (mean[coord] != mean[coord] + fac * B[coord][axis]) { - break; - } - } - if (coord == p.n) { // means are way too big (little) for numerical accuraccy. Start rocking the craddle a bit more - sigma *= exp(0.2+1./p.damp); - } - - } - - /* Testen ob eine Komponente des Objektparameters festhaengt */ - /* Correct issues with scale between objective values and covariances */ - bool theresAnIssue = false; + /* treat stdevs */ + for (unsigned i = 0; i < p.n; ++i) { + if (sigma * sqrt(C[i][i]) < p.minStdevs[i]) { + // increase stdev + sigma *= exp(0.05+1./p.damp); + break; + } + } - for (unsigned i = 0; i < p.n; ++i) { - if (mean[i] == mean[i] + 0.2 * sigma * sqrt(C[i][i])) { - C[i][i] *= (1. + p.ccov); - theresAnIssue = true; - } - } + /* treat convergence */ + if (best == worst) { + sigma *= exp(0.2 + 1./p.damp); + } - if (theresAnIssue) { - sigma *= exp(0.05 + 1./p.damp); - } + /* Jede Hauptachse i testen, ob x == x + 0.1 * sigma * rgD[i] * B[i] */ + /* Test if all the means are not numerically out of whack with our coordinate system*/ + for (unsigned axis = 0; axis < p.n; ++axis) { + double fac = 0.1 * sigma * d[axis]; + unsigned coord; + for (coord = 0; coord < p.n; ++coord) { + if (mean[coord] != mean[coord] + fac * B[coord][axis]) { + break; + } + } + + if (coord == p.n) { // means are way too big (little) for numerical accuraccy. Start rocking the craddle a bit more + sigma *= exp(0.2+1./p.damp); + } + + } + + /* Testen ob eine Komponente des Objektparameters festhaengt */ + /* Correct issues with scale between objective values and covariances */ + bool theresAnIssue = false; + + for (unsigned i = 0; i < p.n; ++i) { + if (mean[i] == mean[i] + 0.2 * sigma * sqrt(C[i][i])) { + C[i][i] *= (1. + p.ccov); + theresAnIssue = true; + } + } + + if (theresAnIssue) { + sigma *= exp(0.05 + 1./p.damp); + } } - + bool updateEigenSystem(unsigned max_tries, unsigned max_iters) { - if (max_iters==0) max_iters = 30 * p.n; - - static double lastGoodMinimumEigenValue = 1.0; - - /* Try to get a valid calculation */ - for (unsigned tries = 0; tries < max_tries; ++tries) { - - unsigned iters = eig( p.n, C, d, B, max_iters); - if (iters < max_iters) - { // all is well - - /* find largest/smallest eigenvalues */ - double minEV = d.min(); - double maxEV = d.max(); + if (max_iters==0) max_iters = 30 * p.n; - /* (MK Original comment was) :Limit Condition of C to dMaxSignifKond+1 - * replaced dMaxSignifKond with 1./numeric_limits::epsilon() - * */ - if (maxEV * numeric_limits::epsilon() > minEV) { - double tmp = maxEV * numeric_limits::epsilon() - minEV; - minEV += tmp; - for (unsigned i=0;i::epsilon() + * */ + if (maxEV * numeric_limits::epsilon() > minEV) { + double tmp = maxEV * numeric_limits::epsilon() - minEV; + minEV += tmp; + for (unsigned i=0;i& initial_point, const double initial_sigma) +CMAState::CMAState(const CMAParams& params, const std::vector& initial_point, const double initial_sigma) : pimpl(new CMAStateImpl(params, initial_point, initial_sigma)) {} CMAState::~CMAState() { delete pimpl; } @@ -362,4 +362,3 @@ bool CMAState::updateEigenSystem(unsigned max_tries, unsigned max_iters) { retur } // namespace eo - diff --git a/eo/src/es/CMAState.h b/eo/src/es/CMAState.h index 505a31b7..85a80c52 100644 --- a/eo/src/es/CMAState.h +++ b/eo/src/es/CMAState.h @@ -1,13 +1,12 @@ - /* * C++ification of Nikolaus Hansen's original C-source code for the - * CMA-ES. + * CMA-ES. * * Copyright (C) 1996, 2003, Nikolaus Hansen - * (C) 2005, Maarten Keijzer + * (C) 2005, Maarten Keijzer * * License: LGPL (see source file) - * + * */ #ifndef CMASTATE_H_ @@ -17,14 +16,14 @@ #include namespace eo { - + class CMAStateImpl; class CMAParams; class CMAState { - + CMAStateImpl* pimpl; /* pointer to implementation, hidden in source file */ - + public: CMAState(const CMAParams&, const std::vector& initial_point, const double initial_sigma = 1.0); @@ -35,34 +34,34 @@ class CMAState { /** * sample a vector from the distribution * - * If the sample is not to your liking (i.e., not within bounds) - * you can do one of two things: + * If the sample is not to your liking (i.e., not within bounds) + * you can do one of two things: * - * a) Call sample again - * b) multiply the entire vector with a number between -1 and 1 - * - * Do not modify the sample in any other way as this will invalidate the - * internal consistency of the system. + * a) Call sample again + * b) multiply the entire vector with a number between -1 and 1 * - * A final approach is to copy the sample and modify the copy externally (in the evaluation function) - * and possibly add a penalty depending on the size of the modification. + * Do not modify the sample in any other way as this will invalidate the + * internal consistency of the system. + * + * A final approach is to copy the sample and modify the copy externally (in the evaluation function) + * and possibly add a penalty depending on the size of the modification. * */ void sample(std::vector& v) const; - + /** * Reestimate covariance matrix and other internal parameters * Does NOT update the eigen system (call that seperately) * * Needs a population of mu individuals, sorted on fitness, plus * - * muBest: the best fitness in the population + * muBest: the best fitness in the population * muWorst: the worst fitness in the population */ - + void reestimate(const std::vector* >& sorted_population, double muBest, double muWorst); - - /** + + /** * call this function after reestimate in order to update the eigen system * It is a seperate call to allow the user to periodically skip this expensive step * @@ -71,7 +70,7 @@ class CMAState { * If after max_tries still no numerically sound eigen system is constructed, * the function returns false */ - bool updateEigenSystem(unsigned max_tries = 1, unsigned max_iters = 0); + bool updateEigenSystem(unsigned max_tries = 1, unsigned max_iters = 0); }; } // namespace eo diff --git a/eo/src/es/eig.cpp b/eo/src/es/eig.cpp index 29998bcb..d7ddd41d 100644 --- a/eo/src/es/eig.cpp +++ b/eo/src/es/eig.cpp @@ -1,4 +1,3 @@ - /* * C++ification of Nikolaus Hansen's original C-source code for the * CMA-ES. These are the eigenvector calculations @@ -8,7 +7,7 @@ * * This algorithm is held almost completely intact. Some other datatypes are used, * but hardly any code has changed - * + * */ /* --------------------------------------------------------- */ @@ -31,7 +30,7 @@ * 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. - * + * * */ /* --- Changes : --- * 03/03/21: argument const double *rgFunVal of @@ -49,21 +48,21 @@ using namespace std; /* ========================================================= */ -/* +/* Householder Transformation einer symmetrischen Matrix auf tridiagonale Form. -> n : Dimension -> ma : symmetrische nxn-Matrix - <- ma : Transformationsmatrix (ist orthogonal): + <- ma : Transformationsmatrix (ist orthogonal): Tridiag.-Matrix == <-ma * ->ma * (<-ma)^t <- diag : Diagonale der resultierenden Tridiagonalmatrix <- neben[0..n-1] : Nebendiagonale (==1..n-1) der res. Tridiagonalmatrix */ -static void +static void Householder( int N, square_matrix& ma, valarray& diag, double* neben) { - double epsilon; + double epsilon; int i, j, k; double h, sum, tmp, tmp2; @@ -82,34 +81,34 @@ Householder( int N, square_matrix& ma, valarray& diag, double* neben) else { for(k = i-1, sum = 0.0; k >= 0; --k) - { /* i-te Zeile von i-1 bis links normieren */ + { /* i-te Zeile von i-1 bis links normieren */ ma[i][k] /= epsilon; - sum += ma[i][k]*ma[i][k]; - } - tmp = (ma[i][i-1] > 0) ? -sqrt(sum) : sqrt(sum); - neben[i] = epsilon*tmp; - h = sum - ma[i][i-1]*tmp; - ma[i][i-1] -= tmp; - for (j = 0, sum = 0.0; j < i; ++j) - { - ma[j][i] = ma[i][j]/h; - tmp = 0.0; - for (k = j; k >= 0; --k) - tmp += ma[j][k]*ma[i][k]; - for (k = j+1; k < i; ++k) - tmp += ma[k][j]*ma[i][k]; - neben[j] = tmp/h; - sum += neben[j] * ma[i][j]; - } /* for j */ - sum /= 2.*h; - for (j = 0; j < i; ++j) - { - neben[j] -= ma[i][j]*sum; - tmp = ma[i][j]; - tmp2 = neben[j]; - for (k = j; k >= 0; --k) - ma[j][k] -= (tmp*neben[k] + tmp2*ma[i][k]); - } /* for j */ + sum += ma[i][k]*ma[i][k]; + } + tmp = (ma[i][i-1] > 0) ? -sqrt(sum) : sqrt(sum); + neben[i] = epsilon*tmp; + h = sum - ma[i][i-1]*tmp; + ma[i][i-1] -= tmp; + for (j = 0, sum = 0.0; j < i; ++j) + { + ma[j][i] = ma[i][j]/h; + tmp = 0.0; + for (k = j; k >= 0; --k) + tmp += ma[j][k]*ma[i][k]; + for (k = j+1; k < i; ++k) + tmp += ma[k][j]*ma[i][k]; + neben[j] = tmp/h; + sum += neben[j] * ma[i][j]; + } /* for j */ + sum /= 2.*h; + for (j = 0; j < i; ++j) + { + neben[j] -= ma[i][j]*sum; + tmp = ma[i][j]; + tmp2 = neben[j]; + for (k = j; k >= 0; --k) + ma[j][k] -= (tmp*neben[k] + tmp2*ma[i][k]); + } /* for j */ } /* else epsilon */ } /* else i == 1 */ diag[i] = h; @@ -117,16 +116,16 @@ Householder( int N, square_matrix& ma, valarray& diag, double* neben) diag[0] = 0.0; neben[0] = 0.0; - + for (i = 0; i < N; ++i) { if(diag[i] != 0.0) for (j = 0; j < i; ++j) { - for (k = i-1, tmp = 0.0; k >= 0; --k) - tmp += ma[i][k] * ma[k][j]; + for (k = i-1, tmp = 0.0; k >= 0; --k) + tmp += ma[i][k] * ma[k][j]; for (k = i-1; k >= 0; --k) - ma[k][j] -= tmp*ma[k][i]; + ma[k][j] -= tmp*ma[k][i]; } /* for j */ diag[i] = ma[i][i]; ma[i][i] = 1.0; @@ -137,21 +136,21 @@ Householder( int N, square_matrix& ma, valarray& diag, double* neben) /* QL-Algorithmus mit implizitem Shift, zur Berechnung von Eigenwerten - und -vektoren einer symmetrischen Tridiagonalmatrix. - -> n : Dimension. - -> diag : Diagonale der Tridiagonalmatrix. + und -vektoren einer symmetrischen Tridiagonalmatrix. + -> n : Dimension. + -> diag : Diagonale der Tridiagonalmatrix. -> neben[0..n-1] : Nebendiagonale (==0..n-2), n-1. Eintrag beliebig - -> mq : Matrix output von Householder() - -> maxIt : maximale Zahl der Iterationen + -> mq : Matrix output von Householder() + -> maxIt : maximale Zahl der Iterationen <- diag : Eigenwerte <- neben : Garbage <- mq : k-te Spalte ist normalisierter Eigenvektor zu diag[k] */ -static int -QLalgo( int N, valarray& diag, square_matrix& mq, - int maxIter, double* neben) +static int +QLalgo( int N, valarray& diag, square_matrix& mq, + int maxIter, double* neben) { int i, j, k, kp1, l; double tmp, diff, cneben, c1, c2, p; @@ -163,77 +162,77 @@ QLalgo( int N, valarray& diag, square_matrix& mq, { for (j = i; j < N-1; ++j) { - tmp = fabs(diag[j]) + fabs(diag[j+1]); - if (fabs(neben[j]) + tmp == tmp) - break; + tmp = fabs(diag[j]) + fabs(diag[j+1]); + if (fabs(neben[j]) + tmp == tmp) + break; } if (j != i) { - if (++iter > maxIter) return maxIter-1; - diff = (diag[i+1]-diag[i])/neben[i]/2.0; - if (diff >= 0) - diff = diag[j] - diag[i] + - neben[i] / (diff + sqrt(diff * diff + 1.0)); - else - diff = diag[j] - diag[i] + - neben[i] / (diff - sqrt(diff * diff + 1.0)); - c2 = c1 = 1.0; - p = 0.0; - for (k = j-1; k >= i; --k) - { - kp1 = k + 1; - tmp = c2 * neben[k]; - cneben = c1 * neben[k]; - if (fabs(tmp) >= fabs(diff)) - { - c1 = diff / tmp; - c2 = 1. / sqrt(c1*c1 + 1.0); - neben[kp1] = tmp / c2; - c1 *= c2; - } - else - { - c2 = tmp / diff; - c1 = 1. / sqrt(c2*c2 + 1.0); - neben[kp1] = diff / c1; - c2 *= c1; - } /* else */ - tmp = (diag[k] - diag[kp1] + p) * c2 + 2.0 * c1 * cneben; - diag[kp1] += tmp * c2 - p; - p = tmp * c2; - diff = tmp * c1 - cneben; - for (l = N-1; l >= 0; --l) /* TF-Matrix Q */ - { - tmp = mq[l][kp1]; - mq[l][kp1] = c2 * mq[l][k] + c1 * tmp; - mq[l][k] = c1 * mq[l][k] - c2 * tmp; - } /* for l */ - } /* for k */ - diag[i] -= p; - neben[i] = diff; - neben[j] = 0.0; + if (++iter > maxIter) return maxIter-1; + diff = (diag[i+1]-diag[i])/neben[i]/2.0; + if (diff >= 0) + diff = diag[j] - diag[i] + + neben[i] / (diff + sqrt(diff * diff + 1.0)); + else + diff = diag[j] - diag[i] + + neben[i] / (diff - sqrt(diff * diff + 1.0)); + c2 = c1 = 1.0; + p = 0.0; + for (k = j-1; k >= i; --k) + { + kp1 = k + 1; + tmp = c2 * neben[k]; + cneben = c1 * neben[k]; + if (fabs(tmp) >= fabs(diff)) + { + c1 = diff / tmp; + c2 = 1. / sqrt(c1*c1 + 1.0); + neben[kp1] = tmp / c2; + c1 *= c2; + } + else + { + c2 = tmp / diff; + c1 = 1. / sqrt(c2*c2 + 1.0); + neben[kp1] = diff / c1; + c2 *= c1; + } /* else */ + tmp = (diag[k] - diag[kp1] + p) * c2 + 2.0 * c1 * cneben; + diag[kp1] += tmp * c2 - p; + p = tmp * c2; + diff = tmp * c1 - cneben; + for (l = N-1; l >= 0; --l) /* TF-Matrix Q */ + { + tmp = mq[l][kp1]; + mq[l][kp1] = c2 * mq[l][k] + c1 * tmp; + mq[l][k] = c1 * mq[l][k] - c2 * tmp; + } /* for l */ + } /* for k */ + diag[i] -= p; + neben[i] = diff; + neben[j] = 0.0; } /* if */ } while (j != i); return iter; } /* QLalgo() */ /* ========================================================= */ -/* - Calculating eigenvalues and vectors. - Input: +/* + Calculating eigenvalues and vectors. + Input: N: dimension. C: lower_triangular NxN-matrix. - niter: number of maximal iterations for QL-Algorithm. - rgtmp: N+1-dimensional vector for temporal use. - Output: + niter: number of maximal iterations for QL-Algorithm. + rgtmp: N+1-dimensional vector for temporal use. + Output: diag: N eigenvalues. Q: Columns are normalized eigenvectors. return: number of iterations in QL-Algorithm. */ namespace eo { -int -eig( int N, const lower_triangular_matrix& C, valarray& diag, square_matrix& Q, +int +eig( int N, const lower_triangular_matrix& C, valarray& diag, square_matrix& Q, int niter) { int ret; @@ -245,15 +244,15 @@ eig( int N, const lower_triangular_matrix& C, valarray& diag, square_ma { vector::const_iterator row = C[i]; for (j = 0; j <= i; ++j) - Q[i][j] = Q[j][i] = row[j]; + Q[i][j] = Q[j][i] = row[j]; } - + double* rgtmp = new double[N+1]; Householder( N, Q, diag, rgtmp); ret = QLalgo( N, diag, Q, niter, rgtmp+1); delete [] rgtmp; - + return ret; -} +} } // namespace eo diff --git a/eo/src/es/eig.h b/eo/src/es/eig.h index 02aa36e0..65d9c53d 100644 --- a/eo/src/es/eig.h +++ b/eo/src/es/eig.h @@ -6,18 +6,18 @@ namespace eo { /* ========================================================= */ -/* - Calculating eigenvalues and vectors. - Input: +/* + Calculating eigenvalues and vectors. + Input: N: dimension. C: lower_triangular NxN-matrix. - niter: number of maximal iterations for QL-Algorithm. - Output: + niter: number of maximal iterations for QL-Algorithm. + Output: diag: N eigenvalues. Q: Columns are normalized eigenvectors. return: number of iterations in QL-Algorithm. */ -extern int eig( int N, const lower_triangular_matrix& C, std::valarray& diag, square_matrix& Q, +extern int eig( int N, const lower_triangular_matrix& C, std::valarray& diag, square_matrix& Q, int niter = 0); } // namespace eo diff --git a/eo/src/es/eoCMABreed.h b/eo/src/es/eoCMABreed.h index d55ab261..450654a7 100644 --- a/eo/src/es/eoCMABreed.h +++ b/eo/src/es/eoCMABreed.h @@ -34,43 +34,43 @@ /// @todo handle bounds template class eoCMABreed : public eoBreed< eoVector > { - + eo::CMAState& state; unsigned lambda; - + typedef eoVector EOT; - + public: eoCMABreed(eo::CMAState& state_, unsigned lambda_) : state(state_), lambda(lambda_) {} - + void operator()(const eoPop& parents, eoPop& offspring) { - - // two temporary arrays of pointers to store the sorted population - std::vector sorted(parents.size()); - + + // two temporary arrays of pointers to store the sorted population + std::vector sorted(parents.size()); + // mu stores population as vector (instead of eoPop) std::vector* > mu(parents.size()); - - parents.sort(sorted); - for (unsigned i = 0; i < sorted.size(); ++i) { - mu[i] = static_cast< const std::vector* >( sorted[i] ); - } - - // learn - state.reestimate(mu, sorted[0]->fitness(), sorted.back()->fitness()); - - if (!state.updateEigenSystem(10)) { - std::cerr << "No good eigensystem found" << std::endl; - } - - // generate - offspring.resize(lambda); - for (unsigned i = 0; i < lambda; ++i) { - state.sample( static_cast< std::vector& >( offspring[i] )); - offspring[i].invalidate(); - } - + parents.sort(sorted); + for (unsigned i = 0; i < sorted.size(); ++i) { + mu[i] = static_cast< const std::vector* >( sorted[i] ); + } + + // learn + state.reestimate(mu, sorted[0]->fitness(), sorted.back()->fitness()); + + if (!state.updateEigenSystem(10)) { + std::cerr << "No good eigensystem found" << std::endl; + } + + // generate + offspring.resize(lambda); + + for (unsigned i = 0; i < lambda; ++i) { + state.sample( static_cast< std::vector& >( offspring[i] )); + offspring[i].invalidate(); + } + } }; diff --git a/eo/src/es/eoCMAInit.h b/eo/src/es/eoCMAInit.h index bce9e5ba..2fdb967e 100644 --- a/eo/src/es/eoCMAInit.h +++ b/eo/src/es/eoCMAInit.h @@ -1,7 +1,7 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; fill-column: 80; -*- //----------------------------------------------------------------------------- -// eoCMAInit +// eoCMAInit // (c) Maarten Keijzer 2005 /* This library is free software; you can redistribute it and/or @@ -35,18 +35,18 @@ /// @todo handle bounds template class eoCMAInit : public eoInit< eoVector > { - + const eo::CMAState& state; typedef eoVector EOT; - + public: eoCMAInit(const eo::CMAState& state_) : state(state_) {} - + void operator()(EOT& v) { - state.sample(static_cast& >(v)); - v.invalidate(); + state.sample(static_cast& >(v)); + v.invalidate(); } }; diff --git a/eo/src/es/eoEsGlobalXover.h b/eo/src/es/eoEsGlobalXover.h index bac4ae27..5be4b506 100644 --- a/eo/src/es/eoEsGlobalXover.h +++ b/eo/src/es/eoEsGlobalXover.h @@ -75,12 +75,12 @@ public: // first, the object variables for (unsigned i=0; i used by _plop to get parents - const EOT& realParent1 = sel(_plop.source()); - const EOT& realParent2 = sel(_plop.source()); - parent[i] = realParent1[i]; - crossObj(parent[i], realParent2[i]); // apply eoBinOp + // get extra parents - use private selector + // _plop.source() is the eoPop used by _plop to get parents + const EOT& realParent1 = sel(_plop.source()); + const EOT& realParent2 = sel(_plop.source()); + parent[i] = realParent1[i]; + crossObj(parent[i], realParent2[i]); // apply eoBinOp } // then the self-adaptation parameters cross_self_adapt(parent, _plop.source()); @@ -110,10 +110,10 @@ private: { for (unsigned i=0; i<_parent.size(); i++) { - const EOT& realParent1 = sel(_pop); - const EOT& realParent2 = sel(_pop); - _parent.stdevs[i] = realParent1.stdevs[i]; - crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.stdevs[i] = realParent1.stdevs[i]; + crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp } } @@ -127,18 +127,18 @@ private: // the StDev for (i=0; i<_parent.size(); i++) { - const EOT& realParent1 = sel(_pop); - const EOT& realParent2 = sel(_pop); - _parent.stdevs[i] = realParent1.stdevs[i]; - crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.stdevs[i] = realParent1.stdevs[i]; + crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp } // the roataion angles for (i=0; i<_parent.correlations.size(); i++) { - const EOT& realParent1 = sel(_pop); - const EOT& realParent2 = sel(_pop); - _parent.correlations[i] = realParent1.correlations[i]; - crossMut(_parent.correlations[i], realParent2.correlations[i]); // apply eoBinOp + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.correlations[i] = realParent1.correlations[i]; + crossMut(_parent.correlations[i], realParent2.correlations[i]); // apply eoBinOp } } diff --git a/eo/src/es/eoEsMutate.h b/eo/src/es/eoEsMutate.h index 6ae09ef2..fd115268 100644 --- a/eo/src/es/eoEsMutate.h +++ b/eo/src/es/eoEsMutate.h @@ -99,7 +99,7 @@ public: { _eo.stdev *= exp(TauLcl * rng.normal()); if (_eo.stdev < stdev_eps) - _eo.stdev = stdev_eps; + _eo.stdev = stdev_eps; // now apply to all for (unsigned i = 0; i < _eo.size(); ++i) { @@ -218,7 +218,7 @@ public: unsigned size = bounds.size(); TauLcl = _init.TauLcl(); TauLcl /= sqrt(2*(double) size); - std::cout << "Init: tau local " << TauLcl << std::endl; + std::cout << "Init: tau local " << TauLcl << std::endl; } diff --git a/eo/src/es/eoEsMutationInit.h b/eo/src/es/eoEsMutationInit.h index 6ee74c2a..987de86b 100644 --- a/eo/src/es/eoEsMutationInit.h +++ b/eo/src/es/eoEsMutationInit.h @@ -55,7 +55,7 @@ public : @param _section Parser section for \f$\tau\f$-parameters. */ eoEsMutationInit(eoParser& _parser, - std::string _section="ES mutation parameters" ) : + std::string _section="ES mutation parameters" ) : parser(_parser), repSection(_section), TauLclParam(0), TauGlbParam(0), TauBetaParam(0) {} diff --git a/eo/src/es/eoEsStandardXover.h b/eo/src/es/eoEsStandardXover.h index 56d59be8..34739693 100644 --- a/eo/src/es/eoEsStandardXover.h +++ b/eo/src/es/eoEsStandardXover.h @@ -1,4 +1,4 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- // eoEsLocalXover.h : ES global crossover @@ -8,16 +8,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ */ //----------------------------------------------------------------------------- @@ -45,7 +45,7 @@ * @ingroup Real * @ingroup Variators */ -template +template class eoEsStandardXover: public eoBinOp { public: @@ -70,13 +70,13 @@ public: // first, the object variables for (unsigned i=0; i<_eo1.size(); i++) { - bLoc |= crossObj(_eo1[i], _eo2[i]); // apply eoBinOp + bLoc |= crossObj(_eo1[i], _eo2[i]); // apply eoBinOp } // then the self-adaptation parameters bLoc |= cross_self_adapt(_eo1, _eo2); return bLoc; } - + private: // the method to cross slef-adaptation parameters: need to specialize @@ -91,7 +91,7 @@ private: bool bLoc=false; for (unsigned i=0; i<_parent1.size(); i++) { - bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp + bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp } return bLoc; } @@ -103,12 +103,12 @@ private: // the StDev for (i=0; i<_parent1.size(); i++) { - bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp + bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp } // the roataion angles for (i=0; i<_parent1.correlations.size(); i++) { - bLoc |= crossMut(_parent1.correlations[i], _parent2.correlations[i]); // apply eoBinOp + bLoc |= crossMut(_parent1.correlations[i], _parent2.correlations[i]); // apply eoBinOp } return bLoc; diff --git a/eo/src/es/eoNormalMutation.h b/eo/src/es/eoNormalMutation.h index 17447244..96dcf54c 100644 --- a/eo/src/es/eoNormalMutation.h +++ b/eo/src/es/eoNormalMutation.h @@ -69,13 +69,13 @@ template class eoNormalVecMutation: public eoMonOp * for each component, the sigma is scaled to the range of the bound, if bounded */ eoNormalVecMutation(eoRealVectorBounds & _bounds, - double _sigma, const double& _p_change = 1.0): + double _sigma, const double& _p_change = 1.0): sigma(_bounds.size(), _sigma), bounds(_bounds), p_change(_p_change) { // scale to the range - if any for (unsigned i=0; i class eoNormalVecMutation: public eoMonOp { bool hasChanged=false; for (unsigned lieu=0; lieu<_eo.size(); lieu++) - { - if (rng.flip(p_change)) - { - _eo[lieu] += sigma[lieu]*rng.normal(); - bounds.foldsInBounds(lieu, _eo[lieu]); - hasChanged = true; - } - } + { + if (rng.flip(p_change)) + { + _eo[lieu] += sigma[lieu]*rng.normal(); + bounds.foldsInBounds(lieu, _eo[lieu]); + hasChanged = true; + } + } return hasChanged; } @@ -138,7 +138,7 @@ public: * @param _p_change the probability to change a given coordinate */ eoNormalMutation(eoRealVectorBounds & _bounds, - double _sigma, const double& _p_change = 1.0): + double _sigma, const double& _p_change = 1.0): sigma(_sigma), bounds(_bounds), p_change(_p_change) {} /** The class name */ @@ -152,14 +152,14 @@ public: { bool hasChanged=false; for (unsigned lieu=0; lieu<_eo.size(); lieu++) - { - if (rng.flip(p_change)) - { - _eo[lieu] += sigma*rng.normal(); - bounds.foldsInBounds(lieu, _eo[lieu]); - hasChanged = true; - } - } + { + if (rng.flip(p_change)) + { + _eo[lieu] += sigma*rng.normal(); + bounds.foldsInBounds(lieu, _eo[lieu]); + hasChanged = true; + } + } return hasChanged; } @@ -199,8 +199,8 @@ public: * @param _threshold the threshold (the 1/5 - 0.2) */ eoOneFifthMutation(eoEvalFunc & _eval, double & _sigmaInit, - unsigned _windowSize = 10, double _updateFactor=0.83, - double _threshold=0.2): + unsigned _windowSize = 10, double _updateFactor=0.83, + double _threshold=0.2): eoNormalMutation(_sigmaInit), eval(_eval), threshold(_threshold), updateFactor(_updateFactor), nbMut(_windowSize, 0), nbSuccess(_windowSize, 0), genIndex(0) @@ -221,21 +221,21 @@ public: */ bool operator()(EOT & _eo) { - if (_eo.invalid()) // due to some crossover??? - eval(_eo); + if (_eo.invalid()) // due to some crossover??? + eval(_eo); Fitness oldFitness = _eo.fitness(); // save old fitness // call standard operator - then count the successes if (eoNormalMutation::operator()(_eo)) // _eo has been modified - { - _eo.invalidate(); // don't forget!!! - nbMut[genIndex]++; - eval(_eo); // compute fitness of offspring + { + _eo.invalidate(); // don't forget!!! + nbMut[genIndex]++; + eval(_eo); // compute fitness of offspring - if (_eo.fitness() > oldFitness) - nbSuccess[genIndex]++; // update counter - } - return false; // because eval has reset the validity flag + if (_eo.fitness() > oldFitness) + nbSuccess[genIndex]++; // update counter + } + return false; // because eval has reset the validity flag } /** the method that will be called every generation @@ -248,18 +248,18 @@ public: // compute the average stats over the time window for ( unsigned i=0; i threshold) { - Sigma() /= updateFactor; // increase sigma + Sigma() /= updateFactor; // increase sigma } else { - Sigma() *= updateFactor; // decrease sigma + Sigma() *= updateFactor; // decrease sigma } genIndex = (genIndex+1) % nbMut.size() ; nbMut[genIndex] = nbSuccess[genIndex] = 0; @@ -268,15 +268,14 @@ public: private: eoEvalFunc & eval; - double threshold; // 1/5 ! - double updateFactor ; // the multiplicative factor - std::vector nbMut; // total number of mutations per gen - std::vector nbSuccess; // number of successful mutations per gen - unsigned genIndex ; // current index in std::vectors (circular) + double threshold; // 1/5 ! + double updateFactor ; // the multiplicative factor + std::vector nbMut; // total number of mutations per gen + std::vector nbSuccess; // number of successful mutations per gen + unsigned genIndex ; // current index in std::vectors (circular) }; //----------------------------------------------------------------------------- //@} #endif - diff --git a/eo/src/es/eoReal.h b/eo/src/es/eoReal.h index 925d4a3a..ff1908a0 100644 --- a/eo/src/es/eoReal.h +++ b/eo/src/es/eoReal.h @@ -17,7 +17,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: Marc.Schoenauer@polytechnique.fr - todos@geneura.ugr.es, http://geneura.ugr.es + todos@geneura.ugr.es, http://geneura.ugr.es mkeijzer@dhi.dk */ diff --git a/eo/src/es/eoRealAtomXover.h b/eo/src/es/eoRealAtomXover.h index c5528734..4d4244dd 100644 --- a/eo/src/es/eoRealAtomXover.h +++ b/eo/src/es/eoRealAtomXover.h @@ -1,4 +1,4 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- // eoRealAtomXover.h : helper classes for std::vector crossover @@ -8,16 +8,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ */ //----------------------------------------------------------------------------- @@ -35,7 +35,7 @@ #include -/** +/** Discrete crossover == exchange of values * * @ingroup Real @@ -55,20 +55,20 @@ public: /** Exchanges or not the values */ - bool operator()(double& r1, const double& r2) + bool operator()(double& r1, const double& r2) { if (eo::rng.flip()) - if (r1 != r2) // if r1 == r2 you must return false - { - r1 = r2; - return true; - } + if (r1 != r2) // if r1 == r2 you must return false + { + r1 = r2; + return true; + } return false; } - + }; -/** +/** Intermediate crossover == linear combination * * @ingroup Real @@ -88,13 +88,13 @@ public: /** Linear combination of both parents */ - bool operator()(double& r1, const double& r2) + bool operator()(double& r1, const double& r2) { double alpha = eo::rng.uniform(); r1 = alpha * r2 + (1-alpha) * r1; return true; } - + }; #endif diff --git a/eo/src/es/eoRealInitBounded.h b/eo/src/es/eoRealInitBounded.h index d74c7698..6488dd05 100644 --- a/eo/src/es/eoRealInitBounded.h +++ b/eo/src/es/eoRealInitBounded.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoRealInitBounded.h // (c) EEAAX 2000 - Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -33,8 +33,8 @@ #include #include -/** Simple initialization for any EOT that derives from std::vector - * uniformly in some bounds +/** Simple initialization for any EOT that derives from std::vector + * uniformly in some bounds * * @ingroup Real * @ingroup Variators @@ -44,7 +44,7 @@ class eoRealInitBounded : public eoInit { public: /** Ctor - from eoRealVectorBounds */ - eoRealInitBounded(eoRealVectorBounds & _bounds):bounds(_bounds) + eoRealInitBounded(eoRealVectorBounds & _bounds):bounds(_bounds) { if (!bounds.isBounded()) throw std::runtime_error("Needs bounded bounds to initialize a std::vector"); @@ -54,7 +54,7 @@ class eoRealInitBounded : public eoInit virtual void operator()(EOT & _eo) { bounds.uniform(_eo); // resizes, and fills uniformly in bounds - _eo.invalidate(); // was MISSING!!!! + _eo.invalidate(); // was MISSING!!!! } /** accessor to the bounds */ @@ -67,5 +67,4 @@ class eoRealInitBounded : public eoInit //----------------------------------------------------------------------------- //@} -#endif - +#endif diff --git a/eo/src/es/eoRealOp.h b/eo/src/es/eoRealOp.h index ab4d47e0..c8c6471a 100644 --- a/eo/src/es/eoRealOp.h +++ b/eo/src/es/eoRealOp.h @@ -66,14 +66,14 @@ template class eoUniformMutation: public eoMonOp * @param _p_change the one probability to change all coordinates */ eoUniformMutation(eoRealVectorBounds & _bounds, - const double& _epsilon, const double& _p_change = 1.0): + const double& _epsilon, const double& _p_change = 1.0): homogeneous(false), bounds(_bounds), epsilon(_bounds.size(), _epsilon), p_change(_bounds.size(), _p_change) { // scale to the range - if any for (unsigned i=0; i class eoUniformMutation: public eoMonOp * @param _p_change the VECTOR of probabilities for each coordinates */ eoUniformMutation(eoRealVectorBounds & _bounds, - const std::vector& _epsilon, - const std::vector& _p_change): + const std::vector& _epsilon, + const std::vector& _p_change): homogeneous(false), bounds(_bounds), epsilon(_epsilon), p_change(_p_change) {} @@ -98,43 +98,43 @@ template class eoUniformMutation: public eoMonOp bool operator()(EOT& _eo) { bool hasChanged=false; - if (homogeneous) // implies no bounds object - for (unsigned lieu=0; lieu<_eo.size(); lieu++) - { - if (rng.flip(p_change[0])) - { - _eo[lieu] += 2*epsilon[0]*rng.uniform()-epsilon[0]; - hasChanged = true; - } - } + if (homogeneous) // implies no bounds object + for (unsigned lieu=0; lieu<_eo.size(); lieu++) + { + if (rng.flip(p_change[0])) + { + _eo[lieu] += 2*epsilon[0]*rng.uniform()-epsilon[0]; + hasChanged = true; + } + } else - { - // sanity check ? - if (_eo.size() != bounds.size()) - throw std::runtime_error("Invalid size of indi in eoUniformMutation"); + { + // sanity check ? + if (_eo.size() != bounds.size()) + throw std::runtime_error("Invalid size of indi in eoUniformMutation"); - for (unsigned lieu=0; lieu<_eo.size(); lieu++) - if (rng.flip(p_change[lieu])) - { - // check the bounds - double emin = _eo[lieu]-epsilon[lieu]; - double emax = _eo[lieu]+epsilon[lieu]; - if (bounds.isMinBounded(lieu)) - emin = std::max(bounds.minimum(lieu), emin); - if (bounds.isMaxBounded(lieu)) - emax = std::min(bounds.maximum(lieu), emax); - _eo[lieu] = emin + (emax-emin)*rng.uniform(); - hasChanged = true; - } - } + for (unsigned lieu=0; lieu<_eo.size(); lieu++) + if (rng.flip(p_change[lieu])) + { + // check the bounds + double emin = _eo[lieu]-epsilon[lieu]; + double emax = _eo[lieu]+epsilon[lieu]; + if (bounds.isMinBounded(lieu)) + emin = std::max(bounds.minimum(lieu), emin); + if (bounds.isMaxBounded(lieu)) + emax = std::min(bounds.maximum(lieu), emax); + _eo[lieu] = emin + (emax-emin)*rng.uniform(); + hasChanged = true; + } + } return hasChanged; } private: bool homogeneous; // == no bounds passed in the ctor eoRealVectorBounds & bounds; - std::vector epsilon; // the ranges for mutation - std::vector p_change; // the proba that each variable is modified + std::vector epsilon; // the ranges for mutation + std::vector p_change; // the proba that each variable is modified }; /** eoDetUniformMutation --> changes exactly k values of the std::vector @@ -166,14 +166,14 @@ template class eoDetUniformMutation: public eoMonOp * @param _no number of coordinate to modify */ eoDetUniformMutation(eoRealVectorBounds & _bounds, - const double& _epsilon, const unsigned& _no = 1): + const double& _epsilon, const unsigned& _no = 1): homogeneous(false), bounds(_bounds), epsilon(_bounds.size(), _epsilon), no(_no) { // scale to the range - if any for (unsigned i=0; i class eoDetUniformMutation: public eoMonOp * @param _no number of coordinates to modify */ eoDetUniformMutation(eoRealVectorBounds & _bounds, - const std::vector& _epsilon, - const unsigned& _no = 1): + const std::vector& _epsilon, + const unsigned& _no = 1): homogeneous(false), bounds(_bounds), epsilon(_epsilon), no(_no) { // scale to the range - if any for (unsigned i=0; i class eoDetUniformMutation: public eoMonOp bool operator()(EOT& _eo) { if (homogeneous) - for (unsigned i=0; i epsilon; // the ranges of mutation + std::vector epsilon; // the ranges of mutation unsigned no; }; @@ -274,7 +274,7 @@ template class eoSegmentCrossover: public eoQuadOp * Must be positive */ eoSegmentCrossover(eoRealVectorBounds & _bounds, - const double& _alpha = 0.0) : + const double& _alpha = 0.0) : bounds(_bounds), alpha(_alpha), range(1+2*_alpha) {} /// The class name. @@ -291,47 +291,47 @@ template class eoSegmentCrossover: public eoQuadOp double r1, r2, fact; double alphaMin = -alpha; double alphaMax = 1+alpha; - if (alpha == 0.0) // no check to perform - fact = -alpha + rng.uniform(range); // in [-alpha,1+alpha) - else // look for the bounds for fact - { - for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - if (r1 != r2) { // otherwise you'll get NAN's - double rmin = std::min(r1, r2); - double rmax = std::max(r1, r2); - double length = rmax - rmin; - if (bounds.isMinBounded(i)) - { - alphaMin = std::max(alphaMin, (bounds.minimum(i)-rmin)/length); - alphaMax = std::min(alphaMax, (rmax-bounds.minimum(i))/length); - } - if (bounds.isMaxBounded(i)) - { - alphaMax = std::min(alphaMax, (bounds.maximum(i)-rmin)/length); - alphaMin = std::max(alphaMin, (rmax-bounds.maximum(i))/length); - } - } - } - fact = alphaMin + (alphaMax-alphaMin)*rng.uniform(); - } + if (alpha == 0.0) // no check to perform + fact = -alpha + rng.uniform(range); // in [-alpha,1+alpha) + else // look for the bounds for fact + { + for (i=0; i<_eo1.size(); i++) + { + r1=_eo1[i]; + r2=_eo2[i]; + if (r1 != r2) { // otherwise you'll get NAN's + double rmin = std::min(r1, r2); + double rmax = std::max(r1, r2); + double length = rmax - rmin; + if (bounds.isMinBounded(i)) + { + alphaMin = std::max(alphaMin, (bounds.minimum(i)-rmin)/length); + alphaMax = std::min(alphaMax, (rmax-bounds.minimum(i))/length); + } + if (bounds.isMaxBounded(i)) + { + alphaMax = std::min(alphaMax, (bounds.maximum(i)-rmin)/length); + alphaMin = std::max(alphaMin, (rmax-bounds.maximum(i))/length); + } + } + } + fact = alphaMin + (alphaMax-alphaMin)*rng.uniform(); + } for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - _eo1[i] = fact * r1 + (1-fact) * r2; - _eo2[i] = (1-fact) * r1 + fact * r2; - } - return true; // shoudl test if fact was 0 or 1 :-))) + { + r1=_eo1[i]; + r2=_eo2[i]; + _eo1[i] = fact * r1 + (1-fact) * r2; + _eo2[i] = (1-fact) * r1 + fact * r2; + } + return true; // shoudl test if fact was 0 or 1 :-))) } protected: eoRealVectorBounds & bounds; double alpha; - double range; // == 1+2*alpha + double range; // == 1+2*alpha }; /** eoHypercubeCrossover --> uniform choice in hypercube @@ -369,7 +369,7 @@ template class eoHypercubeCrossover: public eoQuadOp * Must be positive */ eoHypercubeCrossover(eoRealVectorBounds & _bounds, - const double& _alpha = 0.0): + const double& _alpha = 0.0): bounds(_bounds), alpha(_alpha), range(1+2*_alpha) { if (_alpha < 0) @@ -389,62 +389,62 @@ template class eoHypercubeCrossover: public eoQuadOp bool hasChanged = false; unsigned i; double r1, r2, fact; - if (alpha == 0.0) // no check to perform - for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - if (r1 != r2) { // otherwise do nothing - fact = rng.uniform(range); // in [0,1) - _eo1[i] = fact * r1 + (1-fact) * r2; - _eo2[i] = (1-fact) * r1 + fact * r2; - hasChanged = true; // forget (im)possible alpha=0 - } - } - else // check the bounds - // do not try to get a bound on the linear factor, but rather - // on the object variables themselves - for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - if (r1 != r2) { // otherwise do nothing - double rmin = std::min(r1, r2); - double rmax = std::max(r1, r2); + if (alpha == 0.0) // no check to perform + for (i=0; i<_eo1.size(); i++) + { + r1=_eo1[i]; + r2=_eo2[i]; + if (r1 != r2) { // otherwise do nothing + fact = rng.uniform(range); // in [0,1) + _eo1[i] = fact * r1 + (1-fact) * r2; + _eo2[i] = (1-fact) * r1 + fact * r2; + hasChanged = true; // forget (im)possible alpha=0 + } + } + else // check the bounds + // do not try to get a bound on the linear factor, but rather + // on the object variables themselves + for (i=0; i<_eo1.size(); i++) + { + r1=_eo1[i]; + r2=_eo2[i]; + if (r1 != r2) { // otherwise do nothing + double rmin = std::min(r1, r2); + double rmax = std::max(r1, r2); - // compute min and max for object variables - double objMin = -alpha * rmax + (1+alpha) * rmin; - double objMax = -alpha * rmin + (1+alpha) * rmax; + // compute min and max for object variables + double objMin = -alpha * rmax + (1+alpha) * rmin; + double objMax = -alpha * rmin + (1+alpha) * rmax; - // first find the limits on the alpha's - if (bounds.isMinBounded(i)) - { - objMin = std::max(objMin, bounds.minimum(i)); - } - if (bounds.isMaxBounded(i)) - { - objMax = std::min(objMax, bounds.maximum(i)); - } - // then draw variables - double median = (objMin+objMax)/2.0; // uniform within bounds - // double median = (rmin+rmax)/2.0; // Bounce on bounds - double valMin = objMin + (median-objMin)*rng.uniform(); - double valMax = median + (objMax-median)*rng.uniform(); - // don't always put large value in _eo1 - or what? - if (rng.flip(0.5)) - { - _eo1[i] = valMin; - _eo2[i] = valMax; - } - else - { - _eo1[i] = valMax; - _eo2[i] = valMin; - } - // seomthing has changed - hasChanged = true; // forget (im)possible alpha=0 - } - } + // first find the limits on the alpha's + if (bounds.isMinBounded(i)) + { + objMin = std::max(objMin, bounds.minimum(i)); + } + if (bounds.isMaxBounded(i)) + { + objMax = std::min(objMax, bounds.maximum(i)); + } + // then draw variables + double median = (objMin+objMax)/2.0; // uniform within bounds + // double median = (rmin+rmax)/2.0; // Bounce on bounds + double valMin = objMin + (median-objMin)*rng.uniform(); + double valMax = median + (objMax-median)*rng.uniform(); + // don't always put large value in _eo1 - or what? + if (rng.flip(0.5)) + { + _eo1[i] = valMin; + _eo2[i] = valMax; + } + else + { + _eo1[i] = valMax; + _eo2[i] = valMin; + } + // seomthing has changed + hasChanged = true; // forget (im)possible alpha=0 + } + } return hasChanged; } @@ -452,7 +452,7 @@ template class eoHypercubeCrossover: public eoQuadOp protected: eoRealVectorBounds & bounds; double alpha; - double range; // == 1+2*alphaMin + double range; // == 1+2*alphaMin }; @@ -473,7 +473,7 @@ template class eoRealUXover: public eoQuadOp eoRealUXover(const float& _preference = 0.5): preference(_preference) { if ( (_preference <= 0.0) || (_preference >= 1.0) ) - std::runtime_error("UxOver --> invalid preference"); + std::runtime_error("UxOver --> invalid preference"); } /// The class name. @@ -488,19 +488,19 @@ template class eoRealUXover: public eoQuadOp bool operator()(EOT& _eo1, EOT& _eo2) { if ( _eo1.size() != _eo2.size()) - std::runtime_error("UxOver --> chromosomes sizes don't match" ); + std::runtime_error("UxOver --> chromosomes sizes don't match" ); bool changed = false; for (unsigned int i=0; i<_eo1.size(); i++) - { - if (rng.flip(preference)) - if (_eo1[i] != _eo2[i]) - { - double tmp = _eo1[i]; - _eo1[i]=_eo2[i]; - _eo2[i] = tmp; - changed = true; - } - } + { + if (rng.flip(preference)) + if (_eo1[i] != _eo2[i]) + { + double tmp = _eo1[i]; + _eo1[i]=_eo2[i]; + _eo2[i] = tmp; + changed = true; + } + } return changed; } private: diff --git a/eo/src/es/eoSBXcross.h b/eo/src/es/eoSBXcross.h index e80e6c78..40f8ac36 100644 --- a/eo/src/es/eoSBXcross.h +++ b/eo/src/es/eoSBXcross.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSBXcross.h // (c) Maarten Keijzer 2000 - Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -43,7 +43,7 @@ template class eoSBXCrossover: public eoQuadOp * (Default) Constructor. * The bounds are initialized with the global object that says: no bounds. * - * + * */ eoSBXCrossover(const double& _eta = 1.0) : bounds(eoDummyVectorNoBounds), eta(_eta), range(1) {} @@ -54,7 +54,7 @@ template class eoSBXCrossover: public eoQuadOp /** * Constructor with bounds * @param _bounds an eoRealVectorBounds that contains the bounds - * @param _eta the amount of exploration OUTSIDE the parents + * @param _eta the amount of exploration OUTSIDE the parents * as in BLX-alpha notation (Eshelman and Schaffer) * 0 == contractive application * Must be positive @@ -62,8 +62,8 @@ template class eoSBXCrossover: public eoQuadOp - eoSBXCrossover(eoRealVectorBounds & _bounds, - const double& _eta = 1.0) : + eoSBXCrossover(eoRealVectorBounds & _bounds, + const double& _eta = 1.0) : bounds(_bounds), eta(_eta), range(1) {} /////////////////////////////////////////////// @@ -76,14 +76,14 @@ template class eoSBXCrossover: public eoQuadOp * eta, the SBX parameter */ - eoSBXCrossover(eoParser & _parser) : + eoSBXCrossover(eoParser & _parser) : // First, decide whether the objective variables are bounded // Warning, must be the same keywords than other possible objectBounds elsewhere bounds (_parser.getORcreateParam(eoDummyVectorNoBounds, "objectBounds", "Bounds for variables", 'B', "Variation Operators").value()) , // then get eta value eta (_parser.getORcreateParam(1.0, "eta", "SBX eta parameter", '\0', "Variation Operators").value()) , range(1) {} - + /// The class name. virtual std::string className() const { return "eoSBXCrossover"; } @@ -91,47 +91,45 @@ template class eoSBXCrossover: public eoQuadOp /***************************************** * SBX crossover - modifies both parents * * @param _eo1 The first parent * - * @param _eo2 The first parent * + * @param _eo2 The first parent * *****************************************/ bool operator()(EOT& _eo1, EOT& _eo2) { unsigned i; double r1, r2, beta; - for (i=0; i<_eo1.size(); i++) - { + for (i=0; i<_eo1.size(); i++) + { double u = rng.uniform(range) ; - if ( u <= 0.5 ) - beta = exp( (1/(eta+1))*log(2*u)); + if ( u <= 0.5 ) + beta = exp( (1/(eta+1))*log(2*u)); else - beta = exp((1/(eta+1))*log(1/(2*(1-u)))); - - - - r1=_eo1[i]; - r2=_eo2[i]; - _eo1[i] =0.5*((1+beta)*r1+(1-beta)*r2); - _eo2[i] =0.5*((1-beta)*r1+(1+beta)*r2); - - - if(!(bounds.isInBounds(i,_eo1[i]))) - bounds.foldsInBounds(i,_eo1[i]); - if(!(bounds.isInBounds(i,_eo2[i]))) - bounds.foldsInBounds(i,_eo2[i]); + beta = exp((1/(eta+1))*log(1/(2*(1-u)))); - } - return true; - } - - + r1=_eo1[i]; + r2=_eo2[i]; + _eo1[i] =0.5*((1+beta)*r1+(1-beta)*r2); + _eo2[i] =0.5*((1-beta)*r1+(1+beta)*r2); + + + if(!(bounds.isInBounds(i,_eo1[i]))) + bounds.foldsInBounds(i,_eo1[i]); + if(!(bounds.isInBounds(i,_eo2[i]))) + bounds.foldsInBounds(i,_eo2[i]); + + + + } + return true; + } + + protected: eoRealVectorBounds & bounds; double eta; - double range; // == 1 + double range; // == 1 }; - - diff --git a/eo/src/es/make_algo_scalar_es.cpp b/eo/src/es/make_algo_scalar_es.cpp index fa35cb36..47585a78 100644 --- a/eo/src/es/make_algo_scalar_es.cpp +++ b/eo/src/es/make_algo_scalar_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar_es.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of select/replace fns * of the library for evolution of ***eoEs genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi /// The following function merely call the templatized do_* functions above @@ -82,4 +82,3 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoS { return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); } - diff --git a/eo/src/es/make_algo_scalar_real.cpp b/eo/src/es/make_algo_scalar_real.cpp index 91b5ccd1..1a1796be 100644 --- a/eo/src/es/make_algo_scalar_real.cpp +++ b/eo/src/es/make_algo_scalar_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar_real.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of select/replace fns * of the library for evolution of ***eoReal*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir */ @@ -58,4 +58,3 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoSta { return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); } - diff --git a/eo/src/es/make_checkpoint_es.cpp b/eo/src/es/make_checkpoint_es.cpp index dea658dc..12bc7860 100644 --- a/eo/src/es/make_checkpoint_es.cpp +++ b/eo/src/es/make_checkpoint_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_checkpoint_es.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of checkpoint fns * of the library for evolution of ***ES genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_checkpoint.h in the src/do dir */ @@ -43,11 +43,11 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi -/// The following function merely call the templatized do_* functions +/// The following function merely call the templatized do_* functions // checkpoint ///////////// @@ -55,7 +55,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _ { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } @@ -65,7 +65,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _s { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } @@ -75,9 +75,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _st { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } - - diff --git a/eo/src/es/make_checkpoint_real.cpp b/eo/src/es/make_checkpoint_real.cpp index 1995d78c..a1cf6d4f 100644 --- a/eo/src/es/make_checkpoint_real.cpp +++ b/eo/src/es/make_checkpoint_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_checkpoint_real.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of checkpoint fns * of the library for evolution of ***eoReal*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_checkpoint.h in the src/do dir */ @@ -45,7 +45,7 @@ // the instanciating EOType #include -/// The following function merely call the templatized do_* functions +/// The following function merely call the templatized do_* functions // checkpoint ///////////// @@ -53,9 +53,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _stat { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } - - diff --git a/eo/src/es/make_continue_es.cpp b/eo/src/es/make_continue_es.cpp index ca9d4fee..e5016795 100644 --- a/eo/src/es/make_continue_es.cpp +++ b/eo/src/es/make_continue_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_continue_es.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of continuator fns * of the library for evolution of ***ES genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_continue.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi /// The following function merely call the templatized do_* functions @@ -79,5 +79,3 @@ eoContinue >& make_continue(eoParser& _parser, eoS { return do_make_continue(_parser, _state, _eval); } - - diff --git a/eo/src/es/make_continue_real.cpp b/eo/src/es/make_continue_real.cpp index 868e8eec..06085217 100644 --- a/eo/src/es/make_continue_real.cpp +++ b/eo/src/es/make_continue_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_continue_real.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of continuator fns * of the library for evolution of ***REAL vectors*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_continue.h in the src/do dir */ @@ -57,5 +57,3 @@ eoContinue >& make_continue(eoParser& _parser, eoSta { return do_make_continue(_parser, _state, _eval); } - - diff --git a/eo/src/es/make_es.h b/eo/src/es/make_es.h index 27bfe4f6..46a4e23f 100644 --- a/eo/src/es/make_es.h +++ b/eo/src/es/make_es.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // es.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 @@ -24,20 +24,20 @@ */ //----------------------------------------------------------------------------- -/** This file contains all ***INSTANCIATED*** declarations of all components +/** This file contains all ***INSTANCIATED*** declarations of all components * of the library for ***ES-like gnptype*** evolution inside EO. * It should be included in the file that calls any of the corresponding fns * - * The corresponding ***INSTANCIATED*** definitions are contained in - * the different .cpp files in the src/es dir, + * The corresponding ***INSTANCIATED*** definitions are contained in + * the different .cpp files in the src/es dir, * while the TEMPLATIZED code is define in the different make_XXX.h files - * either in hte src/do dir for representation independant functions, + * either in hte src/do dir for representation independant functions, * or in the src/es dir for representation dependent stuff. * - * See also real.h for the similar declarations of eoReal genotypes + * See also real.h for the similar declarations of eoReal genotypes * i.e. ***without*** mutation parameters attached to individuals * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -54,9 +54,9 @@ #include #include -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi // include all similar declaration for eoReal - i.e. real-valued genotyes // without self-adaptation @@ -68,7 +68,7 @@ //Representation dependent - rewrite everything anew for each representation ////////////////////////// -// the genotypes +// the genotypes eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsSimple _eo); eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsSimple _eo); diff --git a/eo/src/es/make_genotype_real.h b/eo/src/es/make_genotype_real.h index 7977bbf9..6ab62967 100644 --- a/eo/src/es/make_genotype_real.h +++ b/eo/src/es/make_genotype_real.h @@ -84,7 +84,7 @@ eoEsChromInit & do_make_genotype(eoParser& _parser, eoState& _state, EOT) eoValueParam& sigmaParam = _parser.getORcreateParam(std::string("0.3"), "sigmaInit", "Initial value for Sigmas (with a '%' -> scaled by the range of each variable)", - 's', "Genotype Initialization"); + 's', "Genotype Initialization"); // check for % bool to_scale = false; size_t pos = sigmaParam.value().find('%'); diff --git a/eo/src/es/make_op.h b/eo/src/es/make_op.h index 0bcda4f7..1c7fe50e 100644 --- a/eo/src/es/make_op.h +++ b/eo/src/es/make_op.h @@ -97,23 +97,23 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit v; std::vector::iterator it; for (it=ppBounds.second.begin(); itc_str()); - double r; - is >> r; - v.push_back(r); - } + { + istrstream is(it->c_str()); + double r; + is >> r; + v.push_back(r); + } // now create the eoRealVectorBounds object if (v.size() == 2) // a min and a max for all variables - ptBounds = new eoRealVectorBounds(vecSize, v[0], v[1]); - else // no time now - throw std::runtime_error("Sorry, only unique bounds for all variables implemented at the moment. Come back later"); + ptBounds = new eoRealVectorBounds(vecSize, v[0], v[1]); + else // no time now + throw std::runtime_error("Sorry, only unique bounds for all variables implemented at the moment. Come back later"); // we need to give ownership of this pointer to somebody /////////// end of temporary code } - else // no param for bounds was given + else // no param for bounds was given ptBounds = new eoRealVectorNoBounds(vecSize); // DON'T USE eoDummyVectorNoBounds - // as it does not have any dimension + // as it does not have any dimension // this is a temporary version(!), // while Maarten codes the full tree-structured general operator input @@ -185,7 +185,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit(*ptQuad, segmentRateParam.value()); - // arithmetic crossover + // arithmetic crossover ptQuad = new eoArithmeticCrossover(*ptBounds); _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, arithmeticRateParam.value()); @@ -258,7 +258,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit(*ptMon, uniformMutRateParam.value()); - // mutate exactly 1 component (uniformly) per individual + // mutate exactly 1 component (uniformly) per individual ptMon = new eoDetUniformMutation(*ptBounds, epsilonParam.value()); _state.storeFunctor(ptMon); ptCombinedMonOp->add(*ptMon, detMutRateParam.value()); @@ -289,7 +289,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit *op = new eoSequentialOp; _state.storeFunctor(op); - op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross op->add(*ptCombinedMonOp, pMutParam.value()); // that's it! diff --git a/eo/src/es/make_op_es.cpp b/eo/src/es/make_op_es.cpp index 7f463599..4dfbacf3 100644 --- a/eo/src/es/make_op_es.cpp +++ b/eo/src/es/make_op_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_real.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of operators fns * of the library for ***eoReal*** evolution inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in es.h in src/es dir * while the TEMPLATIZED code is define in make_op.h in the es dir * @@ -77,4 +77,3 @@ eoGenOp >& make_op(eoParser& _parser, eoState& _s { return do_make_op(_parser, _state, _init); } - diff --git a/eo/src/es/make_op_es.h b/eo/src/es/make_op_es.h index 0d93e060..00a3373f 100644 --- a/eo/src/es/make_op_es.h +++ b/eo/src/es/make_op_es.h @@ -154,10 +154,10 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< if (crossTypeParam.value() == std::string("global")) ptCross = new eoEsGlobalXover(*ptObjAtomCross, *ptStdevAtomCross); else if (crossTypeParam.value() == std::string("standard")) - { // using a standard eoBinOp, but wrap it into an eoGenOp + { // using a standard eoBinOp, but wrap it into an eoGenOp eoBinOp & crossTmp = _state.storeFunctor( - new eoEsStandardXover(*ptObjAtomCross, *ptStdevAtomCross) - ); + new eoEsStandardXover(*ptObjAtomCross, *ptStdevAtomCross) + ); ptCross = new eoBinGenOp(crossTmp); } else throw std::runtime_error("Invalide Object variable crossover type"); diff --git a/eo/src/es/make_op_real.cpp b/eo/src/es/make_op_real.cpp index 19435831..b429cd41 100644 --- a/eo/src/es/make_op_real.cpp +++ b/eo/src/es/make_op_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_real.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of operators fns * of the library for ***eoReal*** evolution inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in es.h in src/es dir * while the TEMPLATIZED code is define in make_op.h in the es dir * diff --git a/eo/src/es/make_op_real.h b/eo/src/es/make_op_real.h index 2792e638..19a8b16b 100644 --- a/eo/src/es/make_op_real.h +++ b/eo/src/es/make_op_real.h @@ -168,12 +168,12 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< _state.storeFunctor(ptQuad); ptCombinedQuadOp = new eoPropCombinedQuadOp(*ptQuad, segmentRateParam.value()); - // hypercube crossover + // hypercube crossover ptQuad = new eoHypercubeCrossover(boundsParam.value(), alphaParam.value()); _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, hypercubeRateParam.value()); - // uniform crossover + // uniform crossover ptQuad = new eoRealUXover(); _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, uxoverRateParam.value()); @@ -249,7 +249,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< // create the CombinedMonOp ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, uniformMutRateParam.value()); - // mutate exactly 1 component (uniformly) per individual + // mutate exactly 1 component (uniformly) per individual ptMon = new eoDetUniformMutation(boundsParam.value(), epsilonParam.value()); _state.storeFunctor(ptMon); ptCombinedMonOp->add(*ptMon, detMutRateParam.value()); @@ -279,7 +279,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< // now the sequential eoSequentialOp & op = _state.storeFunctor(new eoSequentialOp); - op.add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op.add(*cross, 1.0); // always crossover (but clone with prob 1-pCross op.add(*ptCombinedMonOp, pMutParam.value()); // that's it! diff --git a/eo/src/es/make_pop_es.cpp b/eo/src/es/make_pop_es.cpp index 4f77e2f5..4f72e344 100644 --- a/eo/src/es/make_pop_es.cpp +++ b/eo/src/es/make_pop_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop_es.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of pop. init. fns * of the library for evolution of ***ES genotypes*** indis inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_pop.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi /// The following function merely call the templatized do_* functions above @@ -82,5 +82,3 @@ eoPop >& make_pop(eoParser& _parser, eoState& _st { return do_make_pop(_parser, _state, _init); } - - diff --git a/eo/src/es/make_pop_real.cpp b/eo/src/es/make_pop_real.cpp index eaa75baa..968e7251 100644 --- a/eo/src/es/make_pop_real.cpp +++ b/eo/src/es/make_pop_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop_real.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of pop. init. fns * of the library for evolution of ***eoReal*** indis inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_pop.h in the src/do dir */ @@ -58,5 +58,3 @@ eoPop >& make_pop(eoParser& _parser, eoState& _stat { return do_make_pop(_parser, _state, _init); } - - diff --git a/eo/src/es/make_real.h b/eo/src/es/make_real.h index bb356fc7..bc04ba1f 100644 --- a/eo/src/es/make_real.h +++ b/eo/src/es/make_real.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // real.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 @@ -24,20 +24,20 @@ */ //----------------------------------------------------------------------------- -/** This file contains all ***INSTANCIATED*** declarations of all components +/** This file contains all ***INSTANCIATED*** declarations of all components * of the library for ***std::vector*** evolution inside EO. * It should be included in the file that calls any of the corresponding fns * - * The corresponding ***INSTANCIATED*** definitions are contained in - * the different .cpp files in the src/es dir, + * The corresponding ***INSTANCIATED*** definitions are contained in + * the different .cpp files in the src/es dir, * while the TEMPLATIZED code is define in the different make_XXX.h files - * either in hte src/do dir for representation independant functions, + * either in hte src/do dir for representation independant functions, * or in the src/es dir for representation dependent stuff. * - * See also es.h for the similar declarations of ES-like genotypes + * See also es.h for the similar declarations of ES-like genotypes * i.e. ***with*** mutation parameters attached to individuals * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -64,7 +64,7 @@ /** @addtogroup Builders * @{ */ -// the genotypes +// the genotypes eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoReal _eo); eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoReal _eo); diff --git a/eo/src/es/make_run_es.cpp b/eo/src/es/make_run_es.cpp index 77a45a08..59912a7f 100644 --- a/eo/src/es/make_run_es.cpp +++ b/eo/src/es/make_run_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_run_es.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of run funs * of the library for evolution of ***ES genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_run.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi // the instanciating fitnesses #include @@ -84,4 +84,3 @@ void run_ea(eoAlgo >& _ga, eoPop >& _ga, eoPop::iterator operator[](unsigned i) { return data.begin() + i * (i+1) / 2; } std::vector::const_iterator operator[](unsigned i) const { return data.begin() + i*(i+1)/2; } }; @@ -32,15 +32,14 @@ class square_matrix { public: square_matrix(unsigned n_ = 0) : n(n_), data(n * n) {}; - + void resize(unsigned n_) { - n = n_; - data.resize(n*n); + n = n_; + data.resize(n*n); } - + std::vector::iterator operator[](unsigned i) { return data.begin() + i * n; } std::vector::const_iterator operator[](unsigned i) const { return data.begin() + i*n; } }; #endif - diff --git a/eo/src/ga.h b/eo/src/ga.h index 87cc0e34..6abb0181 100644 --- a/eo/src/ga.h +++ b/eo/src/ga.h @@ -1,7 +1,7 @@ //----------------------------------------------------------------------------- // ga.h // (c) GeNeura Team 1998 - 2000, 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 @@ -24,7 +24,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #ifndef _ga_h #define _ga_h diff --git a/eo/src/ga/Readme b/eo/src/ga/Readme index 69d7d466..3d9b8663 100644 --- a/eo/src/ga/Readme +++ b/eo/src/ga/Readme @@ -1,11 +1,11 @@ This directory contains: -- some standard EO source files, named eoXXXXX, that define objects +- some standard EO source files, named eoXXXXX, that define objects for the eoBit representation (bitstrings). - some make_XXX.cpp files that are instanciations for EO bitstrings -(eoBit AND eoBit) of the tempatized code -that is defined in the EO src/do dir. +(eoBit AND eoBit) of the tempatized code +that is defined in the EO src/do dir. This MK's trick allows to actually compile all these bits in a library (eolibga.a) and to only recompile the bits you need for your own (bitstring!) application. @@ -18,4 +18,3 @@ that constructs the EOType initializer (make_genotype.h) and the one that buils up the operators (make_op.h). MS, April 23, 2001CVS - diff --git a/eo/src/ga/eoBit.h b/eo/src/ga/eoBit.h index 7f91b886..c1bc9c75 100644 --- a/eo/src/ga/eoBit.h +++ b/eo/src/ga/eoBit.h @@ -106,11 +106,11 @@ public: std::string bits; is >> bits; if (is) - { - resize(bits.size()); - std::transform(bits.begin(), bits.end(), begin(), + { + resize(bits.size()); + std::transform(bits.begin(), bits.end(), begin(), std::bind2nd(std::equal_to(), '1')); - } + } } }; diff --git a/eo/src/ga/eoBitOp.h b/eo/src/ga/eoBitOp.h index 21205a3d..3e3f4fa5 100644 --- a/eo/src/ga/eoBitOp.h +++ b/eo/src/ga/eoBitOp.h @@ -87,10 +87,10 @@ template class eoDetBitFlip: public eoMonOp { // does not check for duplicate: if someone volunteers .... for (unsigned k=0; k class eoBitMutation: public eoMonOp double actualRate = (normalize ? rate/chrom.size() : rate); bool changed_something = false; for (unsigned i = 0; i < chrom.size(); i++) - if (eo::rng.flip(actualRate)) + if (eo::rng.flip(actualRate)) { - chrom[i] = !chrom[i]; + chrom[i] = !chrom[i]; changed_something = true; } @@ -137,7 +137,7 @@ template class eoBitMutation: public eoMonOp private: double rate; - bool normalize; // divide rate by chromSize + bool normalize; // divide rate by chromSize }; @@ -187,16 +187,16 @@ template class eoBitNext: public eoMonOp bool operator()(Chrom& chrom) { for (int i = chrom.size() - 1; i >= 0; i--) - if (chrom[i]) - { - chrom[i] = 0; - continue; - } - else - { - chrom[i] = 1; - break; - } + if (chrom[i]) + { + chrom[i] = 0; + continue; + } + else + { + chrom[i] = 1; + break; + } return true; } @@ -221,16 +221,16 @@ template class eoBitPrev: public eoMonOp bool operator()(Chrom& chrom) { for (int i = chrom.size() - 1; i >= 0; i--) - if (chrom[i]) - { - chrom[i] = 0; - break; - } - else - { - chrom[i] = 1; - continue; - } + if (chrom[i]) + { + chrom[i] = 0; + break; + } + else + { + chrom[i] = 1; + continue; + } return true; } @@ -281,7 +281,7 @@ template class eoUBitXover: public eoQuadOp eoUBitXover(const float& _preference = 0.5): preference(_preference) { if ( (_preference <= 0.0) || (_preference >= 1.0) ) - std::runtime_error("UxOver --> invalid preference"); + std::runtime_error("UxOver --> invalid preference"); } /// The class name. virtual std::string className() const { return "eoUBitXover"; } @@ -295,18 +295,18 @@ template class eoUBitXover: public eoQuadOp bool operator()(Chrom& chrom1, Chrom& chrom2) { if ( chrom1.size() != chrom2.size()) - std::runtime_error("UxOver --> chromosomes sizes don't match" ); + std::runtime_error("UxOver --> chromosomes sizes don't match" ); bool changed = false; for (unsigned int i=0; i class eoBitGxOver: public eoQuadOp gene_size(_gene_size), num_points(_num_points) { if (gene_size < 1) - std::runtime_error("GxOver --> invalid gene size"); + std::runtime_error("GxOver --> invalid gene size"); if (num_points < 1) - std::runtime_error("GxOver --> invalid number of points"); + std::runtime_error("GxOver --> invalid number of points"); } /// The class name @@ -412,22 +412,22 @@ template class eoBitGxOver: public eoQuadOp // selects genes to swap do { - unsigned bit = eo::rng.random(max_genes); - if (points[bit]) - continue; - else - { - points[bit] = true; - cut_genes--; - } + unsigned bit = eo::rng.random(max_genes); + if (points[bit]) + continue; + else + { + points[bit] = true; + cut_genes--; + } } while (cut_genes); // swaps genes for (unsigned i = 0; i < points.size(); i++) - if (points[i]) - std::swap_ranges(chrom1.begin() + i * gene_size, - chrom1.begin() + i * gene_size + gene_size, - chrom2.begin() + i * gene_size); + if (points[i]) + std::swap_ranges(chrom1.begin() + i * gene_size, + chrom1.begin() + i * gene_size + gene_size, + chrom2.begin() + i * gene_size); return true; } @@ -442,4 +442,3 @@ template class eoBitGxOver: public eoQuadOp //----------------------------------------------------------------------------- //@} #endif - diff --git a/eo/src/ga/eoBitOpFactory.h b/eo/src/ga/eoBitOpFactory.h index b16900e7..6511f937 100644 --- a/eo/src/ga/eoBitOpFactory.h +++ b/eo/src/ga/eoBitOpFactory.h @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- // eoOpFactory.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -39,135 +39,134 @@ that are created here @ingroup Variators */ template< class EOT> -class eoBitOpFactory: public eoFactory +class eoBitOpFactory: public eoFactory { - + public: - - /// @name ctors and dtors - //{@ - /// constructor - eoBitOpFactory( ) {}; - - /// destructor - virtual ~eoBitOpFactory() {}; - //@} - /** Another factory method: creates an object from an std::istream, reading from - it whatever is needed to create the object. Usually, the format for the std::istream will be\\ - objectType parameter1 parameter2 ... parametern\\ - If there are problems, an std::exception is raised; it should be caught at the - upper level, because it might be something for that level\\ - At the same time, it catches std::exceptions thrown at a lower level, which will - indicate that whatever is in the stream is for this method to process - @param _is an stream from where a single line will be read - @throw runtime_std::exception if the object type is not known - */ - virtual eoOp* make(std::istream& _is) + /// @name ctors and dtors + //{@ + /// constructor + eoBitOpFactory( ) {}; + + /// destructor + virtual ~eoBitOpFactory() {}; + //@} + + /** Another factory method: creates an object from an std::istream, reading from + it whatever is needed to create the object. Usually, the format for the std::istream will be\\ + objectType parameter1 parameter2 ... parametern\\ + If there are problems, an std::exception is raised; it should be caught at the + upper level, because it might be something for that level\\ + At the same time, it catches std::exceptions thrown at a lower level, which will + indicate that whatever is in the stream is for this method to process + @param _is an stream from where a single line will be read + @throw runtime_std::exception if the object type is not known + */ + virtual eoOp* make(std::istream& _is) { - eoOp * opPtr = NULL; - try { - opPtr = eoFactory::make( _is ); - } catch ( const std::string& objectTypeStr ) { - if ( objectTypeStr == "eoBinBitFlip" ) { - opPtr = new eoOneBitFlip( ); - } - // handles old operator names as well as new ones - if ( objectTypeStr == "eoOneBitFlip" ) { - opPtr = new eoOneBitFlip( ); - } + eoOp * opPtr = NULL; + try { + opPtr = eoFactory::make( _is ); + } catch ( const std::string& objectTypeStr ) { + if ( objectTypeStr == "eoBinBitFlip" ) { + opPtr = new eoOneBitFlip( ); + } + // handles old operator names as well as new ones + if ( objectTypeStr == "eoOneBitFlip" ) { + opPtr = new eoOneBitFlip( ); + } - // Standard BitFilp Mutation - if ( objectTypeStr == "eoBinMutation" ) { - float rate; - _is >> rate; - opPtr = new eoBitMutation( rate ); - } - if ( objectTypeStr == "eoBitMutation" ) { - float rate; - _is >> rate; - opPtr = new eoBitMutation( rate ); - } + // Standard BitFilp Mutation + if ( objectTypeStr == "eoBinMutation" ) { + float rate; + _is >> rate; + opPtr = new eoBitMutation( rate ); + } + if ( objectTypeStr == "eoBitMutation" ) { + float rate; + _is >> rate; + opPtr = new eoBitMutation( rate ); + } - // Bit inversion - if ( objectTypeStr == "eoBinInversion" ) { - opPtr = new eoBitInversion( ); - } - if ( objectTypeStr == "eoBitInversion" ) { - opPtr = new eoBitInversion( ); - } + // Bit inversion + if ( objectTypeStr == "eoBinInversion" ) { + opPtr = new eoBitInversion( ); + } + if ( objectTypeStr == "eoBitInversion" ) { + opPtr = new eoBitInversion( ); + } - // Next binary value - if ( objectTypeStr == "eoBinNext" ) { - opPtr = new eoBitNext( ); - } - if ( objectTypeStr == "eoBitNext" ) { - opPtr = new eoBitNext( ); - } + // Next binary value + if ( objectTypeStr == "eoBinNext" ) { + opPtr = new eoBitNext( ); + } + if ( objectTypeStr == "eoBitNext" ) { + opPtr = new eoBitNext( ); + } - // Previous binary value - if ( objectTypeStr == "eoBinPrev" ) { - opPtr = new eoBitPrev( ); - } - if ( objectTypeStr == "eoBitPrev" ) { - opPtr = new eoBitPrev( ); - } + // Previous binary value + if ( objectTypeStr == "eoBinPrev" ) { + opPtr = new eoBitPrev( ); + } + if ( objectTypeStr == "eoBitPrev" ) { + opPtr = new eoBitPrev( ); + } - // 1 point Xover - if ( objectTypeStr == "eoBinCrossover" ) { - opPtr = new eo1PtBitXover( ); - } - if ( objectTypeStr == "eo1PtBitXover" ) { - opPtr = new eo1PtBitXover( ); - } + // 1 point Xover + if ( objectTypeStr == "eoBinCrossover" ) { + opPtr = new eo1PtBitXover( ); + } + if ( objectTypeStr == "eo1PtBitXover" ) { + opPtr = new eo1PtBitXover( ); + } - // Npts Xover - if ( objectTypeStr == "eoBinNxOver" ) { - unsigned nPoints; - _is >> nPoints; - opPtr = new eoNPtsBitXover( nPoints ); - } - if ( objectTypeStr == "eoNPtsBitXover" ) { - unsigned nPoints; - _is >> nPoints; - opPtr = new eoNPtsBitXover( nPoints ); - } + // Npts Xover + if ( objectTypeStr == "eoBinNxOver" ) { + unsigned nPoints; + _is >> nPoints; + opPtr = new eoNPtsBitXover( nPoints ); + } + if ( objectTypeStr == "eoNPtsBitXover" ) { + unsigned nPoints; + _is >> nPoints; + opPtr = new eoNPtsBitXover( nPoints ); + } - // Gene Xover (obsolete) - if ( objectTypeStr == "eoBinGxOver" ) { - unsigned geneSize, nPoints; - _is >> geneSize >> nPoints; - opPtr = new eoBitGxOver( geneSize, nPoints ); - } - if ( objectTypeStr == "eoBitGxOver" ) { - unsigned geneSize, nPoints; - _is >> geneSize >> nPoints; - opPtr = new eoBitGxOver( geneSize, nPoints ); - } + // Gene Xover (obsolete) + if ( objectTypeStr == "eoBinGxOver" ) { + unsigned geneSize, nPoints; + _is >> geneSize >> nPoints; + opPtr = new eoBitGxOver( geneSize, nPoints ); + } + if ( objectTypeStr == "eoBitGxOver" ) { + unsigned geneSize, nPoints; + _is >> geneSize >> nPoints; + opPtr = new eoBitGxOver( geneSize, nPoints ); + } - // Uniform Xover - if ( objectTypeStr == "eoBinUxOver" ) { - float rate; - _is >> rate; - opPtr = new eoUBitXover( rate ); - } - if ( objectTypeStr == "eoUBitXover" ) { - float rate; - _is >> rate; - opPtr = new eoUBitXover( rate ); - } + // Uniform Xover + if ( objectTypeStr == "eoBinUxOver" ) { + float rate; + _is >> rate; + opPtr = new eoUBitXover( rate ); + } + if ( objectTypeStr == "eoUBitXover" ) { + float rate; + _is >> rate; + opPtr = new eoUBitXover( rate ); + } - // nothing read! - if ( !opPtr ) { // to be caught by the upper level - throw objectTypeStr; - } - } - return opPtr; - }; + // nothing read! + if ( !opPtr ) { // to be caught by the upper level + throw objectTypeStr; + } + } + return opPtr; + }; }; #endif - diff --git a/eo/src/ga/eoBoolFlip.h b/eo/src/ga/eoBoolFlip.h index be9d252b..47c43ee0 100644 --- a/eo/src/ga/eoBoolFlip.h +++ b/eo/src/ga/eoBoolFlip.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoBoolFlip.h // (c) Marc Schoenauer, 2003 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -33,7 +33,7 @@ @ingroup Variators */ class eoBoolFlip : public eoMonOp { -public: +public: /** simply flips the boolean argument */ bool operator()(bool & _b) { diff --git a/eo/src/ga/eoPBILAdditive.h b/eo/src/ga/eoPBILAdditive.h index dd360337..e57a05a2 100644 --- a/eo/src/ga/eoPBILAdditive.h +++ b/eo/src/ga/eoPBILAdditive.h @@ -49,8 +49,8 @@ public: * using the default values is equivalent to using eoPBILOrg */ eoPBILAdditive(double _LRBest, unsigned _nbBest = 1, - double _tolerance=0.0, - double _LRWorst = 0.0, unsigned _nbWorst = 0 ) : + double _tolerance=0.0, + double _LRWorst = 0.0, unsigned _nbWorst = 0 ) : maxBound(1.0-_tolerance), minBound(_tolerance), LR(0.0), nbBest(_nbBest), nbWorst(_nbWorst) { @@ -59,18 +59,18 @@ public: if (_nbBest) { - lrb = _LRBest/_nbBest; - LR += _LRBest; + lrb = _LRBest/_nbBest; + LR += _LRBest; } else - lrb=0.0; // just in case + lrb=0.0; // just in case if (_nbWorst) { - lrw = _LRWorst/_nbWorst; - LR += _LRWorst; + lrw = _LRWorst/_nbWorst; + LR += _LRWorst; } else - lrw=0.0; // just in case + lrw=0.0; // just in case } /** Update the distribution from the current population */ @@ -82,29 +82,29 @@ public: unsigned i, popSize=_pop.size(); std::vector result; - _pop.sort(result); // is it necessary to sort the whole population? - // but I'm soooooooo lazy !!! + _pop.sort(result); // is it necessary to sort the whole population? + // but I'm soooooooo lazy !!! for (unsigned g=0; g=popSize-nbWorst; i--) - { - const EOT & best = (*result[i]); - if ( !best[g] ) // if 0, increase proba - p[g] += lrw; - } - // stay in [0,1] (possibly strictly due to tolerance) - p[g] = std::min(maxBound, p[g]); - p[g] = std::max(minBound, p[g]); + p[g] *= (1-LR); // relaxation + if (nbBest) // update from some of the best + for (i=0; i=popSize-nbWorst; i--) + { + const EOT & best = (*result[i]); + if ( !best[g] ) // if 0, increase proba + p[g] += lrw; + } + // stay in [0,1] (possibly strictly due to tolerance) + p[g] = std::min(maxBound, p[g]); + p[g] = std::max(minBound, p[g]); } } diff --git a/eo/src/ga/eoPBILDistrib.h b/eo/src/ga/eoPBILDistrib.h index 91720acb..56556ba0 100644 --- a/eo/src/ga/eoPBILDistrib.h +++ b/eo/src/ga/eoPBILDistrib.h @@ -28,26 +28,26 @@ #include /** - * Distribution Class for PBIL algorithm + * Distribution Class for PBIL algorithm * (Population-Based Incremental Learning, Baluja and Caruana 96) * * It encodes a univariate distribution on the space of bitstrings, * i.e. one probability for each bit to be one * - * It is an eoValueParam > : + * It is an eoValueParam > : * the std::vector stores the probabilities that each bit is 1 * * It is still pure virtual, as the update method needs to be specified */ template -class eoPBILDistrib : public eoDistribution, - public eoValueParam > +class eoPBILDistrib : public eoDistribution, + public eoValueParam > { public: /** Ctor with size of genomes, and update parameters */ eoPBILDistrib(unsigned _genomeSize) : - eoDistribution(), + eoDistribution(), eoValueParam >(std::vector(_genomeSize, 0.5), "Distribution"), genomeSize(_genomeSize) {} @@ -55,10 +55,10 @@ public: /** the randomizer of indis */ virtual void operator()(EOT & _eo) { - _eo.resize(genomeSize); // just in case + _eo.resize(genomeSize); // just in case for (unsigned i=0; i> sz; - + value().resize(sz); unsigned i; - + for (i = 0; i < sz; ++i) { - double atom; - is >> atom; - value()[i] = atom; + double atom; + is >> atom; + value()[i] = atom; } } diff --git a/eo/src/ga/eoPBILOrg.h b/eo/src/ga/eoPBILOrg.h index 80bf2d09..45b95c84 100644 --- a/eo/src/ga/eoPBILOrg.h +++ b/eo/src/ga/eoPBILOrg.h @@ -58,15 +58,15 @@ public: for (unsigned g=0; g // for time(0) for random seeding +#include // for time(0) for random seeding #include #include #include @@ -51,21 +51,21 @@ eoPBILDistrib & do_make_PBILdistrib(eoParser & _parser, eoState& _state, E // First the random seed eoValueParam& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) - seedParam.value() = time(0); + seedParam.value() = time(0); // chromosome size: unsigned theSize; // but it might have been already read in the definition fo the performance eoParam* ptParam = _parser.getParamWithLongName(std::string("chromSize")); - if (!ptParam) // not already defined: read it here + if (!ptParam) // not already defined: read it here { - theSize = _parser.createParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); + theSize = _parser.createParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); } - else // it was read before, get its value + else // it was read before, get its value { - eoValueParam* ptChromSize = dynamic_cast*>(ptParam); - theSize = ptChromSize->value(); + eoValueParam* ptChromSize = dynamic_cast*>(ptParam); + theSize = ptChromSize->value(); } eoPBILDistrib * ptDistrib = new eoPBILDistrib(theSize); diff --git a/eo/src/ga/make_PBILupdate.h b/eo/src/ga/make_PBILupdate.h index 9b4ffd83..a8572136 100644 --- a/eo/src/ga/make_PBILupdate.h +++ b/eo/src/ga/make_PBILupdate.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_PBILupdate.h // (c) Marc Schoenauer, Maarten Keijzer, 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 @@ -47,7 +47,7 @@ template eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, EOT) { - // ast the moment, a single update rule is available + // ast the moment, a single update rule is available // but at some point we'll have to choose among different rules std::string UType = _parser.createParam(std::string("PBIL"), "updateRule", "Type of update rule (only PBIL additive at the moment)", 'U', "Algorithm").value(); @@ -59,7 +59,7 @@ eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, double tolerance = _parser.createParam(0.0, "tolerance", "Keeping away from 0 and 1", 't', "Algorithm").value(); // a pointer to choose among several possible types - eoDistribUpdater * ptUpdate; + eoDistribUpdater * ptUpdate; if (UType == std::string("PBIL")) { @@ -72,7 +72,7 @@ eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, throw std::runtime_error("Only PBIL additive update rule available at the moment"); // done: don't forget to store the allocated pointers - _state.storeFunctor(ptUpdate); + _state.storeFunctor(ptUpdate); return *ptUpdate; } diff --git a/eo/src/ga/make_algo_scalar_ga.cpp b/eo/src/ga/make_algo_scalar_ga.cpp index aa9b2e05..631e6dad 100644 --- a/eo/src/ga/make_algo_scalar_ga.cpp +++ b/eo/src/ga/make_algo_scalar_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of pop. init. * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/ga/ga.h * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -61,4 +61,3 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoStat { return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); } - diff --git a/eo/src/ga/make_checkpoint_ga.cpp b/eo/src/ga/make_checkpoint_ga.cpp index f7da6d4a..eecc40ca 100644 --- a/eo/src/ga/make_checkpoint_ga.cpp +++ b/eo/src/ga/make_checkpoint_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_checkpoint_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in make_checkpoint_ga.h * while the TEMPLATIZED code is define in make_checkpoint.h in the do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -48,7 +48,7 @@ // the instanciating EOType #include -/// The following function merely call the templatized do_* functions +/// The following function merely call the templatized do_* functions // checkpoint ///////////// @@ -56,9 +56,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } - - diff --git a/eo/src/ga/make_continue_ga.cpp b/eo/src/ga/make_continue_ga.cpp index e2dbb35a..1b25a0c8 100644 --- a/eo/src/ga/make_continue_ga.cpp +++ b/eo/src/ga/make_continue_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_continue_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in ga.h * while the TEMPLATIZED code is define in make_contninue.h in the src/do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -60,5 +60,3 @@ eoContinue >& make_continue(eoParser& _parser, eoStat { return do_make_continue(_parser, _state, _eval); } - - diff --git a/eo/src/ga/make_ga.h b/eo/src/ga/make_ga.h index 6ce8a07a..ce594903 100644 --- a/eo/src/ga/make_ga.h +++ b/eo/src/ga/make_ga.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // ga.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 @@ -24,14 +24,14 @@ */ //----------------------------------------------------------------------------- -/** This file contains all ***INSTANCIATED*** declarations of all components +/** This file contains all ***INSTANCIATED*** declarations of all components * of the library for ***BISTRING*** evolution inside EO. * It should be included in the file that calls any of the corresponding fns * * The corresponding ***INSTANCIATED*** definitions are contained in ga.cpp * while the TEMPLATIZED code is define in the different makeXXX.h files * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -56,7 +56,7 @@ * @{ */ -// the genotypes +// the genotypes eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo); eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo); diff --git a/eo/src/ga/make_genotype_ga.cpp b/eo/src/ga/make_genotype_ga.cpp index 873093dc..4f9e69ef 100644 --- a/eo/src/ga/make_genotype_ga.cpp +++ b/eo/src/ga/make_genotype_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_genotype_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,8 +35,8 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained - * in ga.h in src/ga dir + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * in ga.h in src/ga dir * while the TEMPLATIZED code is define in make_genotype_ga.h */ diff --git a/eo/src/ga/make_genotype_ga.h b/eo/src/ga/make_genotype_ga.h index 159b85cd..ea1b2005 100644 --- a/eo/src/ga/make_genotype_ga.h +++ b/eo/src/ga/make_genotype_ga.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_genotype.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 @@ -36,24 +36,24 @@ /////////////////// the bitstring //////////////// /* - * This fuction does the initialization of what's needed for a particular + * This fuction does the initialization of what's needed for a particular * genotype (here, bitstrings). - * It could be here tempatied only on the fitness, as it can be used to evolve + * It could be here tempatied only on the fitness, as it can be used to evolve * bitstrings with any fitness. - * However, for consistency reasons, it was finally chosen, as in - * the rest of EO, to templatize by the full EOT, as this eventually + * However, for consistency reasons, it was finally chosen, as in + * the rest of EO, to templatize by the full EOT, as this eventually * allows to choose the type of genotype at run time (see in es dir) * * It is instanciated in ga/ga.cpp - and incorporated in the ga/libga.a * - * It returns an eoInit > tha can later be used to initialize + * It returns an eoInit > tha can later be used to initialize * the population (see make_pop.h). * * It uses a parser (to get user parameters) and a state (to store the memory) * the last argument is to disambiguate the call upon different instanciations. * - * WARNING: that last argument will generally be the result of calling - * the default ctor of EOT, resulting in most cases in an EOT + * WARNING: that last argument will generally be the result of calling + * the default ctor of EOT, resulting in most cases in an EOT * that is ***not properly initialized*** * * @ingroup bitstring diff --git a/eo/src/ga/make_op.h b/eo/src/ga/make_op.h index 338557b5..8c46549f 100644 --- a/eo/src/ga/make_op.h +++ b/eo/src/ga/make_op.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op.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 @@ -57,9 +57,9 @@ * This is why the template is the complete EOT even though only the fitness * is actually templatized here: the following only applies to bitstrings * - * Note : the last parameter is an eoInit: if some operator needs some info + * Note : the last parameter is an eoInit: if some operator needs some info * about the gneotypes, the init has it all (e.g. bounds, ...) - * Simply do + * Simply do * EOT myEO; * _init(myEO); * and myEO is then an ACTUAL object @@ -78,12 +78,12 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init eoValueParam& operatorParam = _parser.createParam(std::string("SGA"), "operator", "Description of the operator (SGA only now)", 'o', "Variation Operators"); if (operatorParam.value() != std::string("SGA")) - throw std::runtime_error("Only SGA-like operator available right now\n"); + throw std::runtime_error("Only SGA-like operator available right now\n"); - // now we read Pcross and Pmut, + // now we read Pcross and Pmut, // the relative weights for all crossovers -> proportional choice // the relative weights for all mutations -> proportional choice - // and create the eoGenOp that is exactly + // and create the eoGenOp that is exactly // crossover with pcross + mutation with pmut eoValueParam& pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ); @@ -118,10 +118,10 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init bool bCross = true; if (onePointRateParam.value()+twoPointsRateParam.value()+uRateParam.value()==0) { - std::cerr << "Warning: no crossover" << std::endl; - bCross = false; + std::cerr << "Warning: no crossover" << std::endl; + bCross = false; } - + // Create the CombinedQuadOp eoPropCombinedQuadOp *ptCombinedQuadOp = NULL; eoQuadOp *ptQuad = NULL; @@ -129,12 +129,12 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init ptQuad = new eo1PtBitXover; _state.storeFunctor(ptQuad); ptCombinedQuadOp = new eoPropCombinedQuadOp(*ptQuad, onePointRateParam.value()); - + // uniform crossover for bitstring ptQuad = new eoUBitXover; _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, uRateParam.value()); - + // 2-points xover ptQuad = new eoNPtsBitXover; _state.storeFunctor(ptQuad); @@ -155,7 +155,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init // minimum check if ( (bitFlipRateParam.value() < 0) ) throw std::runtime_error("Invalid bitFlipRate"); - + eoValueParam & oneBitRateParam = _parser.createParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'd', "Variation Operators" ); // minimum check if ( (oneBitRateParam.value() < 0) ) @@ -165,10 +165,10 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init bool bMut = true; if (bitFlipRateParam.value()+oneBitRateParam.value()==0) { - std::cerr << "Warning: no mutation" << std::endl; - bMut = false; + std::cerr << "Warning: no mutation" << std::endl; + bMut = false; } - + // Create the CombinedMonOp eoPropCombinedMonOp *ptCombinedMonOp = NULL; eoMonOp *ptMon = NULL; @@ -180,7 +180,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, bitFlipRateParam.value()); // mutate exactly 1 bit per individual - ptMon = new eoDetBitFlip; + ptMon = new eoDetBitFlip; _state.storeFunctor(ptMon); ptCombinedMonOp->add(*ptMon, oneBitRateParam.value()); @@ -190,7 +190,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init // to simulate SGA (crossover with proba pCross + mutation with proba pMut // we must construct // a sequential combination of - // with proba 1, a proportional combination of + // with proba 1, a proportional combination of // a QuadCopy and our crossover // with proba pMut, our mutation @@ -205,7 +205,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init // now the sequential eoSequentialOp *op = new eoSequentialOp; _state.storeFunctor(op); - op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross op->add(*ptCombinedMonOp, pMutParam.value()); // that's it! diff --git a/eo/src/ga/make_op_ga.cpp b/eo/src/ga/make_op_ga.cpp index 8bed5a66..e3a53d65 100644 --- a/eo/src/ga/make_op_ga.cpp +++ b/eo/src/ga/make_op_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in make_op_ga.h * while the TEMPLATIZED code is define in make_op.h in the ga dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -59,4 +59,3 @@ eoGenOp >& make_op(eoParser& _parser, eoState& _stat { return do_make_op(_parser, _state, _init); } - diff --git a/eo/src/ga/make_pop_ga.cpp b/eo/src/ga/make_pop_ga.cpp index 2ab0b5cd..31927979 100644 --- a/eo/src/ga/make_pop_ga.cpp +++ b/eo/src/ga/make_pop_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of population init * of the library for ***BISTRING*** evolution inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in ga/make_ga.h * while the TEMPLATIZED code is define in make_pop.h in the src/do dir * @@ -59,5 +59,3 @@ eoPop >& make_pop(eoParser& _parser, eoState& _state { return do_make_pop(_parser, _state, _init); } - - diff --git a/eo/src/ga/make_run_ga.cpp b/eo/src/ga/make_run_ga.cpp index afdab3d9..d64d2b02 100644 --- a/eo/src/ga/make_run_ga.cpp +++ b/eo/src/ga/make_run_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_run_ga.cpp // (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 @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in make_run_ga.h * while the TEMPLATIZED code is define in make_run.h in the do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -63,4 +63,3 @@ void run_ea(eoAlgo >& _ga, eoPop::printOn(os); + EO::printOn(os); os << ' '; os << size() << ' '; @@ -133,13 +133,13 @@ public: { - EO::readFrom(is); + EO::readFrom(is); unsigned sz; is >> sz; - std::vector v(sz); + std::vector v(sz); unsigned i; @@ -149,24 +149,24 @@ public: is >> node; v[i] = node; } - parse_tree tmp(v.begin(), v.end()); - swap(tmp); + parse_tree tmp(v.begin(), v.end()); + swap(tmp); - /* - * old code which caused problems for paradisEO - * - * this can be removed once it has proved itself - EO::readFrom(is); + /* + * old code which caused problems for paradisEO + * + * this can be removed once it has proved itself + EO::readFrom(is); - // even older code - FType fit; + // even older code + FType fit; is >> fit; fitness(fit); std::copy(std::istream_iterator(is), std::istream_iterator(), back_inserter(*this)); - */ + */ } }; /** @example t-eoSymreg.cpp diff --git a/eo/src/gp/eoParseTreeDepthInit.h b/eo/src/gp/eoParseTreeDepthInit.h index 687c83f2..18dc55b9 100644 --- a/eo/src/gp/eoParseTreeDepthInit.h +++ b/eo/src/gp/eoParseTreeDepthInit.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoParseTreeDepthInit.h : initializor for eoParseTree class // (c) Maarten Keijzer 2000 Jeroen Eggermont 2002 @@ -8,20 +8,20 @@ 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 - mak@dhi.dk - jeggermo@liacs.nl - + mak@dhi.dk + jeggermo@liacs.nl + */ //----------------------------------------------------------------------------- @@ -48,17 +48,17 @@ template class eoParseTreeDepthInit : public eoInit< eoParseTree > { protected: - // a binary predicate for sorting - // hopefully this will work with M$VC++ 6.0 - struct lt_arity:public std::binary_function - { - bool operator()(const Node &_node1, const Node &_node2) { return (_node1.arity() < _node2.arity());}; - }; + // a binary predicate for sorting + // hopefully this will work with M$VC++ 6.0 + struct lt_arity:public std::binary_function + { + bool operator()(const Node &_node1, const Node &_node2) { return (_node1.arity() < _node2.arity());}; + }; public : typedef eoParseTree EoType; - + /** * Constructor * @param _max_depth The maximum depth of a tree @@ -66,18 +66,18 @@ class eoParseTreeDepthInit : public eoInit< eoParseTree > * @param _grow False results in a full tree, True result is a randomly grown tree * @param _ramped_half_and_half True results in Ramped Half and Half Initialization */ - eoParseTreeDepthInit( + eoParseTreeDepthInit( unsigned _max_depth, - const std::vector& _initializor, + const std::vector& _initializor, bool _grow = true, - bool _ramped_half_and_half = false) + bool _ramped_half_and_half = false) : eoInit(), - max_depth(_max_depth), - initializor(_initializor), - grow(_grow), - ramped_half_and_half(_ramped_half_and_half), - current_depth(_max_depth) + max_depth(_max_depth), + initializor(_initializor), + grow(_grow), + ramped_half_and_half(_ramped_half_and_half), + current_depth(_max_depth) { if(initializor.empty()) { @@ -88,82 +88,82 @@ class eoParseTreeDepthInit : public eoInit< eoParseTree > stable_sort(initializor.begin(), initializor.end(), lt_arity()); } /// My class name - virtual std::string className() const { return "eoParseTreeDepthInit"; }; + virtual std::string className() const { return "eoParseTreeDepthInit"; }; /**initialize a tree * @param _tree : the tree to be initialized */ void operator()(EoType& _tree) - { + { std::list sequence; generate(sequence, current_depth); parse_tree tmp(sequence.begin(), sequence.end()); _tree.swap(tmp); - - if(ramped_half_and_half) - { - if(grow) - { - if (current_depth > 2) - current_depth--; - else - current_depth = max_depth; - } - // change the grow method from 'grow' to 'full' or from 'full' to 'grow' - grow = !grow; - }; - - } + + if(ramped_half_and_half) + { + if(grow) + { + if (current_depth > 2) + current_depth--; + else + current_depth = max_depth; + } + // change the grow method from 'grow' to 'full' or from 'full' to 'grow' + grow = !grow; + }; + + } private : void generate(std::list& sequence, int the_max, int last_terminal = -1) { - if (last_terminal == -1) - { // check where the last terminal in the sequence resides + if (last_terminal == -1) + { // check where the last terminal in the sequence resides typename std::vector::iterator it; - for (it = initializor.begin(); it != initializor.end(); ++it) - { - if (it->arity() > 0) - break; - } - - last_terminal = it - initializor.begin(); - } + for (it = initializor.begin(); it != initializor.end(); ++it) + { + if (it->arity() > 0) + break; + } - if (the_max == 1) - { // generate terminals only - typename std::vector::iterator it = initializor.begin() + rng.random(last_terminal); - it->randomize(); - sequence.push_front(*it); - return; - } - - typename std::vector::iterator what_it; + last_terminal = it - initializor.begin(); + } - if (grow) - { - what_it = initializor.begin() + rng.random(initializor.size()); - } - else // full - { - what_it = initializor.begin() + last_terminal + rng.random(initializor.size() - last_terminal); - } + if (the_max == 1) + { // generate terminals only + typename std::vector::iterator it = initializor.begin() + rng.random(last_terminal); + it->randomize(); + sequence.push_front(*it); + return; + } + + typename std::vector::iterator what_it; + + if (grow) + { + what_it = initializor.begin() + rng.random(initializor.size()); + } + else // full + { + what_it = initializor.begin() + last_terminal + rng.random(initializor.size() - last_terminal); + } what_it->randomize(); - sequence.push_front(*what_it); + sequence.push_front(*what_it); - for (int i = 0; i < what_it->arity(); ++i) - generate(sequence, the_max - 1, last_terminal); + for (int i = 0; i < what_it->arity(); ++i) + generate(sequence, the_max - 1, last_terminal); } - unsigned max_depth; - std::vector initializor; - bool grow; - bool ramped_half_and_half; - unsigned current_depth; + unsigned max_depth; + std::vector initializor; + bool grow; + bool ramped_half_and_half; + unsigned current_depth; }; /** @@ -172,46 +172,46 @@ class eoParseTreeDepthInit : public eoInit< eoParseTree > * @param population_size the size of the population to be created * @param init_max_depth the initial maximum tree depth * @param initializor A std::vector containing the possible nodes - + \ingroup ParseTree */ template void eoInitRampedHalfAndHalf(eoPop< eoParseTree > &pop, unsigned int population_size, unsigned int init_max_depth, std::vector &initializor) { - typedef eoParseTree EoType; - typedef eoPop< EoType > Pop; - - unsigned int M = init_max_depth - 1; - unsigned int part_pop_size = population_size / (2*M); - unsigned int m=0; + typedef eoParseTree EoType; + typedef eoPop< EoType > Pop; - std::cerr << "EO WARNING: Ramped Half and Half Initialization is now supported by eoParseTreeDepthInit." << std::endl; - std::cerr << " This function is now obsolete and might be removed in the future so you should"<< std::endl; - std::cerr << " update your code to use: " << std::endl << std::endl; - std::cerr << " eoParseTreeDepthInit( _max_depth, _initializer, bool _grow, bool _ramped_half_and_half)" << std::endl << std::endl; - - pop.clear(); - - // initialize with Depth's (D) -> 2 - for(m=init_max_depth; m >= 2; m--) - { - eoParseTreeDepthInit grow_initializer(m, initializor, true); - Pop grow(part_pop_size, grow_initializer); - pop.insert(pop.begin(), grow.begin(), grow.end()); - - eoParseTreeDepthInit full_initializer(m, initializor, false); - Pop full(part_pop_size, full_initializer); - pop.insert(pop.begin(), full.begin(), full.end()); - } - - bool g = true; - while (pop.size() < population_size) - { - eoParseTreeDepthInit initializer(init_max_depth, initializor, g); - Pop p(1, initializer); - pop.insert(pop.begin(), p.begin(), p.end()); - g= !g; - } + unsigned int M = init_max_depth - 1; + unsigned int part_pop_size = population_size / (2*M); + unsigned int m=0; + + std::cerr << "EO WARNING: Ramped Half and Half Initialization is now supported by eoParseTreeDepthInit." << std::endl; + std::cerr << " This function is now obsolete and might be removed in the future so you should"<< std::endl; + std::cerr << " update your code to use: " << std::endl << std::endl; + std::cerr << " eoParseTreeDepthInit( _max_depth, _initializer, bool _grow, bool _ramped_half_and_half)" << std::endl << std::endl; + + pop.clear(); + + // initialize with Depth's (D) -> 2 + for(m=init_max_depth; m >= 2; m--) + { + eoParseTreeDepthInit grow_initializer(m, initializor, true); + Pop grow(part_pop_size, grow_initializer); + pop.insert(pop.begin(), grow.begin(), grow.end()); + + eoParseTreeDepthInit full_initializer(m, initializor, false); + Pop full(part_pop_size, full_initializer); + pop.insert(pop.begin(), full.begin(), full.end()); + } + + bool g = true; + while (pop.size() < population_size) + { + eoParseTreeDepthInit initializer(init_max_depth, initializor, g); + Pop p(1, initializer); + pop.insert(pop.begin(), p.begin(), p.end()); + g= !g; + } } diff --git a/eo/src/gp/eoParseTreeOp.h b/eo/src/gp/eoParseTreeOp.h index 58824eea..0b623f3d 100644 --- a/eo/src/gp/eoParseTreeOp.h +++ b/eo/src/gp/eoParseTreeOp.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoParseTreeOp.h : crossover and mutation operator for the eoParseTree class // (c) Maarten Keijzer 2000 for eoSubtreeXOver, eoBranchMutation @@ -10,18 +10,18 @@ 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 - mak@dhi.dk + mak@dhi.dk jeggermo@liacs.nl */ //----------------------------------------------------------------------------- @@ -34,8 +34,8 @@ #include -/** eoSubtreeXOver --> subtree xover -\class eoSubtreeXOver eoParseTreeOp.h gp/eoParseTreeOp.h +/** eoSubtreeXOver --> subtree xover +\class eoSubtreeXOver eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ template @@ -63,23 +63,23 @@ public: */ bool operator()(EoType & _eo1, EoType & _eo2 ) { - int i = rng.random(_eo1.size()); - int j = rng.random(_eo2.size()); + int i = rng.random(_eo1.size()); + int j = rng.random(_eo2.size()); - typename parse_tree::subtree tmp = _eo1[i]; - _eo1[i] = _eo2[j]; // insert subtree - _eo2[j] = tmp; + typename parse_tree::subtree tmp = _eo1[i]; + _eo1[i] = _eo2[j]; // insert subtree + _eo2[j] = tmp; + + _eo1.pruneTree(max_length); + _eo2.pruneTree(max_length); - _eo1.pruneTree(max_length); - _eo2.pruneTree(max_length); - return true; } private: unsigned max_length; }; -/** eoBranchMutation --> replace a subtree with a randomly created subtree +/** eoBranchMutation --> replace a subtree with a randomly created subtree \class eoBranchMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ @@ -97,29 +97,29 @@ public: eoBranchMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// the class name virtual std::string className() const { return "eoBranchMutation"; }; /// Dtor virtual ~eoBranchMutation() {}; - + /** * Mutate an individual * @param _eo1 The individual that is to be changed */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); + int i = rng.random(_eo1.size()); EoType eo2; initializer(eo2); - int j = rng.random(eo2.size()); + int j = rng.random(eo2.size()); - _eo1[i] = eo2[j]; // insert subtree + _eo1[i] = eo2[j]; // insert subtree - _eo1.pruneTree(max_length); + _eo1.pruneTree(max_length); return true; } @@ -130,7 +130,7 @@ private : eoInit& initializer; }; -// Additional Mutation operators from +// Additional Mutation operators from // TITLE:"Genetic Programming~An Introduction" // AUTHORS: Banzhaf, Nordin, Keller, Francone // ISBN: 3-920993-58-6 @@ -138,8 +138,8 @@ private : // // For the eoParseTree class -/** eoPointMutation --> replace a Node with a Node of the same arity -\class eoPointMutation eoParseTreeOp.h gp/eoParseTreeOp.h +/** eoPointMutation --> replace a Node with a Node of the same arity +\class eoPointMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ @@ -157,7 +157,7 @@ public: eoPointMutation( std::vector& _initializor) : eoMonOp(), initializor(_initializor) {}; - + /// the class name virtual std::string className() const { return "eoPointMutation"; }; @@ -170,32 +170,32 @@ public: */ bool operator()(EoType& _eo1 ) { - // select a random node i that is to be mutated - int i = rng.random(_eo1.size()); - // request the arity of the node that is to be replaced - int arity = _eo1[i].arity(); - - int j=0; - - do - { - j = rng.random(initializor.size()); - - }while ((initializor[j].arity() != arity)); - - _eo1[i] = initializor[j]; - - - - return true; + // select a random node i that is to be mutated + int i = rng.random(_eo1.size()); + // request the arity of the node that is to be replaced + int arity = _eo1[i].arity(); + + int j=0; + + do + { + j = rng.random(initializor.size()); + + }while ((initializor[j].arity() != arity)); + + _eo1[i] = initializor[j]; + + + + return true; } private : - std::vector& initializor; + std::vector& initializor; }; -/** eoExpansionMutation --> replace a terminal with a randomly created subtree +/** eoExpansionMutation --> replace a terminal with a randomly created subtree \class eoExpansionMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ @@ -206,7 +206,7 @@ class eoExpansionMutation: public eoMonOp< eoParseTree > public: typedef eoParseTree EoType; - + /** * Constructor * @param _init An instantiation of eoGpDepthInitializer @@ -215,7 +215,7 @@ public: eoExpansionMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// The class name virtual std::string className() const { return "eoExpansionMutation"; }; @@ -227,33 +227,33 @@ public: */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); - // look for a terminal + int i = rng.random(_eo1.size()); + // look for a terminal while (_eo1[i].arity() != 0) - { - i= rng.random(_eo1.size()); - }; - - // create a new tree to - EoType eo2; - // make sure we get a tree with more than just a terminal - do - { - initializer(eo2); - }while(eo2.size() == 1); - - int j = rng.random(eo2.size()); - // make sure we select a subtree (and not a terminal) - while((eo2[j].arity() == 0)) - { - j = rng.random(eo2.size()); - }; - + { + i= rng.random(_eo1.size()); + }; - _eo1[i] = eo2[j]; // insert subtree + // create a new tree to + EoType eo2; + // make sure we get a tree with more than just a terminal + do + { + initializer(eo2); + }while(eo2.size() == 1); + + int j = rng.random(eo2.size()); + // make sure we select a subtree (and not a terminal) + while((eo2[j].arity() == 0)) + { + j = rng.random(eo2.size()); + }; + + + _eo1[i] = eo2[j]; // insert subtree + + _eo1.pruneTree(max_length); - _eo1.pruneTree(max_length); - return true; } @@ -294,29 +294,29 @@ public: */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); - // look for a subtree + int i = rng.random(_eo1.size()); + // look for a subtree while ((_eo1[i].arity() == 0) && (_eo1.size() > 1)) - { - i= rng.random(_eo1.size()); - }; - - // create a new tree to - EoType eo2; - initializer(eo2); - - int j = rng.random(eo2.size()); - // make sure we select a subtree (and not a terminal) - while(eo2[j].arity() != 0) - { - j = rng.random(eo2.size()); - }; + { + i= rng.random(_eo1.size()); + }; + + // create a new tree to + EoType eo2; + initializer(eo2); + + int j = rng.random(eo2.size()); + // make sure we select a subtree (and not a terminal) + while(eo2[j].arity() != 0) + { + j = rng.random(eo2.size()); + }; + + _eo1[i] = eo2[j]; // insert subtree + + // we don't have to prune because the subtree is always smaller + _eo1.pruneTree(max_length); - _eo1[i] = eo2[j]; // insert subtree - - // we don't have to prune because the subtree is always smaller - _eo1.pruneTree(max_length); - return true; } @@ -327,11 +327,11 @@ private : }; -/** eoHoistMutation --> replace the individual with one of its subtree's +/** eoHoistMutation --> replace the individual with one of its subtree's \class eoHoistMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ - + template class eoHoistMutation: public eoMonOp< eoParseTree > { @@ -345,7 +345,7 @@ public: eoHoistMutation() : eoMonOp() {}; - + /// The class name virtual std::string className() const { return "eoHoistMutation"; }; @@ -357,17 +357,17 @@ public: */ bool operator()(EoType& _eo1 ) { - - - // select a hoist point - int i = rng.random(_eo1.size()); - // and create a new tree - EoType eo2(_eo1[i]); - - // we don't have to prune because the new tree is always smaller - //_eo1.pruneTree(max_length); - - _eo1 = eo2; + + + // select a hoist point + int i = rng.random(_eo1.size()); + // and create a new tree + EoType eo2(_eo1[i]); + + // we don't have to prune because the new tree is always smaller + //_eo1.pruneTree(max_length); + + _eo1 = eo2; return true; } diff --git a/eo/src/gp/eoStParseTreeDepthInit.h b/eo/src/gp/eoStParseTreeDepthInit.h index 43c4c2a2..37b17887 100644 --- a/eo/src/gp/eoStParseTreeDepthInit.h +++ b/eo/src/gp/eoStParseTreeDepthInit.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoStParseTreeDepthInit.h : initializor strongly type GP // (c) Jeroen Eggermont 2001 @@ -8,19 +8,19 @@ 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 - jeggermo@liacs.nl - + jeggermo@liacs.nl + */ //----------------------------------------------------------------------------- @@ -49,7 +49,7 @@ using namespace gp_parse_tree; individual but now each node class must have two additional functions. \li int type(void) which returns the return type of the node \li int type(int child) which returns the required type for child 0, 1 or 2 - + Pruning strongly typed trees is not possible at the moment. \ingroup Representations @@ -66,7 +66,7 @@ class eoStParseTreeDepthInit : public eoInit< eoParseTree > public : typedef eoParseTree EoType; - + /** * Constructor * @param _max_depth The maximum depth of a tree @@ -74,121 +74,121 @@ class eoStParseTreeDepthInit : public eoInit< eoParseTree > * @param _return_type (JD_2010-11-09: don't know the use of this parameter, maybe to force implicit template instanciation?) * @param _grow False results in a full tree, True result is a randomly grown tree */ - eoStParseTreeDepthInit( + eoStParseTreeDepthInit( unsigned _max_depth, - const std::vector& _node, - const int& _return_type, + const std::vector& _node, + const int& _return_type, bool _grow = true) : eoInit(), - max_depth(_max_depth), - return_type(_return_type), - grow(_grow) + max_depth(_max_depth), + return_type(_return_type), + grow(_grow) { if(_node.empty()) { throw std::logic_error("eoStParseTreeDepthInit: uhm, wouldn't you rather give a non-empty set of Nodes?"); } - - + + unsigned int i=0; int arity=0; int type=0; std::vector node_vector; for(i=0; i < _node.size(); i++) { - arity = _node[i].arity(); - type = _node[i].type(); - if(arity==0) - { - node_vector = node[type][TERMINAL]; - node_vector.push_back(_node[i]); - node[type][TERMINAL]= node_vector; - } - else - //if (arity != 0) // non-terminal - { - node_vector = node[type][NONTERMINAL]; - node_vector.push_back(_node[i]); - node[type][NONTERMINAL] = node_vector; - } - node_vector = node[type][ALL]; - node_vector.push_back(_node[i]); - node[type][ALL] = node_vector; - + arity = _node[i].arity(); + type = _node[i].type(); + if(arity==0) + { + node_vector = node[type][TERMINAL]; + node_vector.push_back(_node[i]); + node[type][TERMINAL]= node_vector; + } + else + //if (arity != 0) // non-terminal + { + node_vector = node[type][NONTERMINAL]; + node_vector.push_back(_node[i]); + node[type][NONTERMINAL] = node_vector; + } + node_vector = node[type][ALL]; + node_vector.push_back(_node[i]); + node[type][ALL] = node_vector; + } - + } /// My class name - virtual std::string className() const { return "eoStParseTreeDepthInit"; }; + virtual std::string className() const { return "eoStParseTreeDepthInit"; }; /**initialize a tree * @param _tree : the tree to be initialized */ void operator()(EoType& _tree) - { - std::list sequence; - bool good_tree = false; - do - { - sequence.clear(); - good_tree = generate(sequence, max_depth, return_type); - }while (!good_tree); + { + std::list sequence; + bool good_tree = false; + do + { + sequence.clear(); + good_tree = generate(sequence, max_depth, return_type); + }while (!good_tree); - parse_tree tmp(sequence.begin(), sequence.end()); - _tree.swap(tmp); - } + parse_tree tmp(sequence.begin(), sequence.end()); + _tree.swap(tmp); + } private : bool generate(std::list& sequence, int the_max, int request_type) { - - int selected=0; - bool ok = true; - - if (the_max == 1) - { // generate terminals only - if( node[request_type][TERMINAL].empty() ) // no possible terminal node of this type - return false; // we have an invalid tree - else - { - selected = rng.random((node[request_type][TERMINAL]).size()); - sequence.push_front(node[request_type][TERMINAL][selected]); - return true; - } - - } - - int arity=0; - if (grow) - { - selected = rng.random((node[request_type][ALL]).size()); - arity = node[request_type][ALL][selected].arity(); - sequence.push_front(node[request_type][ALL][selected]); - for (int i = 0; i < arity; ++i) - ok &= generate(sequence, the_max - 1, node[request_type][ALL][selected].type(i)); - } - else // full - { - selected = rng.random((node[request_type][NONTERMINAL]).size()); - arity = node[request_type][NONTERMINAL][selected].arity(); - sequence.push_front(node[request_type][NONTERMINAL][selected]); - for (int i = 0; i < arity; ++i) - ok &=generate(sequence, the_max - 1, node[request_type][NONTERMINAL][selected].type(i)); - } - - return ok; - + + int selected=0; + bool ok = true; + + if (the_max == 1) + { // generate terminals only + if( node[request_type][TERMINAL].empty() ) // no possible terminal node of this type + return false; // we have an invalid tree + else + { + selected = rng.random((node[request_type][TERMINAL]).size()); + sequence.push_front(node[request_type][TERMINAL][selected]); + return true; + } + + } + + int arity=0; + if (grow) + { + selected = rng.random((node[request_type][ALL]).size()); + arity = node[request_type][ALL][selected].arity(); + sequence.push_front(node[request_type][ALL][selected]); + for (int i = 0; i < arity; ++i) + ok &= generate(sequence, the_max - 1, node[request_type][ALL][selected].type(i)); + } + else // full + { + selected = rng.random((node[request_type][NONTERMINAL]).size()); + arity = node[request_type][NONTERMINAL][selected].arity(); + sequence.push_front(node[request_type][NONTERMINAL][selected]); + for (int i = 0; i < arity; ++i) + ok &=generate(sequence, the_max - 1, node[request_type][NONTERMINAL][selected].type(i)); + } + + return ok; + } - - unsigned max_depth; - std::map < int, std::map < int, std::vector > > node; + + unsigned max_depth; + std::map < int, std::map < int, std::vector > > node; int return_type; - bool grow; + bool grow; }; #endif diff --git a/eo/src/gp/eoStParseTreeOp.h b/eo/src/gp/eoStParseTreeOp.h index eb0d1023..88020448 100644 --- a/eo/src/gp/eoStParseTreeOp.h +++ b/eo/src/gp/eoStParseTreeOp.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoStParseTreeOp.h : crossover and mutation operators for the strongly typed GP // (c) Jeroen Eggermont 2001 for other mutation operators @@ -9,18 +9,18 @@ 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 - mak@dhi.dk + mak@dhi.dk jeggermo@liacs.nl */ //----------------------------------------------------------------------------- @@ -40,17 +40,17 @@ template void get_possible_nodes(const EOT &_eo, std::vector &possible_nodes, const int type) { - int n=0; - possible_nodes.clear(); - // collect the possible crossover points in _eo (nodes with the same type) - for(n=0; n < _eo.size(); n++) - if (type == _eo[n]->type()) - possible_nodes.push_back(n); -} + int n=0; + possible_nodes.clear(); + // collect the possible crossover points in _eo (nodes with the same type) + for(n=0; n < _eo.size(); n++) + if (type == _eo[n]->type()) + possible_nodes.push_back(n); +} /** eoStSubtreeXOver --> subtree xover for strongly typed tree-based genetic programming -\class eoStSubtreeXOver eoStParseTreeOp.h gp/eoStParseTreeOp.h +\class eoStSubtreeXOver eoStParseTreeOp.h gp/eoStParseTreeOp.h \ingroup StParseTree */ template @@ -78,54 +78,54 @@ public: */ bool operator()(EoType & _eo1, EoType & _eo2 ) { - int i = 0; - std::vector nodes; - int n = 0; - int type = 0; - int j = 0; - std::set test; - do - { - do // select a random node in _eo1 as crossover point, and check if we didn't try it already - { - i = rng.random(_eo1.size()); - }while(test.count(i) > 0); - - test.insert(i); - - type = _eo1[i]->type(); - - get_possible_nodes(_eo2, nodes, type); - - }while(nodes.empty() && (test.size() < _eo1.size())); - - if (nodes.empty()) // we failed to select a crossover point but tried all points (test.size() == _eo1.size()). - return true; // should this be false ?? + int i = 0; + std::vector nodes; + int n = 0; + int type = 0; + int j = 0; + std::set test; + do + { + do // select a random node in _eo1 as crossover point, and check if we didn't try it already + { + i = rng.random(_eo1.size()); + }while(test.count(i) > 0); - // we did find at least one possible crossover point in _eo2 - - n = rng.random(nodes.size()); - j = nodes[n]; - + test.insert(i); - - typename eoParseTree::subtree tmp = _eo1[i]; - _eo1[i] = _eo2[j]; // insert subtree - _eo2[j] = tmp; + type = _eo1[i]->type(); - // we can't prune anymore - /* + get_possible_nodes(_eo2, nodes, type); + + }while(nodes.empty() && (test.size() < _eo1.size())); + + if (nodes.empty()) // we failed to select a crossover point but tried all points (test.size() == _eo1.size()). + return true; // should this be false ?? + + // we did find at least one possible crossover point in _eo2 + + n = rng.random(nodes.size()); + j = nodes[n]; + + + + typename eoParseTree::subtree tmp = _eo1[i]; + _eo1[i] = _eo2[j]; // insert subtree + _eo2[j] = tmp; + + // we can't prune anymore + /* _eo1.pruneTree(max_length); _eo2.pruneTree(max_length); - */ - - return true; + */ + + return true; } private: unsigned max_length; }; -/** eoStBranchMutation --> replace a strongly typed subtree with a randomly created strongly typed subtree +/** eoStBranchMutation --> replace a strongly typed subtree with a randomly created strongly typed subtree \class eoStBranchMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h \ingroup StParseTree */ @@ -143,42 +143,42 @@ public: eoStBranchMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// the class name virtual std::string className() const { return "eoStBranchMutation"; }; /// Dtor virtual ~eoStBranchMutation() {}; - + /** * Mutate an individual * @param _eo1 The individual that is to be changed */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); - std::vector nodes; - int type = _eo1[i]->type(); - int j=0; - int n=0; + int i = rng.random(_eo1.size()); + std::vector nodes; + int type = _eo1[i]->type(); + int j=0; + int n=0; - EoType eo2; - - do - { - initializer(eo2); - get_possible_nodes(eo2, nodes, type); - }while (nodes.empty()); + EoType eo2; - n = rng.random(nodes.size()); - j = nodes[n]; - - _eo1[i] = eo2[j]; // insert subtree - - // no more pruning - /* - _eo1.pruneTree(max_length); - */ + do + { + initializer(eo2); + get_possible_nodes(eo2, nodes, type); + }while (nodes.empty()); + + n = rng.random(nodes.size()); + j = nodes[n]; + + _eo1[i] = eo2[j]; // insert subtree + + // no more pruning + /* + _eo1.pruneTree(max_length); + */ return true; } @@ -208,22 +208,22 @@ public: eoStPointMutation( std::vector& _node) : eoMonOp() { - unsigned int i=0; + unsigned int i=0; int arity=0; int type=0; std::vector node_vector; for(i=0; i < _node.size(); i++) { - arity = _node[i].arity(); - type = _node[i].type(); - - node_vector = node[type][arity]; - node_vector.push_back(_node[i]); - node[type][arity]= node_vector; - + arity = _node[i].arity(); + type = _node[i].type(); + + node_vector = node[type][arity]; + node_vector.push_back(_node[i]); + node[type][arity]= node_vector; + }; }; - + /// the class name virtual std::string className() const { return "eoStPointMutation"; }; @@ -236,24 +236,24 @@ public: */ bool operator()(EoType& _eo1 ) { - // select a random node i that is to be mutated - int i = rng.random(_eo1.size()); - int arity = _eo1[i].arity(); - int type = _eo1[i]->type(); - int j = rng.random(node[type][arity].size()); + // select a random node i that is to be mutated + int i = rng.random(_eo1.size()); + int arity = _eo1[i].arity(); + int type = _eo1[i]->type(); + int j = rng.random(node[type][arity].size()); - - _eo1[i] = node[type][arity][j]; - return true; + + _eo1[i] = node[type][arity][j]; + return true; } private : - - std::map < int, std::map < int, std::vector > > node; + + std::map < int, std::map < int, std::vector > > node; }; - - /** eoStHoistMutation --> replace the individual with one of its strongly typed subtree's + + /** eoStHoistMutation --> replace the individual with one of its strongly typed subtree's \class eoStHoistMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h \ingroup StParseTree */ @@ -271,13 +271,13 @@ public: eoStHoistMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// the class name virtual std::string className() const { return "eoStHoistMutation"; }; /// Dtor virtual ~eoStHoistMutation() {}; - + /** * Mutate an individual * @param _eo1 The individual that is to be changed @@ -285,19 +285,19 @@ public: bool operator()(EoType& _eo1 ) { - std::vector nodes; - // get the type of the current tree - int type = _eo1[ _eo1.size() - 1 ]->type(); + std::vector nodes; + // get the type of the current tree + int type = _eo1[ _eo1.size() - 1 ]->type(); - get_possible_nodes(_eo1, nodes, type); - - // select a subtree-node to replace the current tree - int n = rng.random(nodes.size()); - int i = nodes[n]; - - EoType eo2(_eo1[i]); - - _eo1 = eo2; + get_possible_nodes(_eo1, nodes, type); + + // select a subtree-node to replace the current tree + int n = rng.random(nodes.size()); + int i = nodes[n]; + + EoType eo2(_eo1[i]); + + _eo1 = eo2; return true; } diff --git a/eo/src/gp/node_pool.h b/eo/src/gp/node_pool.h index e3b41b8a..8935e7e2 100644 --- a/eo/src/gp/node_pool.h +++ b/eo/src/gp/node_pool.h @@ -1,13 +1,13 @@ /** * Pool allocator for the subtree and parse tree classes (homebrew and not compliant to ANSI allocator requirements) - * (c) copyright Maarten Keijzer 1999, 2000 + * (c) copyright Maarten Keijzer 1999, 2000 - * Permission to copy, use, modify, sell and distribute this software is granted provided + * Permission to copy, use, modify, sell and distribute this software is granted provided * this copyright notice appears in all copies. This software is provided "as is" without * express or implied warranty, and with no claim as to its suitability for * any purpose. - + * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. @@ -21,7 +21,7 @@ class MemPool { public : - + MemPool(unsigned int sz) : esize(sz(p)->next = + reinterpret_cast(p)->next = reinterpret_cast(p + esize); } - + reinterpret_cast(last)->next = 0; head = reinterpret_cast(start); } @@ -91,15 +91,15 @@ template class Node_alloc { public : - - T* allocate(void) + + T* allocate(void) { T* t = static_cast(mem.allocate()); t = new (t) T; return t; } - - T* construct(const T& org) + + T* construct(const T& org) { T* t = static_cast(mem.allocate()); t = new (t) T(org); @@ -117,7 +117,7 @@ private : }; -template +template class Standard_alloc { public : @@ -130,7 +130,7 @@ public : return new T [arity]; } - + T* construct(size_t arity, T* org) { if (arity == 0) @@ -154,7 +154,7 @@ public : }; -template +template class Standard_Node_alloc { public : @@ -270,19 +270,19 @@ public : switch(arity) { case 0: return; - case 3 : + case 3 : { t[2].~T(); t[1].~T(); t[0].~T(); mem3.deallocate(static_cast(t)); return; } - case 2 : + case 2 : { t[1].~T(); t[0].~T(); mem2.deallocate(static_cast(t)); return; } - case 1 : + case 1 : { t[0].~T(); mem1.deallocate(static_cast(t)); @@ -295,7 +295,7 @@ public : } } } - + private : static MemPool mem1; diff --git a/eo/src/gp/parse_tree.h b/eo/src/gp/parse_tree.h index 8437c0c7..84ec04d3 100644 --- a/eo/src/gp/parse_tree.h +++ b/eo/src/gp/parse_tree.h @@ -23,22 +23,22 @@ ****** Arity ****** \code - int arity(void) const + int arity(void) const \endcode - Note: the default constructor of a Node should provide a - Node with arity 0! + Note: the default constructor of a Node should provide a + Node with arity 0! ****** Evaluation ****** A parse_tree is evaluated through one of it's apply() members: - 1) parse_tree::apply(RetVal) + 1) parse_tree::apply(RetVal) - is the simplest evaluation, it will call + is the simplest evaluation, it will call \code - RetVal Node::operator()(RetVal, subtree::const_iterator) + RetVal Node::operator()(RetVal, subtree::const_iterator) \endcode (Unfortunately the first RetVal argument is mandatory (although you @@ -49,7 +49,7 @@ error. That is why you have to call tree.apply(double()) instead.) - 2) parse_tree::apply(RetVal v, It values) + 2) parse_tree::apply(RetVal v, It values) will call: @@ -58,10 +58,10 @@ \endcode where It is whatever type you desire (most of the time - this will be a std::vector containing the values of your - variables); + this will be a std::vector containing the values of your + variables); - 3) parse_tree::apply(RetVal, It values, It2 moreValues) + 3) parse_tree::apply(RetVal, It values, It2 moreValues) will call: @@ -69,26 +69,26 @@ RetVal Node::operator()(RetVal, subtree<... , It values, It2 moreValues) \endcode - although I do not see the immediate use of this, however... + although I do not see the immediate use of this, however... - 4) parse_tree::apply(RetVal, It values, It2 args, It3 adfs) + 4) parse_tree::apply(RetVal, It values, It2 args, It3 adfs) - that calls: + that calls: \code RetVal Node::operator()(subtree<... , It values, It2 args, It3 adfs) \endcode - can be useful for implementing adfs. + can be useful for implementing adfs. - In general it is a good idea to leave the specifics of the - arguments open so that different ways of evaluation remain - possible. Implement the simplest eval as: + In general it is a good idea to leave the specifics of the + arguments open so that different ways of evaluation remain + possible. Implement the simplest eval as: \code - template - RetVal operator()(RetVal dummy, It begin) const + template + RetVal operator()(RetVal dummy, It begin) const \endcode ****** Internal Structure ****** @@ -99,10 +99,10 @@ The nodes are stored in a tree like : - node4 - / \ - node3 node2 - / \ + node4 + / \ + node3 node2 + / \ node1 node0 where nodes 2 and 4 have arity 2 and nodes 0,1 and 3 arity 0 (terminals) @@ -129,9 +129,9 @@ will not crash and result in a tree structured as: - node4 - / \ - node3 node0 + node4 + / \ + node3 node0 Note that the rank numbers no longer specify their place in the tree: @@ -212,10 +212,10 @@ public : typedef subtree* iterator; typedef const subtree* const_iterator; - /* Constructors, assignments */ + /* Constructors, assignments */ subtree(void) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - {} + {} subtree(const subtree& s) : content(node_allocator.allocate()), args(0), @@ -228,7 +228,7 @@ public : } subtree(const T& t) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - { copy(t); } + { copy(t); } template subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) @@ -239,57 +239,57 @@ public : virtual ~subtree(void) { tree_allocator.deallocate(args, arity()); node_allocator.deallocate(content); } subtree& operator=(const subtree& s) - { - if (s.get_root() == get_root()) + { + if (s.get_root() == get_root()) { // from the same tree, maybe a child. Don't take any chances subtree anotherS = s; return copy(anotherS); } - copy(s); + copy(s); updateAfterInsert(); return *this; - } + } subtree& operator=(const T& t) { copy(t); updateAfterInsert(); return *this; } - /* Access to the nodes */ + /* Access to the nodes */ T& operator*(void) { return *content; } const T& operator*(void) const { return *content; } T* operator->(void) { return content; } const T* operator->(void) const { return content; } - /* Equality, inequality check, Node needs to implement operator== */ + /* Equality, inequality check, Node needs to implement operator== */ - bool operator==(const subtree& other) const - { - if (! (*content == *other.content)) - return false; + bool operator==(const subtree& other) const + { + if (! (*content == *other.content)) + return false; - for (int i = 0; i < arity(); i++) - { - if (!(args[i] == other.args[i])) - return false; - } + for (int i = 0; i < arity(); i++) + { + if (!(args[i] == other.args[i])) + return false; + } - return true; - } + return true; + } - bool operator !=(const subtree& other) const - { - return !operator==(other); - } + bool operator !=(const subtree& other) const + { + return !operator==(other); + } - /* Arity */ + /* Arity */ int arity(void) const { return content->arity(); } - /* Evaluation with an increasing amount of user defined arguments */ - template - void apply(RetVal& v) const { (*content)(v, begin()); } + /* Evaluation with an increasing amount of user defined arguments */ + template + void apply(RetVal& v) const { (*content)(v, begin()); } - template - void apply(RetVal& v, It values) const + template + void apply(RetVal& v, It values) const { (*content)(v, begin(), values); } @@ -302,12 +302,12 @@ public : /* template - void apply(RetVal& v, It values, It2 moreValues) const - { (*content)(v, begin(), values, moreValues); } + void apply(RetVal& v, It values, It2 moreValues) const + { (*content)(v, begin(), values, moreValues); } - template - void apply(RetVal& v, It values, It2 moreValues, It3 evenMoreValues) const - { (*content)(v, begin(), values, moreValues, evenMoreValues); } + template + void apply(RetVal& v, It values, It2 moreValues, It3 evenMoreValues) const + { (*content)(v, begin(), values, moreValues, evenMoreValues); } */ template @@ -338,7 +338,7 @@ public : } } - /* Iterators */ + /* Iterators */ iterator begin(void) { return args; } const_iterator begin(void) const { return args; } @@ -346,10 +346,10 @@ public : iterator end(void) { return args + arity(); } const_iterator end(void) const { return args + arity(); } - subtree& operator[](int i) { return *(begin() + i); } - const subtree& operator[](int i) const { return *(begin() + i); } + subtree& operator[](int i) { return *(begin() + i); } + const subtree& operator[](int i) const { return *(begin() + i); } - /* Some statistics */ + /* Some statistics */ size_t size(void) const { return _size; } @@ -370,11 +370,11 @@ public : subtree* get_parent(void) { return parent; } const subtree* get_parent(void) const { return parent; } - void clear(void) - { tree_allocator.deallocate(args, arity()); args = 0; *content = T(); parent = 0; _cumulative_size = 0; _depth = 0; _size = 0; } + void clear(void) + { tree_allocator.deallocate(args, arity()); args = 0; *content = T(); parent = 0; _cumulative_size = 0; _depth = 0; _size = 0; } - void swap(subtree& y) - { + void swap(subtree& y) + { do_the_swap(content, y.content); do_the_swap(args, y.args); @@ -386,12 +386,12 @@ public : do_the_swap(_cumulative_size, y._cumulative_size); do_the_swap(_depth, y._depth); do_the_swap(_size, y._size); - updateAfterInsert(); - } + updateAfterInsert(); + } protected : - virtual void updateAfterInsert(void) + virtual void updateAfterInsert(void) { _depth = 0; _size = 1; @@ -419,7 +419,7 @@ private : // else for (int i = arity() - 1; i >= 0; --i) - { + { if (which < args[i]._cumulative_size) return args[i].imp_select_cumulative(which); which -= args[i]._cumulative_size; @@ -434,7 +434,7 @@ private : return *this; for (int i = arity() - 1; i >= 0; --i) - { + { unsigned c_size = args[i].size(); if (which < c_size) return args[i].imp_get_node(which); @@ -454,34 +454,34 @@ private : } subtree& copy(const subtree& s) { - int old_arity = arity(); + int old_arity = arity(); - int new_arity = s.arity(); + int new_arity = s.arity(); - if (new_arity != old_arity) - { - tree_allocator.deallocate(args, old_arity); + if (new_arity != old_arity) + { + tree_allocator.deallocate(args, old_arity); args = tree_allocator.allocate(new_arity); - } + } - switch(new_arity) - { - case 3 : args[2].copy(s.args[2]); args[2].parent = this; // no break! - case 2 : args[1].copy(s.args[1]); args[1].parent = this; - case 1 : args[0].copy(s.args[0]); args[0].parent = this; - case 0 : break; - default : - { - for (int i = 0; i < new_arity; ++i) - { - args[i].copy(s.args[i]); + switch(new_arity) + { + case 3 : args[2].copy(s.args[2]); args[2].parent = this; // no break! + case 2 : args[1].copy(s.args[1]); args[1].parent = this; + case 1 : args[0].copy(s.args[0]); args[0].parent = this; + case 0 : break; + default : + { + for (int i = 0; i < new_arity; ++i) + { + args[i].copy(s.args[i]); args[i].parent = this; - } - } - } + } + } + } - *content = *s.content; + *content = *s.content; _size = s._size; _depth = s._depth; _cumulative_size = s._cumulative_size; @@ -493,66 +493,66 @@ private : { int oldArity = arity(); - if (content != &t) + if (content != &t) *content = t; - else - oldArity = -1; + else + oldArity = -1; - int ar = arity(); + int ar = arity(); - if (ar != oldArity) - { + if (ar != oldArity) + { if (oldArity != -1) - tree_allocator.deallocate(args, oldArity); + tree_allocator.deallocate(args, oldArity); args = tree_allocator.allocate(ar); //if (ar > 0) - // args = new subtree [ar]; - //else - // args = 0; - } + // args = new subtree [ar]; + //else + // args = 0; + } adopt(); updateAfterInsert(); - return *this; + return *this; } - void disown(void) - { - switch(arity()) - { - case 3 : args[2].parent = 0; // no break! - case 2 : args[1].parent = 0; - case 1 : args[0].parent = 0; break; - case 0 : break; - default : - { - for (iterator it = begin(); it != end(); ++it) - { - it->parent = 0; - } - } - } + void disown(void) + { + switch(arity()) + { + case 3 : args[2].parent = 0; // no break! + case 2 : args[1].parent = 0; + case 1 : args[0].parent = 0; break; + case 0 : break; + default : + { + for (iterator it = begin(); it != end(); ++it) + { + it->parent = 0; + } + } + } - } + } void adopt(void) { - switch(arity()) - { - case 3 : args[2].parent = this; // no break! - case 2 : args[1].parent = this; - case 1 : args[0].parent = this; break; - case 0 : break; - default : - { - for (iterator it = begin(); it != end(); ++it) - { - it->parent = this; - } - } - } + switch(arity()) + { + case 3 : args[2].parent = this; // no break! + case 2 : args[1].parent = this; + case 1 : args[0].parent = this; break; + case 0 : break; + default : + { + for (iterator it = begin(); it != end(); ++it) + { + it->parent = this; + } + } + } } template @@ -581,7 +581,7 @@ private : subtree* args; subtree* parent; - size_t _cumulative_size; + size_t _cumulative_size; size_t _depth; size_t _size; }; @@ -590,7 +590,7 @@ private : typedef T value_type; - /* Constructors and Assignments */ + /* Constructors and Assignments */ parse_tree(void) : _root(), pushed() {} parse_tree(const parse_tree& org) : _root(org._root), pushed(org.pushed) { } @@ -602,33 +602,33 @@ private : virtual ~parse_tree(void) {} parse_tree& operator=(const parse_tree& org) { return copy(org); } - parse_tree& operator=(const subtree& sub) - { return copy(sub); } + parse_tree& operator=(const subtree& sub) + { return copy(sub); } - /* Equality and inequality */ + /* Equality and inequality */ - bool operator==(const parse_tree& other) const - { return _root == other._root; } + bool operator==(const parse_tree& other) const + { return _root == other._root; } - bool operator !=(const parse_tree& other) const - { return !operator==(other); } + bool operator !=(const parse_tree& other) const + { return !operator==(other); } - /* Simple tree statistics */ + /* Simple tree statistics */ size_t size(void) const { return _root.size(); } - size_t depth(void) const { return _root.depth(); } + size_t depth(void) const { return _root.depth(); } void clear(void) { _root.clear(); pushed.resize(0); } - /* Evaluation (application), with an increasing number of user defined arguments */ + /* Evaluation (application), with an increasing number of user defined arguments */ - template - void apply(RetVal& v) const - { _root.apply(v); } + template + void apply(RetVal& v) const + { _root.apply(v); } - template - void apply(RetVal& v, It varValues) const - { _root.apply(v, varValues); } + template + void apply(RetVal& v, It varValues) const + { _root.apply(v, varValues); } template void apply_mem_func(RetVal& v, It misc, void (T::* f)(RetVal&, typename subtree::iterator, It)) @@ -636,13 +636,13 @@ private : _root.apply_mem_func(v, misc, f); } - //template - // void apply(RetVal& v, It varValues, It2 moreValues) const - // { _root.apply(v, varValues, moreValues); } + //template + // void apply(RetVal& v, It varValues, It2 moreValues) const + // { _root.apply(v, varValues, moreValues); } - //template - // void apply(RetVal& v, It varValues, It2 moreValues, It3 evenMoreValues) const - // { _root.apply(v, varValues, moreValues, evenMoreValues); } + //template + // void apply(RetVal& v, It varValues, It2 moreValues, It3 evenMoreValues) const + // { _root.apply(v, varValues, moreValues, evenMoreValues); } template void find_nodes(std::vector& result, Pred& p) @@ -656,14 +656,14 @@ private : _root.find_nodes(p); } - /* Customized Swap */ - void swap(parse_tree& other) - { - do_the_swap(pushed, other.pushed); - _root.swap(other._root); - } + /* Customized Swap */ + void swap(parse_tree& other) + { + do_the_swap(pushed, other.pushed); + _root.swap(other._root); + } - /* Definitions of the iterators */ + /* Definitions of the iterators */ class base_iterator { @@ -680,19 +680,19 @@ private : bool operator!=(const base_iterator& org) const { return !operator==(org); } - base_iterator operator+(size_t n) const - { - base_iterator tmp = *this; + base_iterator operator+(size_t n) const + { + base_iterator tmp = *this; - for(;n != 0; --n) - { - ++tmp; - } + for(;n != 0; --n) + { + ++tmp; + } - return tmp; - } + return tmp; + } - base_iterator& operator++(void) + base_iterator& operator++(void) { subtree* parent = node->get_parent(); @@ -702,7 +702,7 @@ private : return *this; } // else - typename subtree::iterator it; + typename subtree::iterator it; for (it = parent->begin(); it != parent->end(); ++it) { if (node == &(*it)) @@ -801,7 +801,7 @@ private : return *this; } // else - typename subtree::const_iterator it; + typename subtree::const_iterator it; for (it = parent->begin(); it != parent->end(); ++it) { @@ -856,35 +856,35 @@ private : using base_const_iterator::node; - typedef std::forward_iterator_tag iterator_category; - typedef const T value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef const T* pointer; - typedef const T& reference; + typedef std::forward_iterator_tag iterator_category; + typedef const T value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef const T* pointer; + typedef const T& reference; embedded_const_iterator() : base_const_iterator() {} embedded_const_iterator(const subtree* n): base_const_iterator(n) {} embedded_const_iterator& operator=(const embedded_const_iterator& org) { base_const_iterator::operator=(org); return *this; } - embedded_const_iterator operator+(size_t n) const - { - embedded_const_iterator tmp = *this; + embedded_const_iterator operator+(size_t n) const + { + embedded_const_iterator tmp = *this; - for(;n != 0; --n) - { - ++tmp; - } + for(;n != 0; --n) + { + ++tmp; + } - return tmp; - } + return tmp; + } const T& operator*(void) const { return **node; } const T* operator->(void) const { return node->operator->(); } }; - /* Iterator access */ + /* Iterator access */ iterator begin(void) { return iterator(&operator[](0)); } const_iterator begin(void) const { return const_iterator(&operator[](0)); } @@ -899,32 +899,32 @@ private : bool empty(void) const { return size() == 0; } bool valid(void) const { return pushed.empty(); } - /* push_back */ + /* push_back */ - void push_back(const parse_tree& tree) - { - if (!empty()) - pushed.push_back(_root); + void push_back(const parse_tree& tree) + { + if (!empty()) + pushed.push_back(_root); - _root = tree.back(); - } + _root = tree.back(); + } void push_back(const T& t) { if (!empty()) pushed.push_back(_root); - _root = t; + _root = t; for (typename subtree::iterator it = _root.begin(); it != _root.end(); it++) { - *it = pushed.back(); + *it = pushed.back(); pushed.pop_back(); } } - /* Access to subtrees */ + /* Access to subtrees */ subtree& back(void) { return _root; } const subtree& back(void) const { return _root; } @@ -954,7 +954,7 @@ private : return *this; } - parse_tree& copy(const subtree& sub) + parse_tree& copy(const subtree& sub) { _root = sub; pushed.resize(0); return *this; } subtree _root; @@ -970,25 +970,25 @@ namespace std template inline std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::embedded_iterator) { - return std::forward_iterator_tag(); + return std::forward_iterator_tag(); } template inline ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::embedded_iterator) { - return 0; + return 0; } template inline std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::iterator) { - return std::forward_iterator_tag(); + return std::forward_iterator_tag(); } template inline ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::iterator) { - return 0; + return 0; } /* Put customized swaps also in std... diff --git a/eo/src/other/eoString.h b/eo/src/other/eoString.h index bc1cf88d..3071d1ee 100644 --- a/eo/src/other/eoString.h +++ b/eo/src/other/eoString.h @@ -37,8 +37,8 @@ // eoString //----------------------------------------------------------------------------- -/** Adaptor that turns an STL std::string into an EO - +/** Adaptor that turns an STL std::string into an EO + @ingroup Representations @ingroup Utilities */ @@ -82,4 +82,3 @@ public: }; #endif - diff --git a/eo/src/pyeo/Makefile b/eo/src/pyeo/Makefile index 6953249c..61c4f89f 100644 --- a/eo/src/pyeo/Makefile +++ b/eo/src/pyeo/Makefile @@ -1,37 +1,35 @@ # Note for however is foolish enough to attempt to build this thing # -# You need: +# You need: # Python 2.2 # Boost.Python v2 # -CXX = g++ +CXX = g++ CPPFLAGS = -Wall -O2 #-g #-O2 -LDFLAGS = +LDFLAGS = COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c -LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) -INC=-I/usr/include/python2.6 -I.. -I../.. -ftemplate-depth-50 +LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) +INC=-I/usr/include/python2.6 -I.. -I../.. -ftemplate-depth-50 OBJECTS=eoFunctorStore.o PyEO.o abstract1.o algos.o \ - random_numbers.o geneticOps.o selectOne.o continuators.o\ - reduce.o replacement.o selectors.o breeders.o\ - mergers.o valueParam.o perf2worth.o monitors.o\ - statistics.o + random_numbers.o geneticOps.o selectOne.o continuators.o\ + reduce.o replacement.o selectors.o breeders.o\ + mergers.o valueParam.o perf2worth.o monitors.o\ + statistics.o LIB=../libeo.a ../utils/libeoutils.a all: PyEO/PyEO.so clean: - rm PyEO/*.so *.o test/*.pyc + rm PyEO/*.so *.o test/*.pyc PyEO/PyEO.so: $(OBJECTS) - $(LINK) -o PyEO/PyEO.so $(OBJECTS) -lboost_python -lpython2.6 ${LIB} -shared #-lstlport + $(LINK) -o PyEO/PyEO.so $(OBJECTS) -lboost_python -lpython2.6 ${LIB} -shared #-lstlport eoFunctorStore.o: ../eoFunctorStore.h ../eoFunctorStore.cpp - $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) - -%.o:%.cpp PyEO.h def_abstract_functor.h - $(COMPILE) $< $(INC) - + $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) +%.o:%.cpp PyEO.h def_abstract_functor.h + $(COMPILE) $< $(INC) diff --git a/eo/src/pyeo/Makefile.rpm b/eo/src/pyeo/Makefile.rpm index dccf30ee..4db4bcca 100644 --- a/eo/src/pyeo/Makefile.rpm +++ b/eo/src/pyeo/Makefile.rpm @@ -5,7 +5,7 @@ CXXFLAGS = #-g #-DNDEBUG CPPFLAGS = -Wall -O2 LDFLAGS = -L/usr/lib/python2.2/config/ COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c -LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) +LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) INC=-I/usr/include/python2.2 -I/usr/include/stlport -I.. -ftemplate-depth-50 OBJECTS=eoFunctorStore.o PyEO.o abstract1.o algos.o \ @@ -25,7 +25,5 @@ PyEO.so: $(OBJECTS) eoFunctorStore.o: ../eoFunctorStore.h ../eoFunctorStore.cpp $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) -%.o:%.cpp PyEO.h def_abstract_functor.h +%.o:%.cpp PyEO.h def_abstract_functor.h $(COMPILE) $< $(INC) - - diff --git a/eo/src/pyeo/PyEO.h b/eo/src/pyeo/PyEO.h index 6cf3c003..188b7f8d 100644 --- a/eo/src/pyeo/PyEO.h +++ b/eo/src/pyeo/PyEO.h @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -21,112 +21,113 @@ #ifndef PYEO_H #define PYEO_H - #include #include #include #include #include -struct index_error : public std::exception { - index_error(std::string w) : what(w) {}; + +struct index_error : public std::exception +{ + index_error(std::string w) : what(w) {}; virtual ~index_error() throw() {} - std::string what; + std::string what; }; class PyFitness : public boost::python::object { - public : - +public : + typedef PyFitness fitness_traits; // it's its own traits class :-) - + PyFitness() : boost::python::object() {} - + template PyFitness(const T& o) : boost::python::object(o) {} - + static unsigned nObjectives() { return objective_info.size(); } static double tol() { return 1e-6; } static bool maximizing(int which) { return objective_info[which] > 0; } - + static void setObjectivesSize(int sz) { objective_info.resize(sz, 0); } static void setObjectivesValue(unsigned which, int value) { - if (which >= objective_info.size()) - { - throw index_error("Too few elements allocated, resize objectives first"); - } + if (which >= objective_info.size()) + { + throw index_error("Too few elements allocated, resize objectives first"); + } - objective_info[which] = value; + objective_info[which] = value; } - + static std::vector objective_info; - + bool dominates(const PyFitness& oth) const; - - double operator[](int i) const - { - boost::python::extract x(object::operator[](i)); - - if (!x.check()) - throw std::runtime_error("PyFitness: does not contain doubles"); - return x(); - } - - bool operator<(const PyFitness& other) const - { - if (objective_info.size() == 0) - { - const object& self = *this; - const object& oth = other; - return self < oth; - } - // otherwise use objective_info - - for (unsigned i = 0; i < objective_info.size(); ++i) - { - double a = objective_info[i] * operator[](i); - double b = objective_info[i] * other[i]; - if ( fabs(a - b) > tol()) - { - if (a < b) - return true; - return false; - } - } + double operator[](int i) const + { + boost::python::extract x(object::operator[](i)); - return false; + if (!x.check()) + throw std::runtime_error("PyFitness: does not contain doubles"); + return x(); } - - bool operator>(const PyFitness& other) const - { - return other.operator<(*this); + + bool operator<(const PyFitness& other) const + { + if (objective_info.size() == 0) + { + const object& self = *this; + const object& oth = other; + return self < oth; + } + // otherwise use objective_info + + for (unsigned i = 0; i < objective_info.size(); ++i) + { + double a = objective_info[i] * operator[](i); + double b = objective_info[i] * other[i]; + + if ( fabs(a - b) > tol()) + { + if (a < b) + return true; + return false; + } + } + + return false; } - + + bool operator>(const PyFitness& other) const + { + return other.operator<(*this); + } + void printOn(std::ostream& os) const { const boost::python::object& o = *this; boost::python::api::operator<<(os,o); } friend std::ostream& operator<<(std::ostream& os, const PyFitness& p) { p.printOn(os); return os; } friend std::istream& operator>>(std::istream& is, PyFitness& p) { boost::python::object o; is >> o; p = o; return is; } }; struct PyEO : public EO< PyFitness > -{ +{ typedef PyFitness Fitness; - + boost::python::object getFitness() const { return invalid()? Fitness(): fitness(); } void setFitness(boost::python::object f) { if (f == Fitness()) invalidate(); else fitness(f); } boost::python::object getGenome() const { return genome; } void setGenome(boost::python::object g) { genome = g; } boost::python::object genome; - + std::string to_string() const { - std::string result; - result += boost::python::extract(boost::python::str(getFitness())); - result += ' '; - result += boost::python::extract(boost::python::str(genome)); - return result; + std::string result; + result += boost::python::extract(boost::python::str(getFitness())); + result += ' '; + result += boost::python::extract(boost::python::str(genome)); + return result; } bool operator<(const PyEO& other) const { return EO::operator<(other); } @@ -139,17 +140,16 @@ std::ostream& operator<<(std::ostream& os, const PyEO& _eo); struct PyEO_pickle_suite : boost::python::pickle_suite { typedef PyEO::Fitness Fitness; - - static - boost::python::tuple getstate(const PyEO& _eo) + + static boost::python::tuple getstate(const PyEO& _eo) { - return boost::python::make_tuple(_eo.getFitness(), _eo.genome); + return boost::python::make_tuple(_eo.getFitness(), _eo.genome); } - static - void setstate(PyEO& _eo, boost::python::tuple pickled) + + static void setstate(PyEO& _eo, boost::python::tuple pickled) { - _eo.setFitness( Fitness(pickled[0]) ); - _eo.genome = pickled[1]; + _eo.setFitness( Fitness(pickled[0]) ); + _eo.genome = pickled[1]; } }; diff --git a/eo/src/pyeo/PyEO/__init__.py b/eo/src/pyeo/PyEO/__init__.py index cc679542..2818319b 100644 --- a/eo/src/pyeo/PyEO/__init__.py +++ b/eo/src/pyeo/PyEO/__init__.py @@ -1,4 +1,3 @@ - from PyEO import * try: @@ -8,80 +7,77 @@ except ImportError: else: class eoGnuplot1DMonitor(eoMonitor): - def __init__(self): - eoMonitor.__init__(self) - self.values = [] - self.indices = [] - self.g = Gnuplot.Gnuplot() - self.g.reset(); - - - def handleParam(self, i, param): - param = float(param) + def __init__(self): + eoMonitor.__init__(self) + self.values = [] + self.indices = [] + self.g = Gnuplot.Gnuplot() + self.g.reset(); - while len(self.values) <= i: - self.values.append( [] ) + def handleParam(self, i, param): + param = float(param) - self.values[i].append(param) - - def __call__(self): - - l = len(self) + while len(self.values) <= i: + self.values.append( [] ) - if l > 3 or l == 0: - print 'Can only handle 1 to 3 params currently' - - i = 0 - for param in self: - self.handleParam(i,param) - i += 1 - - self.indices.append( len(self.indices) ) + self.values[i].append(param) + + def __call__(self): + l = len(self) + + if l > 3 or l == 0: + print 'Can only handle 1 to 3 params currently' + + i = 0 + for param in self: + self.handleParam(i,param) + i += 1 + + self.indices.append( len(self.indices) ) - data1 = Gnuplot.Data(self.indices, self.values[0], with = 'lines') - - if l == 1: - self.g.plot(data1) - else: - data2 = Gnuplot.Data(self.indices, self.values[1], with = 'lines') + data1 = Gnuplot.Data(self.indices, self.values[0], with = 'lines') - if l == 2: - self.g.plot(data1, data2) - else: - data3 = Gnuplot.Data(self.indices, self.values[2], with = 'lines') + if l == 1: + self.g.plot(data1) + else: + data2 = Gnuplot.Data(self.indices, self.values[1], with = 'lines') - self.g.plot(data1, data2, data3) + if l == 2: + self.g.plot(data1, data2) + else: + data3 = Gnuplot.Data(self.indices, self.values[2], with = 'lines') + + self.g.plot(data1, data2, data3) def SeperatedVolumeMonitor(eoMonitor): def __init__(self, file): - eoMonitor.__init__(self) - self.file = file - self.initialized = None; + eoMonitor.__init__(self) + self.file = file + self.initialized = None; def __call__(self): - pass + pass class eoStat(eoStatBase, eoValueParam): def __init__(self): - eoStatBase.__init__(self) - eoValueParam.__init__(self) - + eoStatBase.__init__(self) + eoValueParam.__init__(self) + class eoSortedStat(eoSortedStatBase, eoValueParam): def __init__(self): - eoSortedStatBase.__init__(self) - eoValueParam.__init__(self) + eoSortedStatBase.__init__(self) + eoValueParam.__init__(self) class eoAverageStat(eoStat): def __call__(self, pop): - sum = 0.0; - for indy in pop: - sum += indy.fitness + sum = 0.0; + for indy in pop: + sum += indy.fitness - sum /= len(pop) - self.object = sum + sum /= len(pop) + self.object = sum class eoBestFitnessStat(eoSortedStat): - def __call__(self, pop): - self.object = pop[0].fitness + self.object = pop[0].fitness diff --git a/eo/src/pyeo/abstract1.cpp b/eo/src/pyeo/abstract1.cpp index e8e84777..43c0dadb 100644 --- a/eo/src/pyeo/abstract1.cpp +++ b/eo/src/pyeo/abstract1.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -34,13 +34,19 @@ void abstract1() /* Abstract Classes: overrideble from python */ def_abstract_functor >("eoEvalFunc"); def_abstract_functor >("eoInit"); - + def_abstract_functor >("eoTransform"); - - class_, bases > >("eoSGATransform", - init< eoQuadOp&, double, - eoMonOp&, double>()) - .def("__call__", &eoSGATransform::operator()); - + + class_, bases > > + ("eoSGATransform", + init< + eoQuadOp&, + double, + eoMonOp&, + double + >() + ) + .def("__call__", &eoSGATransform::operator()); + def_abstract_functor >("eoPopEvalFunc"); -} +} diff --git a/eo/src/pyeo/algos.cpp b/eo/src/pyeo/algos.cpp index 12feaf19..caa2fcd3 100644 --- a/eo/src/pyeo/algos.cpp +++ b/eo/src/pyeo/algos.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,76 +31,96 @@ using namespace boost::python; void algos() { def_abstract_functor >("eoAlgo"); - + /* Algorithms */ - class_, bases >, boost::noncopyable>("eoSGA", - init&, - eoQuadOp&, float, - eoMonOp&, float, - eoEvalFunc&, - eoContinue&>() - [ - with_custodian_and_ward<1,2, - with_custodian_and_ward<1,3, - with_custodian_and_ward<1,5, - with_custodian_and_ward<1,7, - with_custodian_and_ward<1,8> - > - > - > - >() - ]) - .def("__call__", &eoSGA::operator()) - ; - - class_, bases > >("eoEasyEA", - init< - eoContinue&, - eoEvalFunc&, - eoBreed&, - eoReplacement& >() ) - .def( init< - eoContinue&, - eoPopEvalFunc&, - eoBreed&, - eoReplacement&>() ) - .def( init< - eoContinue&, - eoEvalFunc&, - eoBreed&, - eoMerge&, - eoReduce& >() ) - .def( init< - eoContinue&, - eoEvalFunc&, - eoSelect&, - eoTransform&, - eoReplacement&>()) - .def( init< - eoContinue&, - eoEvalFunc&, - eoSelect&, - eoTransform&, - eoMerge&, - eoReduce&>()) - .def("__call__", &eoEasyEA::operator()) - ; - + class_, bases >, boost::noncopyable> + ("eoSGA", + init< + eoSelectOne&, + eoQuadOp&, + float, + eoMonOp&, + float, + eoEvalFunc&, + eoContinue& + >() + [ + with_custodian_and_ward<1,2, + with_custodian_and_ward<1,3, + with_custodian_and_ward<1,5, + with_custodian_and_ward<1,7, + with_custodian_and_ward<1,8> + > + > + > + >() + ] + ) + .def("__call__", &eoSGA::operator()) + ; + + class_, bases > > + ("eoEasyEA", + init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoReplacement& + >() + ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoReplacement&, + unsigned + >() ) + .def( init< + eoContinue&, + eoPopEvalFunc&, + eoBreed&, + eoReplacement& + >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoMerge&, + eoReduce& + >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoSelect&, + eoTransform&, + eoReplacement& + >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoSelect&, + eoTransform&, + eoMerge&, + eoReduce& + >() ) + .def("__call__", &eoEasyEA::operator()) + ; + /* - class_, bases< eoAlgo > >("eoCellularEasyEA", - init< eoContinue&, - eoEvalFunc&, - eoSelectOne&, - eoBinOp&, - eoMonOp&, - eoSelectOne&>()) - .def( - init< eoContinue&, - eoEvalFunc&, - eoSelectOne&, - eoQuadOp&, - eoMonOp&, - eoSelectOne&>()) - ; + class_, bases< eoAlgo > >("eoCellularEasyEA", + init< eoContinue&, + eoEvalFunc&, + eoSelectOne&, + eoBinOp&, + eoMonOp&, + eoSelectOne&>()) + .def( + init< eoContinue&, + eoEvalFunc&, + eoSelectOne&, + eoQuadOp&, + eoMonOp&, + eoSelectOne&>()) + ; */ } diff --git a/eo/src/pyeo/breeders.cpp b/eo/src/pyeo/breeders.cpp index 30cf0994..c66b6bcc 100644 --- a/eo/src/pyeo/breeders.cpp +++ b/eo/src/pyeo/breeders.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -27,9 +27,19 @@ using namespace boost::python; -#define DEF3(x, i1, i2) class_, bases > >(#x, \ - init()[with_custodian_and_ward<1,2,with_custodian_and_ward<1,3> >()])\ - .def("__call__", &eoBreed::operator()) +#define DEF3(x, i1, i2) \ + class_, bases > > \ + (#x, \ + init() \ + [ \ + with_custodian_and_ward<1,2, \ + with_custodian_and_ward<1,3 \ + > \ + > \ + () \ + ] \ + ) \ + .def("__call__", &eoBreed::operator()) void breeders() { @@ -38,14 +48,12 @@ void breeders() DEF3(eoSelectTransform, eoSelect&, eoTransform&); DEF3(eoGeneralBreeder, eoSelectOne&, eoGenOp&) - .def( init&, eoGenOp&, double>()[WC2]) - .def( init&, eoGenOp&, double, bool>()[WC2] ) - .def( init&, eoGenOp&, eoHowMany>() ); + .def( init&, eoGenOp&, double>()[WC2]) + .def( init&, eoGenOp&, double, bool>()[WC2] ) + .def( init&, eoGenOp&, eoHowMany>() ); DEF3(eoOneToOneBreeder, eoGenOp&, eoEvalFunc&) - .def( init&, eoEvalFunc&, double>()[WC2] ) - .def( init&, eoEvalFunc&, double, eoHowMany>()[WC2] ); - + .def( init&, eoEvalFunc&, double>()[WC2] ) + .def( init&, eoEvalFunc&, double, eoHowMany>()[WC2] ); } - diff --git a/eo/src/pyeo/continuators.cpp b/eo/src/pyeo/continuators.cpp index 4f1a76c5..d31613d2 100644 --- a/eo/src/pyeo/continuators.cpp +++ b/eo/src/pyeo/continuators.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -40,28 +40,34 @@ void add_checkpoint(); void continuators() { /* Counters, wrappers etc */ - - class_, bases > >("eoEvalFuncCounter", - init< eoEvalFunc&, std::string>()) - .def("__call__", &eoEvalFuncCounter::operator()) - ; + + class_, bases > > + ("eoEvalFuncCounter", + init< eoEvalFunc&, std::string>() + ) + .def("__call__", &eoEvalFuncCounter::operator()) + ; /* Continuators */ - def_abstract_functor >("eoContinue"); - - class_, bases >, boost::noncopyable >("eoGenContinue", init() ) - .def("__call__", &eoGenContinue::operator()) - ; - - class_, bases > >("eoCombinedContinue", init&>()[WC1]) - .def( init&, eoContinue& >()[WC2] ) - .def("add", &eoCombinedContinue::add, WC1) - .def("__call__", &eoCombinedContinue::operator()) - ; - - class_, bases > >("eoEvalContinue", - init&, unsigned long>()[WC1]) - .def("__call__", &eoEvalContinue::operator()) - ; + def_abstract_functor >("eoContinue"); + + class_, bases >, boost::noncopyable > + ("eoGenContinue", init() ) + .def("__call__", &eoGenContinue::operator()) + ; + + class_, bases > > + ("eoCombinedContinue", init&>()[WC1]) + .def( init&, eoContinue& >()[WC2] ) + .def("add", &eoCombinedContinue::add, WC1) + .def("__call__", &eoCombinedContinue::operator()) + ; + + class_, bases > > + ("eoEvalContinue", + init&, unsigned long>()[WC1] + ) + .def("__call__", &eoEvalContinue::operator()) + ; DEF2(eoFitContinue, object); // object is the fitness type @@ -77,14 +83,14 @@ void addSortedStat(eoCheckPoint& c, eoSortedStatBase& s) { c.add(s); void add_checkpoint() { - class_, bases< eoContinue > >("eoCheckPoint", - - init&> ()[with_custodian_and_ward<1,2>()] - ) - .def("add", addContinue, with_custodian_and_ward<1,2>() ) - .def("add", addMonitor, with_custodian_and_ward<1,2>() ) - .def("add", addStat, with_custodian_and_ward<1,2>()) - .def("add", addSortedStat, with_custodian_and_ward<1,2>()) - .def("__call__", &eoCheckPoint::operator()) - ; + class_, bases< eoContinue > > + ("eoCheckPoint", + init&> ()[with_custodian_and_ward<1,2>()] + ) + .def("add", addContinue, with_custodian_and_ward<1,2>() ) + .def("add", addMonitor, with_custodian_and_ward<1,2>() ) + .def("add", addStat, with_custodian_and_ward<1,2>()) + .def("add", addSortedStat, with_custodian_and_ward<1,2>()) + .def("__call__", &eoCheckPoint::operator()) + ; } diff --git a/eo/src/pyeo/def_abstract_functor.h b/eo/src/pyeo/def_abstract_functor.h index 7324dc48..4c3101df 100644 --- a/eo/src/pyeo/def_abstract_functor.h +++ b/eo/src/pyeo/def_abstract_functor.h @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -23,104 +23,104 @@ #include -// DEFINES for call +// DEFINES for call #define WC1 boost::python::with_custodian_and_ward<1,2>() #define WC2 boost::python::with_custodian_and_ward<1,2, with_custodian_and_ward<1,3> >() namespace eoutils { -using namespace boost::python; - -template -class ProcWrapper : public Proc -{ - public: - PyObject* self; - ProcWrapper(PyObject* s) : self(s) {} + using namespace boost::python; - typename Proc::result_type operator()(void) + template + class ProcWrapper : public Proc { - return boost::python::call_method(self, "__call__"); - } -}; - -template -void make_abstract_functor(std::string name, typename eoFunctorBase::procedure_tag) -{ - typedef ProcWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator()); -} - -template -void make_abstract_functor_ref(std::string name, typename eoFunctorBase::procedure_tag) -{ - typedef ProcWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>()); -} - -template -class UnaryWrapper : public Unary -{ public: - PyObject* self; - UnaryWrapper(PyObject* s) : self(s) {} + PyObject* self; + ProcWrapper(PyObject* s) : self(s) {} - typename Unary::result_type operator()(typename Unary::argument_type a) - { - return boost::python::call_method(self, "__call__", boost::ref(a) ); - } -}; + typename Proc::result_type operator()(void) + { + return boost::python::call_method(self, "__call__"); + } + }; -template -void make_abstract_functor(std::string name, typename eoFunctorBase::unary_function_tag) -{ - typedef UnaryWrapper Wrapper; - - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator()) - ; -} - -template -void make_abstract_functor_ref(std::string name, typename eoFunctorBase::unary_function_tag) -{ - typedef UnaryWrapper Wrapper; - - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ) - ; -} - -template -class BinaryWrapper : public Binary -{ - public: - PyObject* self; - BinaryWrapper(PyObject* s) : self(s) {} - typename Binary::result_type operator()(typename Binary::first_argument_type a1, typename Binary::second_argument_type a2) + template + void make_abstract_functor(std::string name, typename eoFunctorBase::procedure_tag) { - return boost::python::call_method< - typename Binary::result_type>(self, "__call__", boost::ref(a1), boost::ref(a2) ); + typedef ProcWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()); } -}; -template -void make_abstract_functor(std::string name, typename eoFunctorBase::binary_function_tag) -{ - typedef BinaryWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator()); -} + template + void make_abstract_functor_ref(std::string name, typename eoFunctorBase::procedure_tag) + { + typedef ProcWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>()); + } -template -void make_abstract_functor_ref(std::string name, typename eoFunctorBase::binary_function_tag) -{ - typedef BinaryWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ); -} + template + class UnaryWrapper : public Unary + { + public: + PyObject* self; + UnaryWrapper(PyObject* s) : self(s) {} + + typename Unary::result_type operator()(typename Unary::argument_type a) + { + return boost::python::call_method(self, "__call__", boost::ref(a) ); + } + }; + + template + void make_abstract_functor(std::string name, typename eoFunctorBase::unary_function_tag) + { + typedef UnaryWrapper Wrapper; + + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()) + ; + } + + template + void make_abstract_functor_ref(std::string name, typename eoFunctorBase::unary_function_tag) + { + typedef UnaryWrapper Wrapper; + + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ) + ; + } + + template + class BinaryWrapper : public Binary + { + public: + PyObject* self; + BinaryWrapper(PyObject* s) : self(s) {} + typename Binary::result_type operator()(typename Binary::first_argument_type a1, typename Binary::second_argument_type a2) + { + return boost::python::call_method< + typename Binary::result_type>(self, "__call__", boost::ref(a1), boost::ref(a2) ); + } + }; + + template + void make_abstract_functor(std::string name, typename eoFunctorBase::binary_function_tag) + { + typedef BinaryWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()); + } + + template + void make_abstract_functor_ref(std::string name, typename eoFunctorBase::binary_function_tag) + { + typedef BinaryWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ); + } }// namespace eoutils diff --git a/eo/src/pyeo/geneticOps.cpp b/eo/src/pyeo/geneticOps.cpp index 2665837b..40617680 100644 --- a/eo/src/pyeo/geneticOps.cpp +++ b/eo/src/pyeo/geneticOps.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,22 +31,22 @@ using namespace boost::python; class GenOpWrapper : public eoGenOp { - public: +public: PyObject* self; GenOpWrapper(PyObject* p) : self(p) {} unsigned max_production(void) { - return call_method(self,"max_production"); + return call_method(self,"max_production"); } std::string className() const { - return "GenOpDerivative"; // never saw the use of className anyway + return "GenOpDerivative"; // never saw the use of className anyway } - + void apply(eoPopulator& populator ) { - boost::python::call_method(self,"apply", boost::ref( populator ) ); + boost::python::call_method(self,"apply", boost::ref( populator ) ); } }; @@ -54,15 +54,15 @@ class PopulatorWrapper : public eoPopulator { public: PyObject* self; - PopulatorWrapper(PyObject* p, const eoPop& src, eoPop& dest) - : eoPopulator(src, dest), self(p) - { - //throw std::runtime_error("abstract base class"); - } - + PopulatorWrapper(PyObject* p, const eoPop& src, eoPop& dest) + : eoPopulator(src, dest), self(p) + { + //throw std::runtime_error("abstract base class"); + } + const PyEO& select() { - return call_method(self,"select"); + return call_method(self,"select"); } }; @@ -94,62 +94,62 @@ public: void geneticOps() { class_, PopulatorWrapper, boost::noncopyable> - ("eoPopulator", init&, eoPop&>() ) - .def("select", &PopulatorWrapper::select, return_internal_reference<>() ) - .def("get", &eoPopulator::operator*, return_internal_reference<>() ) - .def("next", &eoPopulator::operator++, return_internal_reference<>() ) - .def("insert", &eoPopulator::insert) - .def("reserve", &eoPopulator::reserve) - .def("source", &eoPopulator::source, return_internal_reference<>() ) - .def("offspring", &eoPopulator::offspring, return_internal_reference<>() ) - .def("tellp", &eoPopulator::tellp) - .def("seekp", &eoPopulator::seekp) - .def("exhausted", &eoPopulator::exhausted) - ; + ("eoPopulator", init&, eoPop&>() ) + .def("select", &PopulatorWrapper::select, return_internal_reference<>() ) + .def("get", &eoPopulator::operator*, return_internal_reference<>() ) + .def("next", &eoPopulator::operator++, return_internal_reference<>() ) + .def("insert", &eoPopulator::insert) + .def("reserve", &eoPopulator::reserve) + .def("source", &eoPopulator::source, return_internal_reference<>() ) + .def("offspring", &eoPopulator::offspring, return_internal_reference<>() ) + .def("tellp", &eoPopulator::tellp) + .def("seekp", &eoPopulator::seekp) + .def("exhausted", &eoPopulator::exhausted) + ; class_, bases > > - ("eoSeqPopulator", init&, eoPop&>() ) - .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) - ; - + ("eoSeqPopulator", init&, eoPop&>() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; + class_, bases > > - ("eoSelectivePopulator", init&, eoPop&, eoSelectOne& >() ) - .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) - ; + ("eoSelectivePopulator", init&, eoPop&, eoSelectOne& >() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; enum_::OpType>("OpType") - .value("unary", eoOp::unary) - .value("binary", eoOp::binary) - .value("quadratic", eoOp::quadratic) - .value("general", eoOp::general) - ; - + .value("unary", eoOp::unary) + .value("binary", eoOp::binary) + .value("quadratic", eoOp::quadratic) + .value("general", eoOp::general) + ; + class_ >("eoOp", init::OpType>()) - .def("getType", &eoOp::getType); - + .def("getType", &eoOp::getType); + class_, MonOpWrapper, bases >, boost::noncopyable>("eoMonOp", init<>()) - .def("__call__", &MonOpWrapper::operator(), "an example docstring"); + .def("__call__", &MonOpWrapper::operator(), "an example docstring"); class_, BinOpWrapper, bases >, boost::noncopyable>("eoBinOp", init<>()) - .def("__call__", &BinOpWrapper::operator()); + .def("__call__", &BinOpWrapper::operator()); class_, QuadOpWrapper, bases >, boost::noncopyable>("eoQuadOp", init<>()) - .def("__call__", &QuadOpWrapper::operator()); - + .def("__call__", &QuadOpWrapper::operator()); + class_, GenOpWrapper, bases >, boost::noncopyable>("eoGenOp", init<>()) - .def("max_production", &GenOpWrapper::max_production) - .def("className", &GenOpWrapper::className) - .def("apply", &GenOpWrapper::apply) - .def("__call__", &eoGenOp::operator()) - ; - + .def("max_production", &GenOpWrapper::max_production) + .def("className", &GenOpWrapper::className) + .def("apply", &GenOpWrapper::apply) + .def("__call__", &eoGenOp::operator()) + ; + class_, bases >, boost::noncopyable>("eoSequentialOp", init<>()) - .def("add", &eoSequentialOp::add, WC1) - .def("apply", &eoSequentialOp::apply) - ; - + .def("add", &eoSequentialOp::add, WC1) + .def("apply", &eoSequentialOp::apply) + ; + class_, bases >, boost::noncopyable>("eoProportionalOp", init<>()) - .def("add", &eoProportionalOp::add, WC1) - .def("apply", &eoProportionalOp::apply) - ; - + .def("add", &eoProportionalOp::add, WC1) + .def("apply", &eoProportionalOp::apply) + ; + /* Cloning */ class_, bases > >("eoMonCloneOp").def("__call__", &eoMonCloneOp::operator()); class_, bases > >("eoBinCloneOp").def("__call__", &eoBinCloneOp::operator()); diff --git a/eo/src/pyeo/mergers.cpp b/eo/src/pyeo/mergers.cpp index fd2b3411..f41af049 100644 --- a/eo/src/pyeo/mergers.cpp +++ b/eo/src/pyeo/mergers.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,11 +31,10 @@ using namespace boost::python; void mergers() { def_abstract_functor >("eoMerge"); - + DEF2(eoElitism, double) - .def( init() ); + .def( init() ); DEF(eoNoElitism); DEF(eoPlus); } - diff --git a/eo/src/pyeo/monitors.cpp b/eo/src/pyeo/monitors.cpp index 8215128d..02d011d8 100644 --- a/eo/src/pyeo/monitors.cpp +++ b/eo/src/pyeo/monitors.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -26,47 +26,46 @@ using namespace boost::python; class MonitorWrapper : public eoMonitor { - public: - PyObject* self; - list objects; - - MonitorWrapper(PyObject* p) :self(p) {} +public: + PyObject* self; + list objects; - eoMonitor& operator()() - { - call_method(self, "__call__"); - return *this; - } + MonitorWrapper(PyObject* p) :self(p) {} - std::string getString(int i) - { - if (static_cast(i) >= vec.size()) - { - throw index_error("Index out of bounds"); - } - - return vec[i]->getValue(); - } + eoMonitor& operator()() + { + call_method(self, "__call__"); + return *this; + } - unsigned size() { return vec.size(); } + std::string getString(int i) + { + if (static_cast(i) >= vec.size()) + { + throw index_error("Index out of bounds"); + } + + return vec[i]->getValue(); + } + + unsigned size() { return vec.size(); } }; void monitors() { - /** - * Change of interface: I encountered some difficulties with + /** + * Change of interface: I encountered some difficulties with * transferring eoParams from and to Python, so now we can * only get at the strings contained in the eoParams. * sorry */ - - class_("eoMonitor", init<>()) - .def("lastCall", &eoMonitor::lastCall) - .def("add", &eoMonitor::add) - .def("__call__", &MonitorWrapper::operator(), return_internal_reference<1>() ) - .def("__getitem__", &MonitorWrapper::getString, - "Returns the string value of the indexed Parameter") - .def("__len__", &MonitorWrapper::size) - ; -} + class_("eoMonitor", init<>()) + .def("lastCall", &eoMonitor::lastCall) + .def("add", &eoMonitor::add) + .def("__call__", &MonitorWrapper::operator(), return_internal_reference<1>() ) + .def("__getitem__", &MonitorWrapper::getString, + "Returns the string value of the indexed Parameter") + .def("__len__", &MonitorWrapper::size) + ; +} diff --git a/eo/src/pyeo/perf2worth.cpp b/eo/src/pyeo/perf2worth.cpp index 3ca13996..a257b0cd 100644 --- a/eo/src/pyeo/perf2worth.cpp +++ b/eo/src/pyeo/perf2worth.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -17,6 +17,7 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + #include #include "PyEO.h" @@ -30,19 +31,18 @@ struct Perf2WorthWrapper : public eoPerf2Worth void operator()( const eoPop& pop) { - call_method(self, "__call__", boost::ref(pop)); + call_method(self, "__call__", boost::ref(pop)); } - }; numeric::array get_worths(eoPerf2Worth& p) { std::vector& worths = p.value(); list result; - + for (unsigned i = 0; i < worths.size(); ++i) - result.append(worths[i]); - + result.append(worths[i]); + return numeric::array(result); } @@ -53,36 +53,37 @@ struct CachedPerf2WorthWrapper : public eoPerf2WorthCached void calculate_worths(const eoPop& pop) { - call_method(self, "calculate_worths", boost::ref(pop)); + call_method(self, "calculate_worths", boost::ref(pop)); } }; -void perf2worth() +void perf2worth() { //numeric::array::set_module_and_type("Numeric", "ArrayType"); - - class_< - eoPerf2Worth, - Perf2WorthWrapper, - bases< eoValueParam > >, - boost::noncopyable>("eoPerf2Worth", init<>()) - - .def("__call__", &Perf2WorthWrapper::operator()) - .def("sort_pop", &eoPerf2Worth::sort_pop) - //.def("value", get_worths) - ; - class_, CachedPerf2WorthWrapper, bases >, boost::noncopyable> - ("eoPerf2WorthCached", init<>()) - .def("__call__", &eoPerf2WorthCached::operator()) - .def("calculate_worths", &CachedPerf2WorthWrapper::calculate_worths) - ; - + class_, + Perf2WorthWrapper, + bases< eoValueParam > >, + boost::noncopyable>("eoPerf2Worth", init<>()) + + .def("__call__", &Perf2WorthWrapper::operator()) + .def("sort_pop", &eoPerf2Worth::sort_pop) + //.def("value", get_worths) + ; + + class_, + CachedPerf2WorthWrapper, + bases >, + boost::noncopyable>("eoPerf2WorthCached", init<>()) + + .def("__call__", &eoPerf2WorthCached::operator()) + .def("calculate_worths", &CachedPerf2WorthWrapper::calculate_worths) + ; + //class_, bases > >("eoNoPerf2Worth") -// .def("__call__", &eoNoPerf2Worth::operator()); - - class_, bases > >("eoNDSorting_II") - .def("calculate_worths", &eoNDSorting_II::calculate_worths); + // .def("__call__", &eoNoPerf2Worth::operator()); + + class_, + bases > >("eoNDSorting_II") + .def("calculate_worths", &eoNDSorting_II::calculate_worths); } - - diff --git a/eo/src/pyeo/pickle.h b/eo/src/pyeo/pickle.h index ee2706fb..0e30654a 100644 --- a/eo/src/pyeo/pickle.h +++ b/eo/src/pyeo/pickle.h @@ -29,32 +29,31 @@ #include /** Implements pickle support for eoPersistent derivatives */ - template struct T_pickle_suite : boost::python::pickle_suite { static std::string print_to_string(const T& t) { - std::ostringstream os; - t.printOn(os); - os << std::ends; - return os.str(); + std::ostringstream os; + t.printOn(os); + os << std::ends; + return os.str(); } static boost::python::tuple getstate(const T& t) { - std::string s = print_to_string(t); - return boost::python::make_tuple( boost::python::str(s)); + std::string s = print_to_string(t); + return boost::python::make_tuple( boost::python::str(s)); } static void setstate(T& t, boost::python::tuple pickled) { - std::string s = boost::python::extract(pickled[0]); - std::istringstream is(s); - t.readFrom(is); + std::string s = boost::python::extract(pickled[0]); + std::istringstream is(s); + t.readFrom(is); } }; @@ -65,7 +64,7 @@ template boost::python::class_& pickle(boost::python::class_& c) { return c.def_pickle(T_pickle_suite()) - .def("__str__", T_pickle_suite::print_to_string); + .def("__str__", T_pickle_suite::print_to_string); } #endif diff --git a/eo/src/pyeo/random_numbers.cpp b/eo/src/pyeo/random_numbers.cpp index aa9e4feb..c9047385 100644 --- a/eo/src/pyeo/random_numbers.cpp +++ b/eo/src/pyeo/random_numbers.cpp @@ -61,52 +61,52 @@ struct RNG_pickle_suite : boost::python::pickle_suite static boost::python::tuple getstate(const eoRng& _rng) { - return boost::python::make_tuple(str(rng_to_string(_rng))); + return boost::python::make_tuple(str(rng_to_string(_rng))); } static void setstate(eoRng& _rng, boost::python::tuple pickled) { - std::string state = extract(pickled[0]); - rng_from_string(_rng, state); + std::string state = extract(pickled[0]); + rng_from_string(_rng, state); } }; int spin(eoRng& _rng, numeric::array values, double total) { - if (total == 0.0) - { - unsigned sz = len(values); - for (unsigned i = 0; i < sz; ++i) - { - total += extract(values[i]); //extract? - } - } + if (total == 0.0) + { + unsigned sz = len(values); + for (unsigned i = 0; i < sz; ++i) + { + total += extract(values[i]); //extract? + } + } - double chance = _rng.uniform() * total; + double chance = _rng.uniform() * total; - int i = 0; - while (chance >= 0.0) - chance -= extract(values[i++]); + int i = 0; + while (chance >= 0.0) + chance -= extract(values[i++]); - return --i; + return --i; } void random_numbers() { class_("eoRng", init()) - .def("flip", &eoRng::flip) - .def("random", &eoRng::random) - .def("rand", &eoRng::rand) - .def("rand_max", &eoRng::rand_max) - .def("reseed", &eoRng::reseed) - // .def("uniform", &eoRng::uniform) - .def("normal", normal) - .def("negexp", &eoRng::negexp) - .def("to_string", rng_to_string) - .def("from_string", rng_from_string) - .def("roulette_wheel", spin) - .def_pickle(RNG_pickle_suite()) - ; + .def("flip", &eoRng::flip) + .def("random", &eoRng::random) + .def("rand", &eoRng::rand) + .def("rand_max", &eoRng::rand_max) + .def("reseed", &eoRng::reseed) + // .def("uniform", &eoRng::uniform) + .def("normal", normal) + .def("negexp", &eoRng::negexp) + .def("to_string", rng_to_string) + .def("from_string", rng_from_string) + .def("roulette_wheel", spin) + .def_pickle(RNG_pickle_suite()) + ; def("rng", get_rng, return_value_policy()); } diff --git a/eo/src/pyeo/reduce.cpp b/eo/src/pyeo/reduce.cpp index a23c15cd..6c9b78c6 100644 --- a/eo/src/pyeo/reduce.cpp +++ b/eo/src/pyeo/reduce.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -27,7 +27,7 @@ using namespace boost::python; // unfortunately have to define it specially class eoReduceWrapper : public eoReduce { - public: +public: PyObject* self; eoReduceWrapper(PyObject* s) : self(s) {} void operator()(eoPop& pop, unsigned i) @@ -38,7 +38,6 @@ class eoReduceWrapper : public eoReduce void reduce() { - // ref trick in def_abstract_functor does not work for unsigned int :-( class_, eoReduceWrapper, boost::noncopyable>("eoReduce", init<>()) .def("__call__", &eoReduceWrapper::operator()); @@ -62,4 +61,3 @@ void reduce() .def("__call__", &eoReduce::operator()) ; } - diff --git a/eo/src/pyeo/replacement.cpp b/eo/src/pyeo/replacement.cpp index 9867a113..eb1bc5d7 100644 --- a/eo/src/pyeo/replacement.cpp +++ b/eo/src/pyeo/replacement.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,8 +31,9 @@ using namespace boost::python; #define DEF(x) class_, bases > >(#x).def("__call__", &eoReplacement::operator()) #define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoReplacement::operator()) -#define DEF3(x, i1, i2) class_, bases > >(#x, \ - init() [WC2])\ +#define DEF3(x, i1, i2) class_, bases > > \ + (#x, \ + init() [WC2]) \ .def("__call__", &eoReplacement::operator()) void replacement() @@ -40,12 +41,12 @@ void replacement() def_abstract_functor >("eoReplacement"); // eoReplacement.h - DEF(eoGenerationalReplacement); - - class_, bases > > + DEF(eoGenerationalReplacement); + + class_, bases > > ("eoWeakElitistReplacement", init< eoReplacement& >()[WC1]); - + // eoMergeReduce.h DEF3(eoMergeReduce, eoMerge&, eoReduce& ); DEF(eoPlusReplacement); @@ -60,13 +61,12 @@ void replacement() // eoReduceMergeReduce.h //class_, bases > >("eoReplacement", -// init&, -// eoHowMany, eoReduce&, eoReduce&>()) -// .def("__call__", &eoReplacement::operator()); - + // init&, + // eoHowMany, eoReduce&, eoReduce&>()) + // .def("__call__", &eoReplacement::operator()); + //eoMGGReplacement DEF(eoMGGReplacement) .def( init() ) .def( init() ); } - diff --git a/eo/src/pyeo/selectOne.cpp b/eo/src/pyeo/selectOne.cpp index 554a6e36..5a28fcff 100644 --- a/eo/src/pyeo/selectOne.cpp +++ b/eo/src/pyeo/selectOne.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -33,10 +33,10 @@ using namespace boost::python; class eoSelectOneWrapper : public eoSelectOne { - public: +public: PyObject* self; eoSelectOneWrapper(PyObject* p) : self(p) {} - const PyEO& operator()(const eoPop& pop) + const PyEO& operator()(const eoPop& pop) { return boost::python::call_method< const PyEO& >(self, "__call__", boost::ref(pop)); } @@ -57,7 +57,7 @@ void add_select(std::string name, Init init) .def("__call__", &Select::operator(), return_internal_reference<>() ) ; } - + template void add_select(std::string name, Init1 init1, Init2 init2) { @@ -70,38 +70,39 @@ void add_select(std::string name, Init1 init1, Init2 init2) void selectOne() { /* Concrete classes */ - + pickle(class_("eoHowMany", init<>()) - .def( init() ) - .def( init() ) - .def( init() ) - .def("__call__", &eoHowMany::operator()) - .def("__neg__", &eoHowMany::operator-) - ); - + .def( init() ) + .def( init() ) + .def( init() ) + .def("__call__", &eoHowMany::operator()) + .def("__neg__", &eoHowMany::operator-) + ); + class_, eoSelectOneWrapper, boost::noncopyable>("eoSelectOne", init<>()) .def("__call__", &eoSelectOneWrapper::operator(), return_internal_reference<>() ) .def("setup", &eoSelectOne::setup); - + /* SelectOne derived classes */ - + add_select >("eoDetTournamentSelect", init<>(), init() ); add_select >("eoStochTournamentSelect", init<>(), init() ); - add_select >("eoTruncatedSelectOne", - init&, double>()[WC1], init&, eoHowMany >()[WC1] ); - + add_select >("eoTruncatedSelectOne", + init&, double>()[WC1], + init&, eoHowMany >()[WC1] + ); + // eoProportionalSelect is not feasible to implement at this point as fitness is not recognizable as a float // use eoDetTournament instead: with a t-size of 2 it is equivalent to eoProportional with linear scaling //add_select >("eoProportionalSelect", init&>() ); - + add_select >("eoRandomSelect"); add_select >("eoBestSelect"); add_select >("eoNoSelect"); - + add_select >("eoSequentialSelect", init<>(), init()); add_select >("eoEliteSequentialSelect"); /* * eoSelectFromWorth.h:class eoSelectFromWorth : public eoSelectOne - - */ + */ } diff --git a/eo/src/pyeo/selectors.cpp b/eo/src/pyeo/selectors.cpp index ba8d405d..7c8f4096 100644 --- a/eo/src/pyeo/selectors.cpp +++ b/eo/src/pyeo/selectors.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -53,9 +53,8 @@ void selectors() DEF3(eoTruncSelect, eoSelectOne&, eoHowMany); class_, bases > >("eoTruncatedSelectMany", - init&, double, double>()[WC1]) + init&, double, double>()[WC1]) .def(init&, double, double, bool> ()[WC1]) .def(init&, double, double, bool, bool> ()[WC1]) .def(init&, eoHowMany, eoHowMany> ()[WC1]); - } diff --git a/eo/src/pyeo/statistics.cpp b/eo/src/pyeo/statistics.cpp index 9c436ba5..fbad9269 100644 --- a/eo/src/pyeo/statistics.cpp +++ b/eo/src/pyeo/statistics.cpp @@ -5,9 +5,9 @@ using namespace boost::python; -class StatBaseWrapper : public eoStatBase +class StatBaseWrapper : public eoStatBase { - public: +public: PyObject* self; StatBaseWrapper(PyObject* p) : self(p) {} @@ -17,9 +17,9 @@ class StatBaseWrapper : public eoStatBase } }; -class SortedStatBaseWrapper : public eoSortedStatBase +class SortedStatBaseWrapper : public eoSortedStatBase { - public: +public: PyObject* self; SortedStatBaseWrapper(PyObject* p) : self(p) {} @@ -31,13 +31,13 @@ class SortedStatBaseWrapper : public eoSortedStatBase typedef std::vector eoPopView; -const PyEO& popview_getitem(const std::vector& pop, int it) -{ +const PyEO& popview_getitem(const std::vector& pop, int it) +{ unsigned item = unsigned(it); if (item > pop.size()) throw index_error("too much"); - - return *pop[item]; + + return *pop[item]; } void statistics() @@ -52,7 +52,7 @@ void statistics() .def("__getitem__", popview_getitem, return_internal_reference<>() ) .def("__len__", &eoPopView::size) ; - + class_, SortedStatBaseWrapper, boost::noncopyable> ("eoSortedStatBase", init<>()) .def("lastCall", &eoSortedStatBase::lastCall) diff --git a/eo/src/pyeo/test/maxone.py b/eo/src/pyeo/test/maxone.py index c2b6a0cf..3544d498 100644 --- a/eo/src/pyeo/test/maxone.py +++ b/eo/src/pyeo/test/maxone.py @@ -1,4 +1,3 @@ - import sys sys.path.append('..') @@ -10,47 +9,47 @@ from copy import copy class MinimFit(float): def __cmp__(self, other): - if other == None: # I seem to be getting None's, don't know why - return 1 - return float.__cmp__(other, self) - + if other == None: # I seem to be getting None's, don't know why + return 1 + return float.__cmp__(other, self) + class EvalFunc(eoEvalFunc): def __call__(self, eo): - eo.fitness = reduce(lambda x,y: x+y, eo.genome, 0) - + eo.fitness = reduce(lambda x,y: x+y, eo.genome, 0) + class MinEvalFunc(eoEvalFunc): def __call__(self, eo): - f = reduce(lambda x,y: x+y, eo.genome, 0 ) - eo.fitness = MinimFit(f) + f = reduce(lambda x,y: x+y, eo.genome, 0 ) + eo.fitness = MinimFit(f) class Init(eoInit): def __init__(self, genome_length = 10): - eoInit.__init__(self) - self.length = genome_length + eoInit.__init__(self) + self.length = genome_length def __call__(self, eo): - eo.genome = [rng().flip(0.5) for x in range(self.length)] - + eo.genome = [rng().flip(0.5) for x in range(self.length)] + class Mutate(eoMonOp): def __call__(self, eo): - eo.genome = copy(eo.genome) + eo.genome = copy(eo.genome) - prob = 1. / len(eo.genome) - for i in range(len(eo.genome)): - if rng().flip(0.5): - eo.genome[i] = 1-eo.genome[i]; - return 1 + prob = 1. / len(eo.genome) + for i in range(len(eo.genome)): + if rng().flip(0.5): + eo.genome[i] = 1-eo.genome[i]; + return 1 class Crossover(eoQuadOp): def __call__(self, eo1, eo2): - eo1.genome = copy(eo1.genome); - eo2.genome = copy(eo2.genome); + eo1.genome = copy(eo1.genome); + eo2.genome = copy(eo2.genome); - point = rng().random( len(eo1.genome) ); + point = rng().random( len(eo1.genome) ); - eo1.genome[:point] = eo2.genome[:point]; - eo2.genome[point:] = eo1.genome[point:]; - - return 1 + eo1.genome[:point] = eo2.genome[:point]; + eo2.genome[point:] = eo1.genome[point:]; + + return 1 evaluate = EvalFunc() init = Init(3) @@ -58,34 +57,32 @@ mutate = Mutate() xover = Crossover() if __name__ == '__main__': - + eo = EO() eo1 = EO() - + init(eo1) init(eo) evaluate(eo) print eo - + for i in range(10): - xover(eo, eo1) - mutate(eo) - - evaluate(eo) - print eo, eo1 - + xover(eo, eo1) + mutate(eo) + + evaluate(eo) + print eo, eo1 + print print print - + pop = eoPop(1, init) - + pop[0] = eo; mutate(pop[0]) pop[0].invalidate() evaluate(pop[0]) - - print pop[0], eo - + print pop[0], eo diff --git a/eo/src/pyeo/test/test_breeders.py b/eo/src/pyeo/test/test_breeders.py index 5d3fc760..c23d4787 100644 --- a/eo/src/pyeo/test/test_breeders.py +++ b/eo/src/pyeo/test/test_breeders.py @@ -1,18 +1,16 @@ from maxone import * import unittest - + class TestBreeders(unittest.TestCase): - def runtest(self, breed): - pop = eoPop(50, Init(20)) evaluate = EvalFunc() - print 'HERE' + print 'HERE' for indy in pop: evaluate(indy) newpop = eoPop(); breed(pop,newpop) - + print pop.best() for indy in newpop: evaluate(indy) print newpop.best() @@ -28,6 +26,5 @@ class TestBreeders(unittest.TestCase): def suite(): return unittest.makeSuite(TestSGA,'test') - if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_mo.py b/eo/src/pyeo/test/test_mo.py index ac847290..5a7a79a4 100644 --- a/eo/src/pyeo/test/test_mo.py +++ b/eo/src/pyeo/test/test_mo.py @@ -2,35 +2,33 @@ from maxone import * from math import exp import unittest - class MyInit(eoInit): def __call__(self, eo): eo.genome = [rng().normal(), rng().normal(), rng().normal()]; class MyMutate(eoMonOp): def __call__(self, eo): - std = 0.05 eo.genome = copy(eo.genome) - + eo.genome[0] += rng().normal() * std eo.genome[1] += rng().normal() * std - eo.genome[2] += rng().normal() * std + eo.genome[2] += rng().normal() * std return 1 class AnEval(eoEvalFunc): def __init__(self): eoEvalFunc.__init__(self) - + setObjectivesSize(2); setObjectivesValue(0,1); setObjectivesValue(1,1); - + def __call__(self, eo): x = abs(eo.genome[0]) y = abs(eo.genome[1]) z = abs(eo.genome[2]) - + eo.fitness = [ x / (x+y+z), y /(x+y+z) ] import Gnuplot @@ -47,71 +45,65 @@ def do_plot(pop): l2.append(indy.fitness[1]) d = Gnuplot.Data(l1,l2, with = 'points') - + d2 = Gnuplot.Data([0,1],[1,0], with='lines') - + g.plot(d,d2) - - class NSGA_II(eoAlgo): def __init__(self, ngens): - self.cont = eoGenContinue(ngens); - + self.selectOne = eoDetTournamentSelect(2); self.evaluate = AnEval() self.mutate = MyMutate() self.init = MyInit() - + self.seq = eoProportionalOp() self.seq.add(self.mutate, 1.0) - + self.perf2worth = eoNDSorting_II() - + def __call__(self, pop): - sz = len(pop) i = 0 while self.cont(pop): - newpop = eoPop() + newpop = eoPop() populator = eoSelectivePopulator(pop, newpop, self.selectOne); while len(newpop) < sz: self.seq(populator) - - for indy in newpop: + + for indy in newpop: self.evaluate(indy) pop.push_back(indy) self.perf2worth(pop) self.perf2worth.sort_pop(pop) - + #print pop[0].fitness, pop[0].genome pop.resize(sz) - + #worth = self.perf2worth.getValue() #print worth[0], worth[sz-1] - + i += 1 if i%100 == 0: - pass + pass do_plot(pop) - + worths = self.perf2worth.getValue() - + w0 = int(worths[0]-0.001) - + for i in range(len(pop)): if worths[i] <= w0: break; print pop[i].genome print pop[i].fitness - - + class TestNSGA_II(unittest.TestCase): - def testIndividuals(self): setObjectivesSize(2); setObjectivesValue(0,1); @@ -133,12 +125,12 @@ class TestNSGA_II(unittest.TestCase): self.failUnlessEqual(dominates(eo1, eo2), 1) self.failUnlessEqual(dominates(eo2, eo1), 0) self.failUnlessEqual(dominates(eo2, eo2), 0) - + def testNDSorting(self): setObjectivesSize(2); setObjectivesValue(0,-1) setObjectivesValue(1,-1); - + pop = eoPop() pop.resize(6) @@ -157,20 +149,18 @@ class TestNSGA_II(unittest.TestCase): for indy in pop: print indy.fitness - worths = srt.getValue() print worths print type(worths) def testNSGA_II(self): - evaluate = AnEval(); pop = eoPop(25, MyInit()) for indy in pop: evaluate(indy) - + nsga = NSGA_II(50) nsga(pop) - + if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_pickling.py b/eo/src/pyeo/test/test_pickling.py index 161668bb..81b3b9f5 100644 --- a/eo/src/pyeo/test/test_pickling.py +++ b/eo/src/pyeo/test/test_pickling.py @@ -5,9 +5,7 @@ import tempfile import os class TestPickling(unittest.TestCase): - def do_pickle(self, object): - filename = tempfile.mktemp() file = open(filename, 'wb') pickler = cPickle.Pickler(file) @@ -15,9 +13,9 @@ class TestPickling(unittest.TestCase): pickler.dump(object); del pickler file.close() - + file = open(filename) - + unpickler = cPickle.Unpickler(file) object2 = unpickler.load() @@ -29,15 +27,13 @@ class TestPickling(unittest.TestCase): return object2 def testInvalidEO(self): - eo = EO(); eo.genome = [1,2,3]; - + eo2 = self.do_pickle(eo) self.failUnlessEqual( str(eo), str(eo2) ) def testValidEO(self): - eo = EO(); eo.genome = [1,2,3]; eo.fitness = 10 @@ -45,19 +41,17 @@ class TestPickling(unittest.TestCase): eo2 = self.do_pickle(eo) self.failUnlessEqual( str(eo), str(eo2) ) - + def testPop(self): - pop = eoPop(40, init) - for indy in pop: + for indy in pop: evaluate(indy) pop2 = self.do_pickle(pop) - + self.failUnlessEqual( str(pop), str(pop2) ) def testHowMany(self): - howmany = eoHowMany(0.8); howmany2 = self.do_pickle(howmany) @@ -65,36 +59,33 @@ class TestPickling(unittest.TestCase): self.failUnlessEqual( str(howmany), str(howmany) ) def testRNG(self): - for i in range(10): rng().rand() - + rng2 = self.do_pickle(rng()) - + for i in range(100): a = rng().rand() b = rng2.rand() self.failUnlessEqual(a,b) def vParam(self,v): - v2 = self.do_pickle(v); self.failUnlessEqual(v.value, v2.value) - + def testValueParam(self): import Numeric - - self.vParam(eoValueParamInt(42,'int')) + + self.vParam(eoValueParamInt(42,'int')) self.vParam(eoValueParamFloat(4.2,'float')) - + v = eoValueParamVec() v.value = Numeric.arange(10) - self.vParam(v) + self.vParam(v) v = eoValueParamPair() v.value = (0.3,0.5) self.vParam(v) - if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_populator.py b/eo/src/pyeo/test/test_populator.py index a6743fda..12335956 100644 --- a/eo/src/pyeo/test/test_populator.py +++ b/eo/src/pyeo/test/test_populator.py @@ -20,36 +20,34 @@ class Xover(Crossover): return Crossover.__call__(self, eo1, eo2) class TestPopulator(unittest.TestCase): - def make_pop(self): pop = eoPop(20, init) for indy in pop: evaluate(indy) return pop - + def test_sequential(self): pop = self.make_pop() populator = eoSeqPopulator(pop, pop) - + print populator.get() print populator.get() - + def test_selective(self): sel = eoDetTournamentSelect(2) pop = self.make_pop() populator = eoSelectivePopulator(pop, pop, sel) - + print populator.get() print populator.get() def runOpContainer(self, opcontainer): - mutate = Mut() xover = Xover() - + print 'making seq' seq = opcontainer() - + print "xovertype", xover.getType() print "mutationtype", mutate.getType() @@ -58,29 +56,27 @@ class TestPopulator(unittest.TestCase): pop = self.make_pop(); offspring = eoPop() - + sel = eoDetTournamentSelect(2) - + print "making populator" populator = eoSelectivePopulator(pop, offspring, sel) print 'made' - + for i in xrange(1000): seq(populator) - + print mutate.cnt print xover.cnt def test_sequentialOp(self): - print '*'*20, "SequentialOp", '*'*20 + print '*'*20, "SequentialOp", '*'*20 self.runOpContainer(eoSequentialOp) - + def test_proportionalOp(self): - print '*'*20, "ProportionalOp", '*'*20 + print '*'*20, "ProportionalOp", '*'*20 self.runOpContainer(eoProportionalOp) - - if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_reduce.py b/eo/src/pyeo/test/test_reduce.py index 2ca99dc5..3e279168 100644 --- a/eo/src/pyeo/test/test_reduce.py +++ b/eo/src/pyeo/test/test_reduce.py @@ -2,11 +2,10 @@ from maxone import * import unittest class TestReduce(unittest.TestCase): - def run_test(self, ReduceClass, Arg = None): pop = eoPop(10, init) for indy in pop: evaluate(indy) - + if Arg: red = ReduceClass(Arg) else: @@ -14,8 +13,8 @@ class TestReduce(unittest.TestCase): red(pop, 5); - self.failUnlessEqual( len(pop), 5) - + self.failUnlessEqual( len(pop), 5) + def test_eoTruncate(self): self.run_test(eoTruncate) def test_eoRandomeReduce(self): @@ -28,7 +27,6 @@ class TestReduce(unittest.TestCase): self.run_test(eoDetTournamentTruncate, 2) def test_eoStochTournamentTruncate(self): self.run_test(eoStochTournamentTruncate, 0.9) - - + if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_selectone.py b/eo/src/pyeo/test/test_selectone.py index 1a25bc7f..f71913b9 100644 --- a/eo/src/pyeo/test/test_selectone.py +++ b/eo/src/pyeo/test/test_selectone.py @@ -3,64 +3,60 @@ import unittest class Init(eoInit): def __call__(self, eo): - pass + pass class TestSGA(unittest.TestCase): - def __init__(self, a): - unittest.TestCase.__init__(self, a) - self.pop = eoPop(4, Init()) + unittest.TestCase.__init__(self, a) + self.pop = eoPop(4, Init()) + + for i in range(len(self.pop)): + self.pop[i].fitness = i; - for i in range(len(self.pop)): - self.pop[i].fitness = i; - def do_test(self, selectOne): - - print '*'*20, "Testing", str(selectOne.__class__), '*'*20 - selection = [0. for i in range(len(self.pop))] + print '*'*20, "Testing", str(selectOne.__class__), '*'*20 + selection = [0. for i in range(len(self.pop))] + + nTries = 500 + for i in range(nTries): + selection[ selectOne(self.pop).fitness ] += 1 + + for i in range(len(self.pop)): + print i, selection[i], selection[i] / nTries + + return selection, nTries - nTries = 500 - for i in range(nTries): - selection[ selectOne(self.pop).fitness ] += 1 - - for i in range(len(self.pop)): - print i, selection[i], selection[i] / nTries - - return selection, nTries - def test_eoDetTournamenSelect(self): - - selectOne = eoDetTournamentSelect(2) - self.do_test(selectOne) - + selectOne = eoDetTournamentSelect(2) + self.do_test(selectOne) + def test_eoRandomSelect(self): - selectOne = eoRandomSelect() - self.do_test(selectOne) + selectOne = eoRandomSelect() + self.do_test(selectOne) def test_eoBestSelect(self): - selectOne = eoBestSelect() - (sel, nTries) = self.do_test(selectOne) + selectOne = eoBestSelect() + (sel, nTries) = self.do_test(selectOne) - self.failUnlessEqual(sel[0], 0); - self.failUnlessEqual(sel[-1], nTries); + self.failUnlessEqual(sel[0], 0); + self.failUnlessEqual(sel[-1], nTries); def test_eoNoSelect(self): - selectOne = eoNoSelect() - self.do_test(selectOne) + selectOne = eoNoSelect() + self.do_test(selectOne) def test_eoStochTournament(self): - selectOne = eoStochTournamentSelect(0.75) - self.do_test(selectOne) + selectOne = eoStochTournamentSelect(0.75) + self.do_test(selectOne) def test_eoSequentialSelect(self): - selectOne = eoSequentialSelect(); - self.do_test(selectOne) - + selectOne = eoSequentialSelect(); + self.do_test(selectOne) + def test_eoEliteSequentialSelect(self): - selectOne = eoEliteSequentialSelect(); - self.do_test(selectOne) - + selectOne = eoEliteSequentialSelect(); + self.do_test(selectOne) if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_sga.py b/eo/src/pyeo/test/test_sga.py index b84afe75..5f6d1c22 100644 --- a/eo/src/pyeo/test/test_sga.py +++ b/eo/src/pyeo/test/test_sga.py @@ -2,43 +2,44 @@ from maxone import * import unittest class TestSGA(unittest.TestCase): - def dotestSGA(self, evaluate): - init = Init(20) - mutate = Mutate() - xover = Crossover() + init = Init(20) + mutate = Mutate() + xover = Crossover() - pop = eoPop(50, init) - for indy in pop: evaluate(indy) + pop = eoPop(50, init) + for indy in pop: evaluate(indy) - select = eoDetTournamentSelect(3); - cont1 = eoGenContinue(20); - - cont = eoCheckPoint(cont1) - - mon = eoGnuplot1DMonitor() - - avg = eoAverageStat() - bst = eoBestFitnessStat() - mon.add(avg) - mon.add(bst) - - # add it to the checkpoint - cont.add(avg) - #cont.add(mon) - cont.add(bst) - - sga = eoSGA(select, xover, 0.6, mutate, 0.4, evaluate, cont); + select = eoDetTournamentSelect(3); + cont1 = eoGenContinue(20); - sga(pop) + cont = eoCheckPoint(cont1) + + mon = eoGnuplot1DMonitor() + + avg = eoAverageStat() + bst = eoBestFitnessStat() + mon.add(avg) + mon.add(bst) + + # add it to the checkpoint + cont.add(avg) + #cont.add(mon) + cont.add(bst) + + sga = eoSGA(select, xover, 0.6, mutate, 0.4, evaluate, cont); + + sga(pop) + + print pop.best() - print pop.best() def testSGA_Max(self): - evaluate = EvalFunc() - self.dotestSGA(evaluate) + evaluate = EvalFunc() + self.dotestSGA(evaluate) + def testSGA_Min(self): - evaluate = MinEvalFunc() - self.dotestSGA(evaluate) + evaluate = MinEvalFunc() + self.dotestSGA(evaluate) if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_transform.py b/eo/src/pyeo/test/test_transform.py index 67d892e6..fb70de3e 100644 --- a/eo/src/pyeo/test/test_transform.py +++ b/eo/src/pyeo/test/test_transform.py @@ -1,61 +1,62 @@ """Test script for the eoSGATranform class""" from copy import deepcopy -from PyEO import * +from PyEO import * from maxone import * pop = eoPop() + for i in range(10): - eo = EO() - init(eo) - evaluate(eo) - pop.push_back(eo) + eo = EO() + init(eo) + evaluate(eo) + pop.push_back(eo) transform = eoSGATransform(xover, 0.8, mutate, 0.2) def test1(pop, transform): - pop = deepcopy(pop) - print "test 1" - print "Initial population:" - print pop + pop = deepcopy(pop) + print "test 1" + print "Initial population:" + print pop - transform(pop) + transform(pop) - print "GM pop:" - print pop + print "GM pop:" + print pop def test2(pop, transform): - pop = deepcopy(pop) + pop = deepcopy(pop) - print "test 2" - print "Initial population" - print pop + print "test 2" + print "Initial population" + print pop - checkpoint = eoCheckPoint(eoGenContinue(50)) - select = eoSelectNumber(eoDetTournamentSelect(3), 10) - replace = eoGenerationalReplacement() - - algo = eoEasyEA(checkpoint, evaluate, select, transform, replace) - algo(pop) + checkpoint = eoCheckPoint(eoGenContinue(50)) + select = eoSelectNumber(eoDetTournamentSelect(3), 10) + replace = eoGenerationalReplacement() - print "Evoluated pop:" - print pop + algo = eoEasyEA(checkpoint, evaluate, select, transform, replace) + algo(pop) + + print "Evoluated pop:" + print pop if __name__ == "__main__": - try: - test1(pop, transform) - except: - import sys - print - print "Caught an exception:" - print sys.exc_type, sys.exc_value - print + try: + test1(pop, transform) + except: + import sys + print + print "Caught an exception:" + print sys.exc_type, sys.exc_value + print - try: - test2(pop, transform) - except: - import sys - print - print "Caught an exception:" - print sys.exc_type, sys.exc_value - print + try: + test2(pop, transform) + except: + import sys + print + print "Caught an exception:" + print sys.exc_type, sys.exc_value + print diff --git a/eo/src/pyeo/valueParam.cpp b/eo/src/pyeo/valueParam.cpp index 60625180..59ed1a47 100644 --- a/eo/src/pyeo/valueParam.cpp +++ b/eo/src/pyeo/valueParam.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -33,13 +33,12 @@ public: PyObject* self; ParamWrapper(PyObject* p) : self(p) {} ParamWrapper(PyObject* p, - std::string a, - std::string b, - std::string c, - char d, - bool e) : eoParam(a,b,c,d,e), self(p) {} + std::string a, + std::string b, + std::string c, + char d, + bool e) : eoParam(a,b,c,d,e), self(p) {} - std::string getValue() const { return call_method(self, "getValueAsString"); @@ -49,7 +48,6 @@ public: { call_method(self, "setValueAsString", s); } - }; template @@ -63,7 +61,7 @@ struct ValueParam_pickle_suite : boost::python::pickle_suite str def(_param.defValue()); str l(_param.longName()); object s(_param.shortName()); - object r(_param.required()); + object r(_param.required()); return make_tuple(v,d,def,l,s,r); } static @@ -90,31 +88,31 @@ void setv(eoValueParam& v, U val) { v.value() = val; } template <> numeric::array getv< std::vector, numeric::array > - (const eoValueParam< std::vector >& param) +(const eoValueParam< std::vector >& param) { const std::vector& v = param.value(); list result; for (unsigned i =0; i < v.size(); ++i) result.append(v[i]); - + return numeric::array(result); } template <> void setv< std::vector, numeric::array > - (eoValueParam< std::vector >& param, numeric::array val) +(eoValueParam< std::vector >& param, numeric::array val) { std::vector& v = param.value(); v.resize( boost::python::len(val) ); for (unsigned i = 0; i < v.size(); ++i) - { - extract x(val[i]); - if (!x.check()) - throw std::runtime_error("double expected"); - - v[i] = x(); - } + { + extract x(val[i]); + if (!x.check()) + throw std::runtime_error("double expected"); + + v[i] = x(); + } } template <> @@ -126,7 +124,7 @@ tuple getv, tuple > template <> void setv< std::pair, tuple > - (eoValueParam< std::pair >& p, tuple val) +(eoValueParam< std::pair >& p, tuple val) { extract first(val[0]); extract second(val[1]); @@ -145,7 +143,7 @@ void define_valueParam(std::string prefix) { std::string name = "eoValueParam"; name += prefix; - + class_, bases >(name.c_str(), init<>()) .def(init()) .def(init()) @@ -173,7 +171,7 @@ void valueParam() .def("shortName", &eoParam::shortName) .def("required", &eoParam::required) ; - + define_valueParam("Int"); define_valueParam("Float"); define_valueParam, numeric::array >("Vec"); @@ -191,4 +189,3 @@ void valueParam() .add_property("object", &ValueParam::getObj, &ValueParam::setObj) ; } - diff --git a/eo/src/pyeo/valueParam.h b/eo/src/pyeo/valueParam.h index 783f2fc1..940a4351 100644 --- a/eo/src/pyeo/valueParam.h +++ b/eo/src/pyeo/valueParam.h @@ -7,23 +7,22 @@ class ValueParam : public eoParam // ValueParam containing python object { boost::python::object obj; - - public: - - ValueParam() : eoParam(), obj() {} - - ValueParam(boost::python::object o, - std::string longName, - std::string d = "No Description", - char s = 0, - bool r = false) : eoParam(longName, "", d, s, r) - { - std::cerr << "HI" << std::endl; - obj = o; - eoParam::defValue(getValue()); - } - +public: + + ValueParam() : eoParam(), obj() {} + + ValueParam(boost::python::object o, + std::string longName, + std::string d = "No Description", + char s = 0, + bool r = false) : eoParam(longName, "", d, s, r) + { + std::cerr << "HI" << std::endl; + obj = o; + eoParam::defValue(getValue()); + } + std::string getValue() const { boost::python::str s = boost::python::str(obj); @@ -37,7 +36,6 @@ class ValueParam : public eoParam // ValueParam containing python object boost::python::object getObj() const { return obj;} void setObj(boost::python::object o) { obj = o; } - }; #endif diff --git a/eo/src/utils/ChangeLog b/eo/src/utils/ChangeLog index a661c0cf..dac74c49 100644 --- a/eo/src/utils/ChangeLog +++ b/eo/src/utils/ChangeLog @@ -1,42 +1,42 @@ 2007-08-22 Jochen Küpper - * eoRNG.h (eoRng::random): Add comment on truncation as standard way of - floating point to integer conversion. + * eoRNG.h (eoRng::random): Add comment on truncation as standard way of + floating point to integer conversion. 2006-12-04 Jochen Küpper - * eoRNG.h (eoRng::normal(stdev)): Revert erroneous change. + * eoRNG.h (eoRng::normal(stdev)): Revert erroneous change. 2006-12-02 Jochen Küpper - * eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned. + * eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned. - * eoRNG.h: Cleanup docs and document /all/ members. + * eoRNG.h: Cleanup docs and document /all/ members. - * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. + * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. 2006-12-01 Jochen Küpper - * eoRNG.cpp: Use C++ style cast. + * eoRNG.cpp: Use C++ style cast. - * Makefile.am: Add missing header for distribution. + * Makefile.am: Add missing header for distribution. 2006-11-30 Jochen Küpper - * eoRNG.h: Generally include + * eoRNG.h: Generally include 2006-11-16 Jochen Küpper - * eoParser.h (eoParser::getORcreateParam): Make this a real if-then-else - clause around ptParam (found or not). + * eoParser.h (eoParser::getORcreateParam): Make this a real if-then-else + clause around ptParam (found or not). - * eoParam.h (eoValueParam::setValue): Document. - (eoValueParam >::setValue): Allow delimiters ',' and - ';'. A plain ' ' does not work, as it is not correctly read by - eoParser::readFrom. + * eoParam.h (eoValueParam::setValue): Document. + (eoValueParam >::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: + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/eo/src/utils/compatibility.h b/eo/src/utils/compatibility.h index af20a792..937ab8a0 100644 --- a/eo/src/utils/compatibility.h +++ b/eo/src/utils/compatibility.h @@ -2,12 +2,12 @@ ----------------------------------------------------------------------------- compatibility.h - File to store some compiler specific stuff in. Currently handles, or + 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 @@ -33,15 +33,15 @@ #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 + // 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) @@ -67,7 +67,7 @@ namespace std // else return b; } - + template const T& max(const T& a, const T& b) { if(a > b) @@ -79,4 +79,4 @@ namespace std #endif // _MSC_VER -#endif +#endif diff --git a/eo/src/utils/eoCheckPoint.h b/eo/src/utils/eoCheckPoint.h index d6df8b78..ea562e8b 100644 --- a/eo/src/utils/eoCheckPoint.h +++ b/eo/src/utils/eoCheckPoint.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // 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 @@ -52,12 +52,12 @@ */ /** eoCheckPoint is a container class. - It contains std::vectors of (pointers to) + 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 - + 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 + 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. */ @@ -66,7 +66,7 @@ class eoCheckPoint : public eoContinue { public : - eoCheckPoint(eoContinue& _cont) + eoCheckPoint(eoContinue& _cont) { continuators.push_back(&_cont); } @@ -118,31 +118,31 @@ bool eoCheckPoint::operator()(const eoPop& _pop) bool bContinue = true; for (i = 0; i < continuators.size(); ++i) - if ( !(*continuators[i])(_pop) ) - bContinue = false; + if ( !(*continuators[i])(_pop) ) + bContinue = false; - if (! bContinue) // we're going to stop: lastCall, gentlemen + 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); + 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 < updaters.size(); ++i) + updaters[i]->lastCall(); - for (i = 0; i < monitors.size(); ++i) - monitors[i]->lastCall(); + for (i = 0; i < monitors.size(); ++i) + monitors[i]->lastCall(); } return bContinue; } -/** returns a string with all className() +/** returns a string with all className() * of data separated with "\n" (for debugging) */ template diff --git a/eo/src/utils/eoData.h b/eo/src/utils/eoData.h index ea70cabe..876b0095 100644 --- a/eo/src/utils/eoData.h +++ b/eo/src/utils/eoData.h @@ -45,4 +45,3 @@ #define eo_is_an_integer false #endif - diff --git a/eo/src/utils/eoDistance.h b/eo/src/utils/eoDistance.h index 1a7c9edd..b26f249d 100644 --- a/eo/src/utils/eoDistance.h +++ b/eo/src/utils/eoDistance.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // 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 @@ -28,11 +28,11 @@ #include -/** @addtogroup Stats +/** @addtogroup Stats * @{ * */ -/** +/** This is a generic class for distance functors: takes 2 things and returns a double */ @@ -41,8 +41,8 @@ class eoDistance : public eoBF {}; -/** - This is a generic class for Euclidain distance (L2 norm) computation: +/** + 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 > @@ -54,16 +54,16 @@ public: double sum=0.0; for (unsigned i=0; i<_v1.size(); i++) { - double r = static_cast (_v1[i]) - static_cast (_v2[i]); - sum += r*r; + double r = static_cast (_v1[i]) - static_cast (_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 +/** + 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 */ @@ -76,15 +76,15 @@ public: double sum=0.0; for (unsigned i=0; i<_v1.size(); i++) { - double r = static_cast (_v1[i]) - static_cast (_v2[i]); - sum += fabs(r); + double r = static_cast (_v1[i]) - static_cast (_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 ... +/* 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 > @@ -100,5 +100,5 @@ public: /** @} */ - + #endif diff --git a/eo/src/utils/eoFDCStat.h b/eo/src/utils/eoFDCStat.h index a604533f..1d2050b7 100644 --- a/eo/src/utils/eoFDCStat.h +++ b/eo/src/utils/eoFDCStat.h @@ -33,7 +33,7 @@ /** The Fitness Distance Correlation computation. - + Stores the values into eoValueParam so they can be snapshot by some eoGnuplotSnapshot ... @@ -53,7 +53,7 @@ public: /** Ctor with the optimum */ eoFDCStat(eoDistance & _dist, EOT & _theBest, - std::string _description = "FDC") : + std::string _description = "FDC") : eoStat(0, _description), dist(_dist), theBest(_theBest), boolOpt(true) {} @@ -63,30 +63,30 @@ public: virtual void operator()(const eoPop& _pop) { unsigned i; - if (!boolOpt) // take the local best - theBest = _pop.best_element(); + 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 & dist; EOT theBest; - bool boolOpt; // whether the best is known or not + bool boolOpt; // whether the best is known or not eoValueParam > distToBest; eoValueParam > fitnesses; }; @@ -119,12 +119,12 @@ 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 + and fitnesses) are added to the monitor so they can be processed later to a file - and eventually by gnuplot */ eoFDCFileSnapshot(eoFDCStat & _FDCstat, - std::string _dirname = "tmpFDC", unsigned _frequency = 1, - std::string _filename = "FDC", std::string _delim = " "): + std::string _dirname = "tmpFDC", unsigned _frequency = 1, + std::string _filename = "FDC", std::string _delim = " "): eoFileSnapshot(_dirname, _frequency, _filename, _delim), FDCstat(_FDCstat) { @@ -142,4 +142,3 @@ private: }; #endif - diff --git a/eo/src/utils/eoFeasibleRatioStat.h b/eo/src/utils/eoFeasibleRatioStat.h index 8d669dbe..cbbe1738 100644 --- a/eo/src/utils/eoFeasibleRatioStat.h +++ b/eo/src/utils/eoFeasibleRatioStat.h @@ -1,11 +1,10 @@ - /* (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 + 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, @@ -46,11 +45,11 @@ public: eoFeasibleRatioStat( std::string description = "FeasibleRatio" ) : eoStat( 0.0, description ) {} - virtual void operator()( const eoPop & pop ) + virtual void operator()( const eoPop & pop ) { #ifndef NDEBUG assert( pop.size() > 0 ); - + double count = static_cast( std::count_if( pop.begin(), pop.end(), eoIsFeasible ) ); double size = static_cast( pop.size() ); double ratio = count/size; @@ -60,9 +59,8 @@ public: value() = static_cast( std::count_if( pop.begin(), pop.end(), eoIsFeasible ) ) / static_cast( pop.size() ); #endif } - + virtual std::string className(void) const { return "eoFeasibleRatioStat"; } }; #endif // _eoFeasibleRatioStat_h_ - diff --git a/eo/src/utils/eoFileMonitor.cpp b/eo/src/utils/eoFileMonitor.cpp index cd5cbab6..3cc96deb 100644 --- a/eo/src/utils/eoFileMonitor.cpp +++ b/eo/src/utils/eoFileMonitor.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include #include @@ -32,21 +32,21 @@ void eoFileMonitor::printHeader(std::ostream& os) void eoFileMonitor::printHeader() { // create file - ofstream os(filename.c_str()); + 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 ? + ofstream os(filename.c_str(), + overwrite ? ios_base::out|ios_base::trunc // truncate : ios_base::out|ios_base::app // append @@ -58,7 +58,7 @@ eoMonitor& eoFileMonitor::operator()(void) throw runtime_error(str); } - if ( + 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 @@ -67,17 +67,17 @@ eoMonitor& eoFileMonitor::operator()(void) 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(); @@ -87,4 +87,3 @@ eoMonitor& eoFileMonitor::operator()(std::ostream& os) return *this; } - diff --git a/eo/src/utils/eoFileMonitor.h b/eo/src/utils/eoFileMonitor.h index b89fd1e6..9438d25c 100644 --- a/eo/src/utils/eoFileMonitor.h +++ b/eo/src/utils/eoFileMonitor.h @@ -58,16 +58,16 @@ public : * @param _overwrite if true, overwrite the existing file */ eoFileMonitor( - std::string _filename, - std::string _delim = " ", - bool _keep_existing = false, + 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), + : filename(_filename), + delim(_delim), + keep(_keep_existing), + header(_header), firstcall(true), overwrite(_overwrite) { @@ -84,7 +84,7 @@ public : //! 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. + /*! 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); @@ -104,13 +104,13 @@ private : //! delimiter to use between each write std::string delim; - + //! should we append or create a new file - bool keep; - + bool keep; + //! printing header at begin of file? bool header; - + //! flag to avoid calling twice operator()(void) bool firstcall; diff --git a/eo/src/utils/eoFileSnapshot.h b/eo/src/utils/eoFileSnapshot.h index b5d5142b..cdd2e36c 100644 --- a/eo/src/utils/eoFileSnapshot.h +++ b/eo/src/utils/eoFileSnapshot.h @@ -58,7 +58,7 @@ public : typedef eoValueParam > vDoubleParam; eoFileSnapshot(std::string _dirname, unsigned _frequency = 1, std::string _filename = "gen", - std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true): + std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true): dirname(_dirname), frequency(_frequency), filename(_filename), delim(_delim), counter(_counter), boolChanged(true) { @@ -71,11 +71,11 @@ public : // now make sure there is a dir without any genXXX file in it if (res) // no dir present { - s = std::string("mkdir ")+dirname; + s = std::string("mkdir ")+dirname; } else if (!res && _rmFiles) { - s = std::string("/bin/rm ")+dirname+ "/" + filename + "*"; + s = std::string("/bin/rm ")+dirname+ "/" + filename + "*"; } else s = " "; @@ -111,9 +111,9 @@ public : { if (counter % frequency) { - boolChanged = false; // subclass with gnuplot will do nothing - counter++; - return (*this); + boolChanged = false; // subclass with gnuplot will do nothing + counter++; + return (*this); } counter++; boolChanged = true; @@ -137,35 +137,35 @@ public : static_cast >* >(vec[0]); const std::vector v = ptParam->value(); - if (vec.size() == 1) // only one std::vector: -> add number in front + if (vec.size() == 1) // only one std::vector: -> add number in front { - for (unsigned k=0; k > vv(vec.size()); - vv[0]=v; - for (unsigned i=1; i >* >(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 > vv(vec.size()); + vv[0]=v; + for (unsigned i=1; i >* >(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(T(), _description), func(f) {} - + using eoStat::value; - + void operator()(const eoPop& pop) { value() = func(pop); } @@ -32,7 +31,7 @@ private: func_t func; }; -/** +/** * @ingroup Stats */ template @@ -43,4 +42,3 @@ eoFuncPtrStat& makeFuncPtrStat( T (*func)(const eoPop&), eoFunctorS } #endif - diff --git a/eo/src/utils/eoGnuplot1DSnapshot.h b/eo/src/utils/eoGnuplot1DSnapshot.h index 05015b64..38c5af74 100644 --- a/eo/src/utils/eoGnuplot1DSnapshot.h +++ b/eo/src/utils/eoGnuplot1DSnapshot.h @@ -64,8 +64,8 @@ class eoGnuplot1DSnapshot: public eoFileSnapshot, public eoGnuplot // Ctor eoGnuplot1DSnapshot(std::string _dirname, eoRealVectorBounds & _bounds, - unsigned _frequency = 1, std::string _filename = "gen", - std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true ) : + 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) diff --git a/eo/src/utils/eoHowMany.h b/eo/src/utils/eoHowMany.h index 2f02216e..1105f3b7 100644 --- a/eo/src/utils/eoHowMany.h +++ b/eo/src/utils/eoHowMany.h @@ -123,7 +123,7 @@ public: if (count == 0) { unsigned int res = static_cast( std::ceil( rate * _size ) ); - + if( res == 0 ) { eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (rate=" << rate << ", size=" << _size << ")" << std::endl; } diff --git a/eo/src/utils/eoIntBounds.cpp b/eo/src/utils/eoIntBounds.cpp index 59350240..11cd942d 100644 --- a/eo/src/utils/eoIntBounds.cpp +++ b/eo/src/utils/eoIntBounds.cpp @@ -60,12 +60,12 @@ eoIntBounds* eoGeneralIntBounds::getBoundsFromString(std::string _value) std::string sMinBounds = sBounds.substr(0,posDelim); if ( (sMinBounds != std::string("-inf")) && - (sMinBounds != std::string("-infinity")) - ) - { - minBounded = true; - minBound = read_int(sMinBounds); - } + (sMinBounds != std::string("-infinity")) + ) + { + minBounded = true; + minBound = read_int(sMinBounds); + } // max bound size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); @@ -73,26 +73,26 @@ eoIntBounds* eoGeneralIntBounds::getBoundsFromString(std::string _value) std::string sMaxBounds = sBounds.substr(posEndDelim); if ( (sMaxBounds != std::string("+inf")) && - (sMaxBounds != std::string("+infinity")) - ) - { - maxBounded = true; - maxBound = read_int(sMaxBounds); - } + (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); - } + { + 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; + locBound = new eoIntNoBounds; else if (!minBounded && maxBounded) - locBound = new eoIntAboveBound(maxBound); + locBound = new eoIntAboveBound(maxBound); else if (minBounded && !maxBounded) - locBound = new eoIntBelowBound(minBound); + locBound = new eoIntBelowBound(minBound); return locBound; } diff --git a/eo/src/utils/eoIntBounds.h b/eo/src/utils/eoIntBounds.h index 807751da..2127c92f 100644 --- a/eo/src/utils/eoIntBounds.h +++ b/eo/src/utils/eoIntBounds.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // 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 @@ -27,7 +27,7 @@ #ifndef _eoIntBounds_h #define _eoIntBounds_h -#include // std::exceptions! +#include // std::exceptions! #include /** @@ -42,24 +42,24 @@ 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 +- 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 +- 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, +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 +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, +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] @@ -68,7 +68,7 @@ THis file also contains the declaration of *the* global object that is the unbounded bound */ class eoIntBounds : public eoPersistent -{ +{ public: virtual ~eoIntBounds(){} @@ -97,7 +97,7 @@ public: */ virtual void foldsInBounds(double &) const = 0; - /** foldsInBounds for ints: + /** foldsInBounds for ints: * call the method for double and convert back */ virtual void foldsInBounds(long int & i) const { @@ -112,24 +112,24 @@ public: /** truncate for ints: call the method for double and convert back */ - virtual void truncate(long int & i) const + virtual void truncate(long int & i) const { double r = double(i); truncate(r); i = (long int)(r); } - /** get minimum value + /** 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 @@ -165,11 +165,11 @@ public: { throw std::logic_error("Trying to get minimum of unbounded eoIntBounds"); } - virtual long int maximum() const + virtual long int maximum() const { throw std::logic_error("Trying to get maximum of unbounded eoIntBounds"); } - virtual long int range() const + virtual long int range() const { throw std::logic_error("Trying to get range of unbounded eoIntBounds"); } @@ -212,7 +212,7 @@ public: } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntNoBounds(*this); } @@ -236,18 +236,18 @@ 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) + 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 + // accessors virtual long int minimum() const { return repMinimum; } virtual long int maximum() const { return repMaximum; } virtual long int range() const { return repRange; } @@ -258,18 +258,18 @@ public : virtual bool isMinBounded(void) const {return true;} virtual bool isMaxBounded(void) const {return true;} - virtual double uniform(eoRng & _rng = eo::rng) const + virtual double uniform(eoRng & _rng = eo::rng) const { return repMinimum + _rng.uniform(repRange); - } + } - virtual long int random(eoRng & _rng = eo::rng) const + 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 + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -279,36 +279,36 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { long iloc; double dlargloc = 2 * range() ; if (fabs(_r) > 1.0E9) // iloc too large! { - _r = uniform(); - return; + _r = uniform(); + return; } if ( (_r > maximum()) ) { - iloc = (long) ( (_r-minimum()) / dlargloc ) ; - _r -= dlargloc * iloc ; - if ( _r > maximum() ) - _r = 2*maximum() - _r ; + iloc = (long) ( (_r-minimum()) / dlargloc ) ; + _r -= dlargloc * iloc ; + if ( _r > maximum() ) + _r = 2*maximum() - _r ; } - - if (_r < minimum()) + + if (_r < minimum()) { - iloc = (long) ( (maximum()-_r) / dlargloc ) ; - _r += dlargloc * iloc ; - if (_r < minimum()) - _r = 2*minimum() - _r ; + 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 + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -341,7 +341,7 @@ public : } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntInterval(*this); } @@ -349,7 +349,7 @@ public : private : long int repMinimum; long int repMaximum; - long int repRange; // to minimize operations ??? + long int repRange; // to minimize operations ??? }; /** @@ -361,22 +361,22 @@ private : class eoIntBelowBound : public eoIntBounds { public : - virtual ~eoIntBelowBound(){} - /** + virtual ~eoIntBelowBound(){} + /** Simple bounds = minimum */ - eoIntBelowBound(long int _min=0) : + eoIntBelowBound(long int _min=0) : repMinimum(_min) {} - // accessors + // accessors virtual long int minimum() const { return repMinimum; } - virtual long int maximum() const + virtual long int maximum() const { throw std::logic_error("Trying to get maximum of eoIntBelowBound"); } - virtual long int range() const + virtual long int range() const { throw std::logic_error("Trying to get range of eoIntBelowBound"); } @@ -402,7 +402,7 @@ public : virtual bool isMaxBounded(void) const {return false;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -410,16 +410,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. minimum - if (_r < repMinimum) // nothing to do otherwise + if (_r < repMinimum) // nothing to do otherwise _r = 2*repMinimum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -450,7 +450,7 @@ public : } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntBelowBound(*this); } @@ -469,22 +469,22 @@ class eoIntAboveBound : public eoIntBounds { public : virtual ~eoIntAboveBound(){} - - /** + + /** Simple bounds = minimum */ - eoIntAboveBound(long int _max=0) : + eoIntAboveBound(long int _max=0) : repMaximum(_max) {} - // accessors + // accessors virtual long int maximum() const { return repMaximum; } - virtual long int minimum() const + virtual long int minimum() const { throw std::logic_error("Trying to get minimum of eoIntAboveBound"); } - virtual long int range() const + virtual long int range() const { throw std::logic_error("Trying to get range of eoIntAboveBound"); } @@ -510,7 +510,7 @@ public : virtual bool isMaxBounded(void) const {return true;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r > repMaximum) return false; @@ -518,16 +518,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. maximum - if (_r > repMaximum) // nothing to do otherwise + if (_r > repMaximum) // nothing to do otherwise _r = 2*repMaximum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r > repMaximum) _r = repMaximum; @@ -558,7 +558,7 @@ public : } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntAboveBound(*this); } @@ -598,13 +598,13 @@ public: if (maxBounded) maximum = bb.maximum(); if (minBounded && maxBounded) - repBound = new eoIntInterval(minimum, maximum); + repBound = new eoIntInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoIntNoBounds; + repBound = new eoIntNoBounds; else if (!minBounded && maxBounded) - repBound = new eoIntAboveBound(maximum); + repBound = new eoIntAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoIntBelowBound(minimum); + repBound = new eoIntBelowBound(minimum); } eoGeneralIntBounds& operator=(const eoGeneralIntBounds& _b) @@ -624,13 +624,13 @@ public: delete repBound; // now reallocate if (minBounded && maxBounded) - repBound = new eoIntInterval(minimum, maximum); + repBound = new eoIntInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoIntNoBounds; + repBound = new eoIntNoBounds; else if (!minBounded && maxBounded) - repBound = new eoIntAboveBound(maximum); + repBound = new eoIntAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoIntBelowBound(minimum); + repBound = new eoIntBelowBound(minimum); return (*this); } @@ -671,17 +671,17 @@ public: */ virtual void truncate(double & _x) const {return repBound->truncate(_x);} - /** get minimum value + /** 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 @@ -698,9 +698,9 @@ public: virtual eoIntBounds * dup() const {return repBound->dup();} /** for efficiency, it's better to use the embedded boud directly */ - const eoIntBounds & theBounds() const { return *repBound;} + const eoIntBounds & theBounds() const { return *repBound;} - /** don't forget the printOn method - + /** don't forget the printOn method - * again that of the embedded bound */ virtual void printOn(std::ostream& _os) const @@ -709,7 +709,7 @@ public: } /** no readFrom ??? Have to check that later */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { std::string s; _is >> s; diff --git a/eo/src/utils/eoLogger.cpp b/eo/src/utils/eoLogger.cpp index ff6f8407..b3002f46 100644 --- a/eo/src/utils/eoLogger.cpp +++ b/eo/src/utils/eoLogger.cpp @@ -1,7 +1,7 @@ // -*- 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 @@ -20,7 +20,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo Caner Candan @@ -87,10 +87,10 @@ void eoLogger::printLevels() const std::cout << "Available verbose levels:" << std::endl; for (std::vector::const_iterator it = _sortedLevels.begin(), end = _sortedLevels.end(); - it != end; ++it) - { - std::cout << "\t" << *it << std::endl; - } + it != end; ++it) + { + std::cout << "\t" << *it << std::endl; + } ::exit(0); } @@ -116,15 +116,15 @@ eoLogger& operator<<(eoLogger& l, eo::setlevel v) 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]; - } + { + l._fd = l._standard_io_streams[&os]; + } return l; } eoLogger::outbuf::outbuf(const int& fd, - const eo::Levels& contexlvl, - const eo::Levels& selectedlvl) + const eo::Levels& contexlvl, + const eo::Levels& selectedlvl) : _fd(fd), _contextLevel(contexlvl), _selectedLevel(selectedlvl) {} @@ -132,11 +132,11 @@ int eoLogger::outbuf::overflow(int_type c) { if (_selectedLevel >= _contextLevel) { - if (_fd >= 0 && c != EOF) - { - ssize_t num; - num = ::write(_fd, &c, 1); - } + if (_fd >= 0 && c != EOF) + { + ssize_t num; + num = ::write(_fd, &c, 1); + } } return c; } @@ -144,14 +144,14 @@ int eoLogger::outbuf::overflow(int_type c) namespace eo { file::file(const std::string f) - : _f(f) + : _f(f) {} setlevel::setlevel(const std::string v) - : _v(v), _lvl((Levels)-1) + : _v(v), _lvl((Levels)-1) {} setlevel::setlevel(const Levels lvl) - : _v(std::string("")), _lvl(lvl) + : _v(std::string("")), _lvl(lvl) {} } diff --git a/eo/src/utils/eoLogger.h b/eo/src/utils/eoLogger.h index c5ca7e3d..11b0cbee 100644 --- a/eo/src/utils/eoLogger.h +++ b/eo/src/utils/eoLogger.h @@ -1,6 +1,6 @@ // -*- 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 @@ -19,7 +19,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo Caner Candan @@ -106,12 +106,12 @@ namespace eo * /!\ 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}; + errors, + warnings, + progress, + logging, + debug, + xdebug}; /** * file @@ -119,8 +119,8 @@ namespace eo */ struct file { - file(const std::string f); - const std::string _f; + file(const std::string f); + const std::string _f; }; /** @@ -129,10 +129,10 @@ namespace eo */ struct setlevel { - setlevel(const std::string v); - setlevel(const Levels lvl); - const std::string _v; - const Levels _lvl; + setlevel(const std::string v); + setlevel(const Levels lvl); + const std::string _v; + const Levels _lvl; }; } @@ -142,7 +142,7 @@ namespace eo * Use of a global variable eo::log to easily use the logger like std::cout */ class eoLogger : public eoObject, - public std::ostream + public std::ostream { public: eoLogger(); @@ -159,7 +159,7 @@ public: * if( eo::log.getLevelSelected() >= eo::progress ) {...} */ eo::Levels getLevelSelected() const { return _selectedLevel; } - + /*! Returns the current level of the context * the one given when you output message with the logger */ @@ -176,15 +176,15 @@ private: class outbuf : public std::streambuf { public: - outbuf(const int& fd, - const eo::Levels& contexlvl, - const eo::Levels& selectedlvl); + outbuf(const int& fd, + const eo::Levels& contexlvl, + const eo::Levels& selectedlvl); protected: - virtual int overflow(int_type c); + virtual int overflow(int_type c); private: - const int& _fd; - const eo::Levels& _contextLevel; - const eo::Levels& _selectedLevel; + const int& _fd; + const eo::Levels& _contextLevel; + const eo::Levels& _selectedLevel; }; private: diff --git a/eo/src/utils/eoMOFitnessStat.h b/eo/src/utils/eoMOFitnessStat.h index 64102139..8e1b2d3f 100644 --- a/eo/src/utils/eoMOFitnessStat.h +++ b/eo/src/utils/eoMOFitnessStat.h @@ -85,7 +85,7 @@ public: } } private: - unsigned int objective; // The objective we're storing + unsigned int objective; // The objective we're storing }; #endif diff --git a/eo/src/utils/eoMonitor.h b/eo/src/utils/eoMonitor.h index e02900f2..1c92e9c0 100644 --- a/eo/src/utils/eoMonitor.h +++ b/eo/src/utils/eoMonitor.h @@ -1,7 +1,7 @@ // -*- 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 @@ -31,7 +31,7 @@ /** @defgroup Monitors Monitoring * - * Monitors take a set of value parameters (eoValueParam) objects and + * 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 diff --git a/eo/src/utils/eoOStreamMonitor.cpp b/eo/src/utils/eoOStreamMonitor.cpp index 3a29dd68..3365301e 100644 --- a/eo/src/utils/eoOStreamMonitor.cpp +++ b/eo/src/utils/eoOStreamMonitor.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include #include diff --git a/eo/src/utils/eoOStreamMonitor.h b/eo/src/utils/eoOStreamMonitor.h index 7436f6ef..b09a11b5 100644 --- a/eo/src/utils/eoOStreamMonitor.h +++ b/eo/src/utils/eoOStreamMonitor.h @@ -1,4 +1,3 @@ - /* (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 @@ -22,7 +21,7 @@ Authors: todos@geneura.ugr.es Marc.Schoenauer@polytechnique.fr mkeijzer@dhi.dk - Johann Dréo + Johann Dréo */ #ifndef _eoOStreamMonitor_h_ @@ -45,15 +44,15 @@ Authors: 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) + 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) { - (void)_verbose; + (void)_verbose; 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; } - eoOStreamMonitor( std::ostream & _out, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : - out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) + 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); @@ -69,4 +68,3 @@ private : }; #endif // _eoOStreamMonitor_h_ - diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index e0ce63aa..d9d09c38 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -45,11 +45,11 @@ 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; - } + { + double _t_end = omp_get_wtime(); + eoLogger log; + log << eo::file("measure_" + prefix()) << _t_end - _t_start << std::endl; + } #endif // !_OPENMP } @@ -63,20 +63,20 @@ std::string eoParallel::prefix() const std::string value( _prefix.value() ); if ( _isEnabled.value() ) - { - if ( _isDynamic.value() ) - { - value += "_dynamic.out"; - } - else - { - value += "_parallel.out"; - } - } + { + if ( _isDynamic.value() ) + { + value += "_dynamic.out"; + } + else + { + value += "_parallel.out"; + } + } else - { - value += "_sequential.out"; - } + { + value += "_sequential.out"; + } return value; } @@ -98,17 +98,17 @@ void make_parallel(eoParser& parser) #ifdef _OPENMP if ( eo::parallel.isEnabled() ) - { - if ( eo::parallel.nthreads() > 0 ) - { - omp_set_num_threads( eo::parallel.nthreads() ); - } - } + { + if ( eo::parallel.nthreads() > 0 ) + { + omp_set_num_threads( eo::parallel.nthreads() ); + } + } if ( eo::parallel.doMeasure() ) - { - eo::parallel._t_start = omp_get_wtime(); - } + { + eo::parallel._t_start = omp_get_wtime(); + } #endif // !_OPENMP } diff --git a/eo/src/utils/eoParam.h b/eo/src/utils/eoParam.h index 868507cf..948092c9 100644 --- a/eo/src/utils/eoParam.h +++ b/eo/src/utils/eoParam.h @@ -135,8 +135,8 @@ private: /** eoValueParam: templatized derivation of eoParam. Can be used to contain - any scalar value type. It makes use of std::strstream to get and set values. - + 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 and @@ -186,7 +186,7 @@ public : /** Change the parameter value */ - void value( ValueType val ) + void value( ValueType val ) { // convert to string std::ostringstream os; @@ -431,7 +431,7 @@ public: // Here, we do have args _os << "("; - if (narg == 1) // 1 arg only + if (narg == 1) // 1 arg only { _os << second[0] << ")" ; return _os; @@ -453,9 +453,9 @@ public: void readFrom(std::string & _value) { - second.resize(0); // just in case + second.resize(0); // just in case size_t pos = _value.find('('); - if (pos >= _value.size()) // no arguments + if (pos >= _value.size()) // no arguments { first = _value; return; @@ -484,4 +484,3 @@ std::istream & operator>>(std::istream & _is, eoParamParamType & _rate); /** @} */ #endif - diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index 23970023..7150882a 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -74,19 +74,19 @@ eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, unsigned i; for (i = 1; i < _argc; ++i) { - if(_argv[i][0] == '@') + 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) + 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); + 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 '@' + // read - will be overwritten by command-line + readFrom(ifs); + break; // stop reading command line args for '@' } } // now read arguments on command-line @@ -188,59 +188,59 @@ void eoParser::readFrom(istream& is) processing = (str.find(string("Parser"))= 3) value = string(str.begin() + 3, str.end()); - } + } else - { + { value = string(str.begin() + 2, str.end()); - } - } + } + } shortNameMap[str[1]] = value; - } - } - } + } + } + } } updateParameters(); @@ -268,8 +268,8 @@ void eoParser::printOn(ostream& os) const eoParam* param = p->second; - if (!isItThere(*param)) // comment out the ones not set by the user - os << "# "; + if (!isItThere(*param)) // comment out the ones not set by the user + os << "# "; string str = "--" + param->longName() + "=" + param->getValue(); @@ -329,12 +329,12 @@ void eoParser::printHelp(ostream& os) } if (p->second->shortName()) - os << "-" << p->second->shortName() << ", "; + os << "-" << p->second->shortName() << ", "; os << "--" <second->longName() <<":\t" - << p->second->description() ; + << p->second->description() ; - os << "\n" << setw(20) << ( (p->second->required())?"Required":"Optional" ); + os << "\n" << setw(20) << ( (p->second->required())?"Required":"Optional" ); os <<". By default: "<second->defValue() << '\n'; } // for p @@ -377,7 +377,7 @@ bool eoParser::userNeedsHelp(void) // search for unknown short names for (ShortNameMapType::const_iterator sIt = shortNameMap.begin(); sIt != shortNameMap.end(); ++sIt) - { + { char entry = sIt->first; MultiMapType::const_iterator it; @@ -403,7 +403,7 @@ bool eoParser::userNeedsHelp(void) string msg = "Use -h or --help to get help about available parameters"; messages.push_back( msg ); } - + } // if stopOnUnknownParam return needHelp.value() || !messages.empty(); @@ -421,4 +421,3 @@ istream & operator>>(istream & _is, eoParamParamType & _rate) _rate.readFrom(_is); return _is; } - diff --git a/eo/src/utils/eoParser.h b/eo/src/utils/eoParser.h index a96ec1be..0088ff4f 100644 --- a/eo/src/utils/eoParser.h +++ b/eo/src/utils/eoParser.h @@ -119,7 +119,7 @@ public: * @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'); + std::string _lFileParamName = "param-file", char _shortHand = 'p'); /** Processes the parameter and puts it in the appropriate section for readability diff --git a/eo/src/utils/eoParserLogger.cpp b/eo/src/utils/eoParserLogger.cpp index 21b67f6c..df70589a 100644 --- a/eo/src/utils/eoParserLogger.cpp +++ b/eo/src/utils/eoParserLogger.cpp @@ -25,10 +25,10 @@ Caner Candan #include "eoParserLogger.h" eoParserLogger::eoParserLogger(unsigned _argc, char** _argv, - std::string _programDescription /*= ""*/ - , - std::string _lFileParamName /*= "param-file"*/, - char _shortHand /*= 'p'*/) + std::string _programDescription /*= ""*/ + , + std::string _lFileParamName /*= "param-file"*/, + char _shortHand /*= 'p'*/) : eoParser(_argc, _argv, _programDescription, _lFileParamName, _shortHand), _verbose("quiet", "verbose", "Set the verbose level", 'v'), _printVerboseLevels(false, "print-verbose-levels", "Print verbose levels", 'l'), @@ -50,9 +50,9 @@ eoParserLogger::eoParserLogger(unsigned _argc, char** _argv, //------------------------------------------------------------------ if ( ! _output.value().empty() ) - { - eo::log << eo::file( _output.value() ); - } + { + eo::log << eo::file( _output.value() ); + } //------------------------------------------------------------------ @@ -62,9 +62,9 @@ eoParserLogger::eoParserLogger(unsigned _argc, char** _argv, //------------------------------------------------------------------ if ( _printVerboseLevels.value() ) - { - eo::log.printLevels(); - } + { + eo::log.printLevels(); + } //------------------------------------------------------------------ diff --git a/eo/src/utils/eoParserLogger.h b/eo/src/utils/eoParserLogger.h index 20f67652..48cb53ec 100644 --- a/eo/src/utils/eoParserLogger.h +++ b/eo/src/utils/eoParserLogger.h @@ -17,8 +17,8 @@ Contact: http://eodev.sourceforge.net Authors: - Johann Dréo - Caner Candan + Johann Dréo + Caner Candan */ #ifndef EO_PARSER_LOGGER_H @@ -37,9 +37,9 @@ class eoParserLogger : public eoParser { public: eoParserLogger(unsigned _argc, char** _argv, - std::string _programDescription = "", - std::string _lFileParamName = "param-file", - char _shortHand = 'p'); + std::string _programDescription = "", + std::string _lFileParamName = "param-file", + char _shortHand = 'p'); ~eoParserLogger(); private: diff --git a/eo/src/utils/eoPopStat.h b/eo/src/utils/eoPopStat.h index 86c5dc04..f3f091a6 100644 --- a/eo/src/utils/eoPopStat.h +++ b/eo/src/utils/eoPopStat.h @@ -59,9 +59,9 @@ public: /** 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*/ + population*/ eoPopStat(unsigned _howMany = 0, std::string _desc ="") - : eoStat("", _desc), combien( _howMany) {} + : eoStat("", _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 @@ -119,15 +119,15 @@ public: */ void operator()(const std::vector& _pop) { - value() = ""; // empty + value() = ""; // empty unsigned howMany=combien?combien:_pop.size(); for (unsigned i = 0; i < howMany; ++i) { - std::ostringstream os; - os << *_pop[i] << std::endl; + std::ostringstream os; + os << *_pop[i] << std::endl; - // paranoid: - value() += os.str(); + // paranoid: + value() += os.str(); } } private: diff --git a/eo/src/utils/eoRNG.cpp b/eo/src/utils/eoRNG.cpp index 79a53d30..b538499f 100644 --- a/eo/src/utils/eoRNG.cpp +++ b/eo/src/utils/eoRNG.cpp @@ -16,4 +16,3 @@ namespace eo // global random number generator object eoRng rng(static_cast(time(0))); } - diff --git a/eo/src/utils/eoRNG.h b/eo/src/utils/eoRNG.h index 3cad9fcc..9885eff5 100644 --- a/eo/src/utils/eoRNG.h +++ b/eo/src/utils/eoRNG.h @@ -25,7 +25,7 @@ Old contact information: todos@geneura.ugr.es, http://geneura.ugr.es #ifndef EO_RANDOM_NUMBER_GENERATOR #define EO_RANDOM_NUMBER_GENERATOR -/** @addtogroup Random +/** @addtogroup Random * @{ * */ diff --git a/eo/src/utils/eoRealBounds.cpp b/eo/src/utils/eoRealBounds.cpp index 1667f644..89dcb358 100644 --- a/eo/src/utils/eoRealBounds.cpp +++ b/eo/src/utils/eoRealBounds.cpp @@ -78,7 +78,7 @@ void eoRealVectorBounds::readFrom(std::string _value) if (ownedBounds.size()>0) for (unsigned i = 0; i < ownedBounds.size(); ++i) { - delete ownedBounds[i]; + delete ownedBounds[i]; } ownedBounds.resize(0); factor.resize(0); @@ -89,29 +89,29 @@ void eoRealVectorBounds::readFrom(std::string _value) while (_value.size()>0) { if (!remove_leading(_value, delim)) // only delimiters were left - break; + 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; - } + { + 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"); + 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"); - } + { + 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); @@ -121,7 +121,7 @@ void eoRealVectorBounds::readFrom(std::string _value) 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"); + throw std::runtime_error("Syntax error when reading bounds"); bool minBounded=false, maxBounded=false; double minBound=0, maxBound=0; @@ -129,38 +129,38 @@ void eoRealVectorBounds::readFrom(std::string _value) // min bound std::string sMinBounds = sBounds.substr(0,posDelim); if (sMinBounds != std::string("-inf")) - { - minBounded = true; - minBound = read_double(sMinBounds); - } + { + 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); - } + { + maxBounded = true; + maxBound = read_double(sMaxBounds); + } // now create the eoRealBounds objects eoRealBounds *ptBounds; if (minBounded && maxBounded) - ptBounds = new eoRealInterval(minBound, maxBound); + ptBounds = new eoRealInterval(minBound, maxBound); else if (!minBounded && !maxBounded) // no bound at all - ptBounds = new eoRealNoBounds; + ptBounds = new eoRealNoBounds; else if (!minBounded && maxBounded) - ptBounds = new eoRealAboveBound(maxBound); + ptBounds = new eoRealAboveBound(maxBound); else if (minBounded && !maxBounded) - ptBounds = new eoRealBelowBound(minBound); + 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 1 already!) factor[factor.size()-1] += missing; } @@ -221,12 +221,12 @@ eoRealBounds* eoGeneralRealBounds::getBoundsFromString(std::string _value) std::string sMinBounds = sBounds.substr(0,posDelim); if ( (sMinBounds != std::string("-inf")) && - (sMinBounds != std::string("-infinity")) - ) - { - minBounded = true; - minBound = read_double(sMinBounds); - } + (sMinBounds != std::string("-infinity")) + ) + { + minBounded = true; + minBound = read_double(sMinBounds); + } // max bound size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); @@ -234,26 +234,26 @@ eoRealBounds* eoGeneralRealBounds::getBoundsFromString(std::string _value) std::string sMaxBounds = sBounds.substr(posEndDelim); if ( (sMaxBounds != std::string("+inf")) && - (sMaxBounds != std::string("+infinity")) - ) - { - maxBounded = true; - maxBound = read_double(sMaxBounds); - } + (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); - } + { + 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; + locBound = new eoRealNoBounds; else if (!minBounded && maxBounded) - locBound = new eoRealAboveBound(maxBound); + locBound = new eoRealAboveBound(maxBound); else if (minBounded && !maxBounded) - locBound = new eoRealBelowBound(minBound); + locBound = new eoRealBelowBound(minBound); return locBound; } diff --git a/eo/src/utils/eoRealBounds.h b/eo/src/utils/eoRealBounds.h index f79aac04..47c06100 100644 --- a/eo/src/utils/eoRealBounds.h +++ b/eo/src/utils/eoRealBounds.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // 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 @@ -27,7 +27,7 @@ #ifndef _eoRealBounds_h #define _eoRealBounds_h -#include // std::exceptions! +#include // std::exceptions! #include /** @@ -55,24 +55,24 @@ 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 +- 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 +- 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, +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 +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, +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] @@ -83,7 +83,7 @@ is the unbounded bound @ingroup Bounds */ class eoRealBounds : public eoPersistent -{ +{ public: virtual ~eoRealBounds(){} @@ -116,17 +116,17 @@ public: */ virtual void truncate(double &) const = 0; - /** get minimum value + /** 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 @@ -159,16 +159,16 @@ public: { throw std::logic_error("Trying to get minimum of unbounded eoRealBounds"); } - virtual double maximum() const + virtual double maximum() const { throw std::logic_error("Trying to get maximum of unbounded eoRealBounds"); } - virtual double range() const + virtual double range() const { throw std::logic_error("Trying to get range of unbounded eoRealBounds"); } - virtual double uniform(eoRng & _rng = eo::rng) const + virtual double uniform(eoRng & _rng = eo::rng) const { (void)_rng; @@ -199,7 +199,7 @@ public: } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealNoBounds(*this); } @@ -220,18 +220,18 @@ 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) + 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 + // accessors virtual double minimum() const { return repMinimum; } virtual double maximum() const { return repMaximum; } virtual double range() const { return repRange; } @@ -242,13 +242,13 @@ public : virtual bool isMinBounded(void) const {return true;} virtual bool isMaxBounded(void) const {return true;} - virtual double uniform(eoRng & _rng = eo::rng) const + 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 + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -258,36 +258,36 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { long iloc; double dlargloc = 2 * range() ; if (fabs(_r) > 1.0E9) // iloc too large! { - _r = uniform(); - return; + _r = uniform(); + return; } if ( (_r > maximum()) ) { - iloc = (long) ( (_r-minimum()) / dlargloc ) ; - _r -= dlargloc * iloc ; - if ( _r > maximum() ) - _r = 2*maximum() - _r ; + iloc = (long) ( (_r-minimum()) / dlargloc ) ; + _r -= dlargloc * iloc ; + if ( _r > maximum() ) + _r = 2*maximum() - _r ; } - - if (_r < minimum()) + + if (_r < minimum()) { - iloc = (long) ( (maximum()-_r) / dlargloc ) ; - _r += dlargloc * iloc ; - if (_r < minimum()) - _r = 2*minimum() - _r ; + 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 + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -320,7 +320,7 @@ public : } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealInterval(*this); } @@ -328,7 +328,7 @@ public : private : double repMinimum; double repMaximum; - double repRange; // to minimize operations ??? + double repRange; // to minimize operations ??? }; /** @@ -339,22 +339,22 @@ private : class eoRealBelowBound : public eoRealBounds { public : - virtual ~eoRealBelowBound(){} - /** + virtual ~eoRealBelowBound(){} + /** Simple bounds = minimum */ - eoRealBelowBound(double _min=0) : + eoRealBelowBound(double _min=0) : repMinimum(_min) {} - // accessors + // accessors virtual double minimum() const { return repMinimum; } - virtual double maximum() const + virtual double maximum() const { throw std::logic_error("Trying to get maximum of eoRealBelowBound"); } - virtual double range() const + virtual double range() const { throw std::logic_error("Trying to get range of eoRealBelowBound"); } @@ -374,7 +374,7 @@ public : virtual bool isMaxBounded(void) const {return false;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -382,16 +382,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. minimum - if (_r < repMinimum) // nothing to do otherwise + if (_r < repMinimum) // nothing to do otherwise _r = 2*repMinimum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -405,7 +405,7 @@ public : * but reading should not be done here, because of bound problems * see eoRealVectorBounds */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { (void)_is; @@ -422,7 +422,7 @@ public : } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealBelowBound(*this); } @@ -438,22 +438,22 @@ class eoRealAboveBound : public eoRealBounds { public : virtual ~eoRealAboveBound(){} - - /** + + /** Simple bounds = minimum */ - eoRealAboveBound(double _max=0) : + eoRealAboveBound(double _max=0) : repMaximum(_max) {} - // accessors + // accessors virtual double maximum() const { return repMaximum; } - virtual double minimum() const + virtual double minimum() const { throw std::logic_error("Trying to get minimum of eoRealAboveBound"); } - virtual double range() const + virtual double range() const { throw std::logic_error("Trying to get range of eoRealAboveBound"); } @@ -473,7 +473,7 @@ public : virtual bool isMaxBounded(void) const {return true;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r > repMaximum) return false; @@ -481,16 +481,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. maximum - if (_r > repMaximum) // nothing to do otherwise + if (_r > repMaximum) // nothing to do otherwise _r = 2*repMaximum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r > repMaximum) _r = repMaximum; @@ -521,7 +521,7 @@ public : } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealAboveBound(*this); } @@ -560,13 +560,13 @@ public: if (maxBounded) maximum = bb.maximum(); if (minBounded && maxBounded) - repBound = new eoRealInterval(minimum, maximum); + repBound = new eoRealInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoRealNoBounds; + repBound = new eoRealNoBounds; else if (!minBounded && maxBounded) - repBound = new eoRealAboveBound(maximum); + repBound = new eoRealAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoRealBelowBound(minimum); + repBound = new eoRealBelowBound(minimum); } eoGeneralRealBounds& operator=(const eoGeneralRealBounds& _b) @@ -586,13 +586,13 @@ public: delete repBound; // now reallocate if (minBounded && maxBounded) - repBound = new eoRealInterval(minimum, maximum); + repBound = new eoRealInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoRealNoBounds; + repBound = new eoRealNoBounds; else if (!minBounded && maxBounded) - repBound = new eoRealAboveBound(maximum); + repBound = new eoRealAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoRealBelowBound(minimum); + repBound = new eoRealBelowBound(minimum); return (*this); } @@ -633,17 +633,17 @@ public: */ virtual void truncate(double & _x) const {return repBound->truncate(_x);} - /** get minimum value + /** 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 @@ -655,9 +655,9 @@ public: virtual eoRealBounds * dup() const {return repBound->dup();} /** for efficiency, it's better to use the embedded boud directly */ - const eoRealBounds & theBounds() const { return *repBound;} + const eoRealBounds & theBounds() const { return *repBound;} - /** don't forget the printOn method - + /** don't forget the printOn method - * again that of the embedded bound */ virtual void printOn(std::ostream& _os) const @@ -666,7 +666,7 @@ public: } /** no readFrom ??? Have to check that later */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { std::string s; _is >> s; diff --git a/eo/src/utils/eoRealVectorBounds.h b/eo/src/utils/eoRealVectorBounds.h index 5e3a460f..56feff34 100644 --- a/eo/src/utils/eoRealVectorBounds.h +++ b/eo/src/utils/eoRealVectorBounds.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // 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 @@ -27,93 +27,93 @@ #ifndef _eoRealVectorBounds_h #define _eoRealVectorBounds_h -#include // std::exceptions! +#include // std::exceptions! #include #include /** Vector type for bounds (see eoRealBounds.h for scalar types) ------------ -Class eoRealVectorBounds implements the std::vectorized version: +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 +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 +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 + and also has a mechanism for memory handling of the pointers it has to allocate @ingroup Bounds */ class eoRealBaseVectorBounds : public std::vector -{ +{ public: // virtual desctructor (to avoid warning?) virtual ~eoRealBaseVectorBounds(){} - /** Default Ctor. + /** Default Ctor. */ eoRealBaseVectorBounds() : std::vector(0) {} /** Ctor: same bounds for everybody, given as an eoRealBounds */ - eoRealBaseVectorBounds(unsigned _dim, eoRealBounds & _bounds) : + eoRealBaseVectorBounds(unsigned _dim, eoRealBounds & _bounds) : std::vector(_dim, &_bounds) {} - + /** Ctor, particular case of dim-2 */ - eoRealBaseVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : + eoRealBaseVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : std::vector(0) { - push_back( &_xbounds); - push_back( &_ybounds); + push_back( &_xbounds); + push_back( &_ybounds); } - + /** test: is i_th component bounded */ - virtual bool isBounded(unsigned _i) - { + virtual bool isBounded(unsigned _i) + { return (*this)[_i]->isBounded(); } - + /** test: bounded iff all are bounded */ - virtual bool isBounded(void) + virtual bool isBounded(void) { for (unsigned i=0; iisBounded()) - return false; + return false; return true; } /** Self-test: true iff i_th component has no bounds at all */ - virtual bool hasNoBoundAtAll(unsigned _i) - { + virtual bool hasNoBoundAtAll(unsigned _i) + { return (*this)[_i]->hasNoBoundAtAll(); } - + /** Self-test: true iff all components have no bound at all */ - virtual bool hasNoBoundAtAll(void) + virtual bool hasNoBoundAtAll(void) { for (unsigned i=0; ihasNoBoundAtAll()) - return false; + return false; return true; } - virtual bool isMinBounded(unsigned _i) + virtual bool isMinBounded(unsigned _i) { return (*this)[_i]->isMinBounded();} ; - virtual bool isMaxBounded(unsigned _i) + virtual bool isMaxBounded(unsigned _i) { return (*this)[_i]->isMaxBounded();} ; /** Folds a real value back into the bounds - i_th component @@ -130,7 +130,7 @@ public: for (unsigned i=0; ifoldsInBounds(_v[i]); - } + } } /** Truncates a real value to the bounds - i_th component @@ -147,7 +147,7 @@ public: for (unsigned i=0; itruncate(_v[i]); - } + } } /** test: is i_th component within the bounds? @@ -161,7 +161,7 @@ public: { for (unsigned i=0; iprintOn(_os); - _os << ";"; + operator[](i)->printOn(_os); + _os << ";"; } } }; @@ -234,19 +234,19 @@ public: /** Ctor: same bounds for everybody, given as an eoRealBounds */ - eoRealVectorBounds(unsigned _dim, eoRealBounds & _bounds) : + eoRealVectorBounds(unsigned _dim, eoRealBounds & _bounds) : eoRealBaseVectorBounds(_dim, _bounds), factor(1,_dim), ownedBounds(0) {} - + /** Ctor, particular case of dim-2 */ - eoRealVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : + 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) : + eoRealVectorBounds(unsigned _dim, double _min, double _max) : eoRealBaseVectorBounds(), factor(1, _dim), ownedBounds(0) { if (_max-_min<=0) @@ -261,7 +261,7 @@ public: /** Ctor: different bounds for different variables, std::vectors of double */ - eoRealVectorBounds(std::vector _min, std::vector _max) : + eoRealVectorBounds(std::vector _min, std::vector _max) : factor(_min.size(), 1), ownedBounds(0) { if (_max.size() != _min.size()) @@ -270,9 +270,9 @@ public: eoRealBounds *ptBounds; for (unsigned i=0; i<_min.size(); i++) { - ptBounds = new eoRealInterval(_min[i], _max[i]); - ownedBounds.push_back(ptBounds); - push_back(ptBounds); + ptBounds = new eoRealInterval(_min[i], _max[i]); + ownedBounds.push_back(ptBounds); + push_back(ptBounds); } } @@ -320,26 +320,26 @@ public: unsigned int index=factor[0]; if (factor.size()>1) for (unsigned i=1; i 1) - _os << factor[i]; - operator[](index)->printOn(_os); - index += factor[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 + /** 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 +private:// WARNING: there is no reason for both std::vector below //to be synchronized in any manner - std::vector factor; // std::list of nb of "grouped" bounds - std::vector ownedBounds; + std::vector factor; // std::list of nb of "grouped" bounds + std::vector ownedBounds; // keep this one private eoRealVectorBounds& operator=(const eoRealVectorBounds&); }; @@ -352,19 +352,19 @@ private:// WARNING: there is no reason for both std::vector below @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) : + eoRealVectorNoBounds(unsigned _dim) : eoRealVectorBounds( (_dim?_dim:1), eoDummyRealNoBounds) {} - + virtual bool isBounded(unsigned) {return false;} virtual bool isBounded(void) {return false;} @@ -383,7 +383,7 @@ public: virtual bool isInBounds(unsigned, double) {return true;} virtual bool isInBounds(std::vector) {return true;} - // accessors + // accessors virtual double minimum(unsigned) { throw std::logic_error("Trying to get minimum of eoRealVectorNoBounds"); @@ -397,7 +397,7 @@ public: throw std::logic_error("Trying to get range of eoRealVectorNoBounds"); } - virtual double averageRange() + virtual double averageRange() { throw std::logic_error("Trying to get average range of eoRealVectorNoBounds"); } diff --git a/eo/src/utils/eoScalarFitnessStat.h b/eo/src/utils/eoScalarFitnessStat.h index f472722a..e56e4682 100644 --- a/eo/src/utils/eoScalarFitnessStat.h +++ b/eo/src/utils/eoScalarFitnessStat.h @@ -52,10 +52,10 @@ public: { value().resize(_popPters.size()); for (unsigned i=0; i<_popPters.size(); i++) - { - value()[i] = _popPters[i]->fitness(); - range.truncate(value()[i]); - } + { + value()[i] = _popPters[i]->fitness(); + range.truncate(value()[i]); + } } private : diff --git a/eo/src/utils/eoStat.h b/eo/src/utils/eoStat.h index 8529f1ce..916bcf43 100644 --- a/eo/src/utils/eoStat.h +++ b/eo/src/utils/eoStat.h @@ -44,7 +44,7 @@ Contact: http://eodev.sourceforge.net * * Compute various statistics on a population. * - * Objects of those classes are generally called by an eoCheckPoint + * 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. @@ -433,7 +433,7 @@ public: eoInterquartileRangeStat( typename EOT::Fitness start, std::string description = "IQR" ) : eoStat( start, description ) {} - virtual void operator()( const eoPop & _pop ) + virtual void operator()( const eoPop & _pop ) { if( _pop.size() == 0 ) { // how to implement value() = 0 ? @@ -444,14 +444,14 @@ public: 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() = Q1 - Q3; } } - + virtual std::string className(void) const { return "eoInterquartileRangeStat"; } }; /** @example t-eoIQRStat.cpp @@ -459,7 +459,7 @@ public: /** Compute the average size of indivudals over the population * - * Obviously, will work only on representations that implement the (standard) "size()" method, + * Obviously, will work only on representations that implement the (standard) "size()" method, * like any STL container. */ template @@ -469,10 +469,10 @@ public: using eoStat::value; - eoAverageSizeStat( std::string description = "Av.Size" ) : + eoAverageSizeStat( std::string description = "Av.Size" ) : eoStat( 0.0, description ) {} // 0 by default - virtual void operator()( const eoPop & pop ) + virtual void operator()( const eoPop & pop ) { size_t pop_size = pop.size(); @@ -487,10 +487,9 @@ public: value() = static_cast(sum) / static_cast(pop_size); } - + virtual std::string className(void) const { return "eoAverageSizeStat"; } }; /** @} */ #endif - diff --git a/eo/src/utils/eoState.cpp b/eo/src/utils/eoState.cpp index c5997fe1..d9d06d99 100644 --- a/eo/src/utils/eoState.cpp +++ b/eo/src/utils/eoState.cpp @@ -123,24 +123,24 @@ void eoState::load(std::istream& is) while (getline(is, str)) { - if (is.eof()) - throw runtime_error("No section in load file"); - if (is_section(str, name)) - break; + 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); + 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"); - } + 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"); + } } } @@ -172,7 +172,7 @@ string eoState::createObjectName(eoObject* obj) { if (obj == 0) { - ostringstream os; + ostringstream os; os << objectMap.size(); return os.str(); } @@ -184,7 +184,7 @@ string eoState::createObjectName(eoObject* obj) unsigned count = 1; while (it != objectMap.end()) { - ostringstream os; + ostringstream os; os << obj->className().c_str() << count++; name = os.str(); it = objectMap.find(name); @@ -192,4 +192,3 @@ string eoState::createObjectName(eoObject* obj) return name; } - diff --git a/eo/src/utils/eoStdoutMonitor.h b/eo/src/utils/eoStdoutMonitor.h index 91fcc11c..a1979b5d 100644 --- a/eo/src/utils/eoStdoutMonitor.h +++ b/eo/src/utils/eoStdoutMonitor.h @@ -1,6 +1,6 @@ // -*- 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 @@ -24,7 +24,7 @@ Authors: todos@geneura.ugr.es Marc.Schoenauer@polytechnique.fr mkeijzer@dhi.dk - Johann Dréo + Johann Dréo */ #ifndef _eoStdoutMonitor_h @@ -43,18 +43,17 @@ Authors: 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) - { + eoStdoutMonitor(bool _verbose, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + eoOStreamMonitor( std::cout, _verbose, _delim, _width, _fill) + { eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoStdutMonitor constructor is deprecated and will be removed in the next release" << std::endl; } - eoStdoutMonitor(std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : - eoOStreamMonitor( std::cout, _delim, _width, _fill) + 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 - diff --git a/eo/src/utils/eoTimeCounter.h b/eo/src/utils/eoTimeCounter.h index 5774844b..62371415 100644 --- a/eo/src/utils/eoTimeCounter.h +++ b/eo/src/utils/eoTimeCounter.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // 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 @@ -40,30 +40,30 @@ class eoTimeCounter : public eoUpdater, public eoValueParam { public: - eoTimeCounter() : eoValueParam(0.0, "Time") // : firstTime(true) + eoTimeCounter() : eoValueParam(0.0, "Time") // : firstTime(true) { start = time(NULL); } - - /** simply stores the time spent in process in its value() */ + + /** 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; + // 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; diff --git a/eo/src/utils/eoTimedMonitor.h b/eo/src/utils/eoTimedMonitor.h index aa660a79..a06ae6cc 100644 --- a/eo/src/utils/eoTimedMonitor.h +++ b/eo/src/utils/eoTimedMonitor.h @@ -51,25 +51,25 @@ public: eoTimedMonitor(unsigned seconds_) : last_tick(0), seconds(seconds_) {} eoMonitor& operator()(void) { - bool monitor = false; - if (last_tick == 0) { - monitor = true; - last_tick = clock(); - } + bool monitor = false; + if (last_tick == 0) { + monitor = true; + last_tick = clock(); + } - clock_t tick = clock(); + clock_t tick = clock(); - if ( (unsigned)(tick-last_tick) >= seconds * CLOCKS_PER_SEC) { - monitor = true; - } + 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; + 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); } diff --git a/eo/src/utils/eoUniformInit.h b/eo/src/utils/eoUniformInit.h index fa1b874d..cede61b7 100644 --- a/eo/src/utils/eoUniformInit.h +++ b/eo/src/utils/eoUniformInit.h @@ -24,8 +24,8 @@ */ //----------------------------------------------------------------------------- -/** Copied from the eoRndGenerators to have objects deriving from eoInit - * As the whole initialization mechanism in EO is based on eoInit rather than +/** 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 @@ -69,14 +69,14 @@ template class eoUniformInit : public eoInit public : /** Ctor with only a max bound */ eoUniformInit(T _max = T(1.0), eoRng& _rng = rng) : - minim(T(0.0)), range(_max), uniform(_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) @@ -84,14 +84,14 @@ template class eoUniformInit : public eoInit 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(uniform.uniform(range)); + void operator()(T & _t) + { + _t = minim+static_cast(uniform.uniform(range)); } private : diff --git a/eo/src/utils/eoUpdatable.h b/eo/src/utils/eoUpdatable.h index 4c029c54..202ef962 100644 --- a/eo/src/utils/eoUpdatable.h +++ b/eo/src/utils/eoUpdatable.h @@ -79,13 +79,13 @@ public : void operator()(void) { - time_t now = time(0); + time_t now = time(0); - if (now >= last_time + interval) - { - last_time = now; - eoDynUpdater::operator() (); - } + if (now >= last_time + interval) + { + last_time = now; + eoDynUpdater::operator() (); + } } private : const time_t interval; @@ -106,10 +106,10 @@ public : void operator()(void) { - if (++counter % interval == 0) - { - eoDynUpdater::operator() (); - } + if (++counter % interval == 0) + { + eoDynUpdater::operator() (); + } } private : const unsigned interval; diff --git a/eo/src/utils/eoUpdater.cpp b/eo/src/utils/eoUpdater.cpp index fa6ca109..dd6a3896 100644 --- a/eo/src/utils/eoUpdater.cpp +++ b/eo/src/utils/eoUpdater.cpp @@ -20,7 +20,7 @@ void eoTimedStateSaver::operator()(void) if (now >= last_time + interval) { last_time = now; - ostringstream os; + ostringstream os; os << prefix << (now - first_time) << '.' << extension; state.save(os.str()); } @@ -28,7 +28,7 @@ void eoTimedStateSaver::operator()(void) void eoCountedStateSaver::doItNow(void) { - ostringstream os; + ostringstream os; os << prefix << counter << '.' << extension; state.save(os.str()); } @@ -44,5 +44,3 @@ void eoCountedStateSaver::lastCall(void) if (saveOnLastCall) doItNow(); } - - diff --git a/eo/src/utils/eoUpdater.h b/eo/src/utils/eoUpdater.h index ab8ae425..072b9a9b 100644 --- a/eo/src/utils/eoUpdater.h +++ b/eo/src/utils/eoUpdater.h @@ -45,8 +45,8 @@ class eoUpdater : public eoF public: virtual void lastCall() {} virtual std::string className(void) const { return "eoUpdater"; } - - template + + template eoUpdater& addTo(eoCheckPoint& cp) { cp.add(*this); return *this; } }; @@ -149,8 +149,8 @@ public : 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) {} + saveOnLastCall(true), + prefix(_prefix), extension(_extension) {} virtual void lastCall(void); void operator()(void); diff --git a/eo/src/utils/make_help.cpp b/eo/src/utils/make_help.cpp index a9aa74f9..a7ab040c 100644 --- a/eo/src/utils/make_help.cpp +++ b/eo/src/utils/make_help.cpp @@ -95,7 +95,7 @@ bool testDirRes(std::string _dirName, bool _erase=true) return true; } // else - if (_erase) // OK to erase + if (_erase) // OK to erase { s = string("/bin/rm ")+ _dirName + "/*"; int res = system(s.c_str()); diff --git a/eo/src/utils/pipecom.cpp b/eo/src/utils/pipecom.cpp index 46ad5489..a175112f 100644 --- a/eo/src/utils/pipecom.cpp +++ b/eo/src/utils/pipecom.cpp @@ -29,14 +29,14 @@ int Check( PCom *com ) { if( ! com ) { - fprintf( stderr, "PipeCom: Null pointer.\n" ); - fflush( stderr ); - return 0; + 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; + fprintf( stderr, "PipeCom: process doesn't exists.\n" ); + fflush( stderr ); + return 0; } return 1; } @@ -59,46 +59,46 @@ PCom * PipeComOpenArgv( char *prog, char *argv[] ) PCom * ret = NULL; if( pipe( toFils ) < 0 ) { - perror( "PipeComOpen: Creating pipes" ); - return ret; + perror( "PipeComOpen: Creating pipes" ); + return ret; } if( pipe( toPere ) < 0 ) { - perror( "PipeComOpen: Creating pipes" ); - return ret; + perror( "PipeComOpen: Creating pipes" ); + return ret; } switch( (sonPid = vfork()) ) { case -1: - perror("PipeComOpen: fork failed" ); - return ret; - break; + 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; + /* --- 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 = (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; + ret->fWrit = (FILE *)fdopen( toFils[1], "w" ); + ret->fRead = (FILE *)fdopen( toPere[0], "r" ); + ret->pid = sonPid; } return ret; } @@ -108,7 +108,7 @@ int PipeComSend( PCom *to, const char *line ) { int nb = 0; if( ! Check(to ) ) - return nb; + return nb; nb = fprintf( to->fWrit, line, 0 ); fflush( to->fWrit ); return nb; @@ -119,7 +119,7 @@ int PipeComSendn( PCom *to, const char *data, int n ) { int nb = 0; if( ! Check(to) ) - return nb; + return nb; nb = fwrite( data, 1, n, to->fWrit ); fflush( to->fWrit ); @@ -130,14 +130,14 @@ int PipeComSendn( PCom *to, const char *data, int n ) int PipeComReceive( PCom *from, char *data, int max ) { if( ! Check(from) ) - return 0; + 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 strlen(data); return 0; } @@ -146,7 +146,7 @@ int PipeComReceive( PCom *from, char *data, int max ) int PipeComClose( PCom *to ) { if( ! Check(to) ) - return 0; + return 0; fclose( to->fRead ); fclose( to->fWrit ); free( to ); @@ -159,8 +159,8 @@ int PipeComWaitFor( PCom *from, char *what ) { char buffer[256]; do { - if( ! PipeComReceive( from, buffer, 256 ) ) - return 0; + if( ! PipeComReceive( from, buffer, 256 ) ) + return 0; } while( strcmp( buffer, what ) ); return 1; } diff --git a/eo/src/utils/selectors.h b/eo/src/utils/selectors.h index d1765b99..37df7997 100644 --- a/eo/src/utils/selectors.h +++ b/eo/src/utils/selectors.h @@ -146,14 +146,14 @@ 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 + 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(*(i++)); + roulette -= static_cast(*(i++)); } return --i; @@ -164,14 +164,14 @@ const EOT& roulette_wheel(const eoPop& _pop, double total, eoRng& _gen = rn { double roulette = _gen.uniform(total); - if (roulette == 0.0) // covers the case where total==0.0 + if (roulette == 0.0) // covers the case where total==0.0 return _pop[_gen.random(_pop.size())]; // uniform choice typename eoPop::const_iterator i = _pop.begin(); while (roulette > 0.0) { - roulette -= static_cast((i++)->fitness()); + roulette -= static_cast((i++)->fitness()); } return *--i; @@ -182,14 +182,14 @@ EOT& roulette_wheel(eoPop& _pop, double total, eoRng& _gen = rng) { float roulette = _gen.uniform(total); - if (roulette == 0.0) // covers the case where total==0.0 + if (roulette == 0.0) // covers the case where total==0.0 return _pop[_gen.random(_pop.size())]; // uniform choice typename eoPop::iterator i = _pop.begin(); while (roulette > 0.0) { - roulette -= static_cast((i++)->fitness()); + roulette -= static_cast((i++)->fitness()); } return *--i; @@ -205,7 +205,7 @@ It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = It competitor = _begin + _gen.random(_end - _begin); if (*best < *competitor) - { + { best = competitor; } } From 70e60a50d2c1adcf0140d97ac9def6fe4307b59e Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Thu, 5 May 2011 17:15:10 +0200 Subject: [PATCH 79/81] * whitespace cleanup --- edo/AUTHORS | 5 +- edo/COPYING | 14 +- edo/application/eda/main.cpp | 4 +- edo/src/edo | 4 +- edo/src/edo.cpp | 5 +- edo/src/edoAlgo.h | 4 +- edo/src/edoBounder.h | 4 +- edo/src/edoBounderBound.h | 4 +- edo/src/edoBounderNo.h | 4 +- edo/src/edoBounderRng.h | 5 +- edo/src/edoBounderUniform.h | 20 +- edo/src/edoContinue.h | 4 +- edo/src/edoDistrib.h | 4 +- edo/src/edoEDA.h | 6 +- edo/src/edoEDASA.h | 6 +- edo/src/edoEstimator.h | 4 +- edo/src/edoEstimatorNormalMono.h | 4 +- edo/src/edoEstimatorNormalMulti.h | 4 +- edo/src/edoEstimatorUniform.h | 4 +- edo/src/edoModifier.h | 5 +- edo/src/edoModifierDispersion.h | 4 +- edo/src/edoModifierMass.h | 5 +- edo/src/edoNormalMono.h | 4 +- edo/src/edoNormalMonoCenter.h | 5 +- edo/src/edoNormalMulti.h | 4 +- edo/src/edoNormalMultiCenter.h | 4 +- edo/src/edoSampler.h | 4 +- edo/src/edoSamplerNormalMono.h | 6 +- edo/src/edoSamplerNormalMulti.h | 4 +- edo/src/edoSamplerUniform.h | 4 +- edo/src/edoUniform.h | 4 +- edo/src/edoUniformCenter.h | 4 +- edo/src/edoVectorBounds.h | 4 +- edo/src/utils/edoCheckPoint.h | 4 +- edo/src/utils/edoFileSnapshot.cpp | 4 +- edo/src/utils/edoFileSnapshot.h | 4 +- edo/src/utils/edoHyperVolume.h | 4 +- edo/src/utils/edoPopStat.h | 4 +- edo/src/utils/edoStat.h | 4 +- edo/src/utils/edoStatNormalMono.h | 4 +- edo/src/utils/edoStatNormalMulti.h | 4 +- edo/src/utils/edoStatUniform.h | 4 +- edo/test/t-bounderno.cpp | 4 +- edo/test/t-continue.cpp | 4 +- edo/test/t-edoEstimatorNormalMulti.cpp | 4 +- edo/test/t-mean-distance.cpp | 4 +- edo/test/t-uniform.cpp | 4 +- edo/test/test_cov_parameters.py | 12 +- eo/CHANGELOG | 226 +++---- eo/COPYING | 4 +- eo/ConfigureChecks.cmake | 26 +- eo/INSTALL | 1 - eo/LICENSE | 6 +- eo/NEWS | 13 +- eo/README | 23 +- eo/app/gprop/CMakeLists.txt | 11 +- eo/app/gprop/gprop.h | 8 +- eo/app/gprop/l2.h | 42 +- eo/app/gprop/mlp.h | 68 +- eo/app/gprop/mse.h | 36 +- eo/app/gprop/qp.h | 88 +-- eo/app/gprop/vecop.h | 11 +- eo/app/gpsymreg/CMakeLists.txt | 5 +- eo/app/gpsymreg/fitness.h | 3 +- eo/app/gpsymreg/main.cpp | 17 +- eo/app/gpsymreg/node.h | 100 +-- eo/app/gpsymreg/parameters.h | 42 +- eo/app/mastermind/CMakeLists.txt | 5 +- eo/app/mastermind/mastermind.cpp | 4 +- eo/config.guess | 170 ++--- eo/config.h.cmake | 2 - eo/contrib/MGE/eoInitVirus.h | 12 +- eo/contrib/boost/config.hpp | 17 +- eo/contrib/boost/config/abi_prefix.hpp | 2 +- eo/contrib/boost/config/abi_suffix.hpp | 4 +- eo/contrib/boost/config/auto_link.hpp | 28 +- eo/contrib/boost/limits.hpp | 13 +- eo/contrib/eoAged.h | 13 +- eo/contrib/eoDrawable.h | 56 +- eo/install_symlink.py.cmake | 16 +- eo/test/ChangeLog | 10 +- eo/test/RoyalRoad.h | 4 +- eo/test/binary_value.h | 2 +- eo/test/boxplot.py | 6 +- eo/test/fitness_traits.cpp | 6 +- eo/test/real_value.h | 7 +- eo/test/run_tests | 2 +- eo/test/t-eo.cpp | 5 +- eo/test/t-eo2dVector.cc | 8 +- eo/test/t-eoCMAES.cpp | 4 - eo/test/t-eoCheckpointing.cpp | 37 +- eo/test/t-eoDualFitness.cpp | 24 +- eo/test/t-eoESAll.cpp | 32 +- eo/test/t-eoESFull.cpp | 24 +- eo/test/t-eoEasyEA.cpp | 17 +- eo/test/t-eoEasyPSO.cpp | 33 +- eo/test/t-eoExtendedVelocity.cpp | 4 +- eo/test/t-eoExternalEO.cpp | 22 +- eo/test/t-eoFitnessAssembled.cpp | 27 +- eo/test/t-eoFitnessAssembledEA.cpp | 38 +- eo/test/t-eoFunctor.cpp | 3 +- eo/test/t-eoGA.cpp | 2 +- eo/test/t-eoGenOp.cpp | 26 +- eo/test/t-eoIQRStat.cpp | 8 +- eo/test/t-eoInitPermutation.cpp | 14 +- eo/test/t-eoOrderXover.cpp | 16 +- eo/test/t-eoPBIL.cpp | 8 +- eo/test/t-eoRNG.cpp | 16 +- eo/test/t-eoReal.cpp | 6 +- eo/test/t-eoReplacement.cpp | 16 +- eo/test/t-eoRingTopology.cpp | 12 +- eo/test/t-eoRoulette.cpp | 16 +- eo/test/t-eoSecondsElapsedContinue.cpp | 3 - eo/test/t-eoSelect.cpp | 12 +- eo/test/t-eoSharing.cpp | 6 +- eo/test/t-eoShiftMutation.cpp | 14 +- eo/test/t-eoStateAndParser.cpp | 24 +- eo/test/t-eoSwapMutation.cpp | 16 +- eo/test/t-eoSymreg.cpp | 100 +-- eo/test/t-eoSyncEasyPSO.cpp | 32 +- eo/test/t-eoTwoOptMutation.cpp | 14 +- eo/test/t-eoUniform.cpp | 2 +- eo/test/t-eoVirus.cpp | 3 +- eo/test/t-eobin.cpp | 4 +- eo/test/t-eofitness.cpp | 19 +- eo/test/t-openmp.py | 84 +-- eo/test/t-selectOne.cpp | 10 +- eo/tutorial/Lesson1/CMakeLists.txt | 12 +- eo/tutorial/Lesson1/FirstBitGA.cpp | 14 +- eo/tutorial/Lesson1/FirstRealGA.cpp | 14 +- eo/tutorial/Lesson1/Makefile.simple | 6 +- eo/tutorial/Lesson1/exercise1.3.cpp | 6 +- eo/tutorial/Lesson2/CMakeLists.txt | 12 +- eo/tutorial/Lesson2/FirstBitEA.cpp | 4 +- eo/tutorial/Lesson2/FirstRealEA.cpp | 6 +- eo/tutorial/Lesson2/Makefile.simple | 8 +- eo/tutorial/Lesson2/binary_value.h | 3 +- eo/tutorial/Lesson2/exercise2.3.cpp | 6 +- eo/tutorial/Lesson2/real_value.h | 7 +- eo/tutorial/Lesson3/CMakeLists.txt | 13 +- eo/tutorial/Lesson3/Makefile.simple | 8 +- eo/tutorial/Lesson3/SecondBitEA.cpp | 8 +- eo/tutorial/Lesson3/SecondRealEA.cpp | 8 +- eo/tutorial/Lesson3/binary_value.h | 3 +- eo/tutorial/Lesson3/exercise3.1.cpp | 10 +- eo/tutorial/Lesson3/real_value.h | 7 +- eo/tutorial/Lesson4/BitEA.cpp | 10 +- eo/tutorial/Lesson4/CMakeLists.txt | 17 +- eo/tutorial/Lesson4/ESEA.cpp | 28 +- eo/tutorial/Lesson4/ESEA.param | 3 +- eo/tutorial/Lesson4/Makefile.simple | 12 +- eo/tutorial/Lesson4/RealEA.cpp | 6 +- eo/tutorial/Lesson4/RealEA.param | 3 +- eo/tutorial/Lesson4/binary_value.h | 2 +- eo/tutorial/Lesson4/real_value.h | 7 +- eo/tutorial/Lesson5/CMakeLists.txt | 10 +- eo/tutorial/Lesson5/Makefile.simple | 10 +- eo/tutorial/Lesson5/OneMaxEA.cpp | 22 +- eo/tutorial/Lesson5/OneMaxLibEA.cpp | 22 +- eo/tutorial/Lesson5/eoOneMax.h | 17 +- eo/tutorial/Lesson5/eoOneMaxEvalFunc.h | 12 +- eo/tutorial/Lesson5/eoOneMaxInit.h | 7 +- eo/tutorial/Lesson5/eoOneMaxMutation.h | 32 +- eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h | 32 +- eo/tutorial/Lesson5/make_OneMax.cpp | 17 +- eo/tutorial/Lesson5/make_genotype_OneMax.h | 20 +- eo/tutorial/Lesson5/make_op_OneMax.h | 44 +- eo/tutorial/Lesson6/BinaryPSO.cpp | 38 +- eo/tutorial/Lesson6/CMakeLists.txt | 11 +- eo/tutorial/Lesson6/Makefile.simple | 10 +- eo/tutorial/Lesson6/RealPSO.cpp | 42 +- eo/tutorial/Makefile.simple | 12 +- eo/tutorial/README | 9 +- eo/tutorial/Templates/CMakeLists.txt.src-tmpl | 13 +- eo/tutorial/Templates/CMakeLists.txt.top-tmpl | 18 +- eo/tutorial/Templates/ChangeLog | 4 +- eo/tutorial/Templates/EO.tpl | 4 +- eo/tutorial/Templates/MyStructLibEA.cpp | 22 +- eo/tutorial/Templates/README | 6 +- eo/tutorial/Templates/README.manual | 36 +- eo/tutorial/Templates/binCrossover.tmpl | 14 +- eo/tutorial/Templates/configure.ac.tmpl | 6 +- eo/tutorial/Templates/continue.tmpl | 9 +- eo/tutorial/Templates/createEOproject.sh | 4 +- eo/tutorial/Templates/eoMyStruct.tmpl | 25 +- eo/tutorial/Templates/evalFunc.tmpl | 12 +- eo/tutorial/Templates/init.tmpl | 7 +- .../lessOffspringExternalSelectorGenOp.tmpl | 18 +- .../lessOffspringSameSelectorGenOp.tmpl | 10 +- eo/tutorial/Templates/make_MyStruct.cpp | 1 - .../Templates/make_genotype_MyStruct.h | 20 +- eo/tutorial/Templates/make_op_MyStruct.h | 44 +- eo/tutorial/Templates/moreOffspringGenOp.tmpl | 18 +- eo/tutorial/Templates/stat.tmpl | 3 +- website/index.html | 602 +++++++++--------- 195 files changed, 1752 insertions(+), 1862 deletions(-) diff --git a/edo/AUTHORS b/edo/AUTHORS index 550b46c0..d66d82bf 100644 --- a/edo/AUTHORS +++ b/edo/AUTHORS @@ -1,6 +1,5 @@ - -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/COPYING b/edo/COPYING index 4362b491..d4537832 100644 --- a/edo/COPYING +++ b/edo/COPYING @@ -1,5 +1,5 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA @@ -10,7 +10,7 @@ as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - Preamble + Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -112,7 +112,7 @@ modification follow. Pay close attention to the difference between a former contains code derived from the library, whereas the latter must be combined with the library in order to run. - GNU LESSER GENERAL PUBLIC LICENSE + GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other @@ -432,7 +432,7 @@ decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - NO WARRANTY + NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. @@ -455,9 +455,9 @@ FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - END OF TERMS AND CONDITIONS + END OF TERMS AND CONDITIONS - How to Apply These Terms to Your New Libraries + How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that diff --git a/edo/application/eda/main.cpp b/edo/application/eda/main.cpp index 8fc663fd..ceb64fb3 100644 --- a/edo/application/eda/main.cpp +++ b/edo/application/eda/main.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edo b/edo/src/edo index 54f20284..1a6a2c68 100644 --- a/edo/src/edo +++ b/edo/src/edo @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edo.cpp b/edo/src/edo.cpp index ff2bd2f9..aab9c37b 100644 --- a/edo/src/edo.cpp +++ b/edo/src/edo.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -25,4 +25,3 @@ Authors: */ #include "edo" - diff --git a/edo/src/edoAlgo.h b/edo/src/edoAlgo.h index 249e42dd..464cb55e 100644 --- a/edo/src/edoAlgo.h +++ b/edo/src/edoAlgo.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoBounder.h b/edo/src/edoBounder.h index 98bfc1a8..3341db5c 100644 --- a/edo/src/edoBounder.h +++ b/edo/src/edoBounder.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoBounderBound.h b/edo/src/edoBounderBound.h index 8d5e52be..106748a3 100644 --- a/edo/src/edoBounderBound.h +++ b/edo/src/edoBounderBound.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoBounderNo.h b/edo/src/edoBounderNo.h index 27d65e6c..c1a98e71 100644 --- a/edo/src/edoBounderNo.h +++ b/edo/src/edoBounderNo.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoBounderRng.h b/edo/src/edoBounderRng.h index e1e3617f..8c7bb3ef 100644 --- a/edo/src/edoBounderRng.h +++ b/edo/src/edoBounderRng.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -60,4 +60,3 @@ private: }; #endif // !_edoBounderRng_h - diff --git a/edo/src/edoBounderUniform.h b/edo/src/edoBounderUniform.h index fef1674d..3af5579f 100644 --- a/edo/src/edoBounderUniform.h +++ b/edo/src/edoBounderUniform.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -39,16 +39,16 @@ public: void operator()( EOT& sol ) { - unsigned int size = sol.size(); - assert(size > 0); + unsigned int size = sol.size(); + assert(size > 0); - for (unsigned int d = 0; d < size; ++d) { + for (unsigned int d = 0; d < size; ++d) { - if ( sol[d] < this->min()[d] || sol[d] > this->max()[d]) { - // use EO's global "rng" - sol[d] = rng.uniform( this->min()[d], this->max()[d] ); - } - } // for d in size + if ( sol[d] < this->min()[d] || sol[d] > this->max()[d]) { + // use EO's global "rng" + sol[d] = rng.uniform( this->min()[d], this->max()[d] ); + } + } // for d in size } }; diff --git a/edo/src/edoContinue.h b/edo/src/edoContinue.h index 2f7dff5a..14b89e61 100644 --- a/edo/src/edoContinue.h +++ b/edo/src/edoContinue.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoDistrib.h b/edo/src/edoDistrib.h index 29ff500d..5ce9ce06 100644 --- a/edo/src/edoDistrib.h +++ b/edo/src/edoDistrib.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoEDA.h b/edo/src/edoEDA.h index dde0bb3a..21f95f52 100644 --- a/edo/src/edoEDA.h +++ b/edo/src/edoEDA.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -108,7 +108,7 @@ public: */ void operator ()(eoPop< EOT > & pop) { - assert(pop.size() > 0); + assert(pop.size() > 0); //double temperature = _initial_temperature; diff --git a/edo/src/edoEDASA.h b/edo/src/edoEDASA.h index b77daa07..99da07cd 100644 --- a/edo/src/edoEDASA.h +++ b/edo/src/edoEDASA.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -108,7 +108,7 @@ public: */ void operator ()(eoPop< EOT > & pop) { - assert(pop.size() > 0); + assert(pop.size() > 0); double temperature = _initial_temperature; diff --git a/edo/src/edoEstimator.h b/edo/src/edoEstimator.h index 6a2be7a3..c68069ee 100644 --- a/edo/src/edoEstimator.h +++ b/edo/src/edoEstimator.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoEstimatorNormalMono.h b/edo/src/edoEstimatorNormalMono.h index 1ef61ab7..97036855 100644 --- a/edo/src/edoEstimatorNormalMono.h +++ b/edo/src/edoEstimatorNormalMono.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoEstimatorNormalMulti.h b/edo/src/edoEstimatorNormalMulti.h index 8b4b7abb..6d5eb0ba 100644 --- a/edo/src/edoEstimatorNormalMulti.h +++ b/edo/src/edoEstimatorNormalMulti.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoEstimatorUniform.h b/edo/src/edoEstimatorUniform.h index 7c5779ff..8b61c7bd 100644 --- a/edo/src/edoEstimatorUniform.h +++ b/edo/src/edoEstimatorUniform.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoModifier.h b/edo/src/edoModifier.h index 5aac0bb5..91f7fbe2 100644 --- a/edo/src/edoModifier.h +++ b/edo/src/edoModifier.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -38,4 +38,3 @@ public: }; #endif // !_edoModifier_h - diff --git a/edo/src/edoModifierDispersion.h b/edo/src/edoModifierDispersion.h index 81a6b541..0d890cbe 100644 --- a/edo/src/edoModifierDispersion.h +++ b/edo/src/edoModifierDispersion.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoModifierMass.h b/edo/src/edoModifierMass.h index fee69d2d..414918c7 100644 --- a/edo/src/edoModifierMass.h +++ b/edo/src/edoModifierMass.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -42,4 +42,3 @@ public: }; #endif // !_edoModifierMass_h - diff --git a/edo/src/edoNormalMono.h b/edo/src/edoNormalMono.h index 0850386c..34c71450 100644 --- a/edo/src/edoNormalMono.h +++ b/edo/src/edoNormalMono.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoNormalMonoCenter.h b/edo/src/edoNormalMonoCenter.h index 8bd990a7..ac6e75f3 100644 --- a/edo/src/edoNormalMonoCenter.h +++ b/edo/src/edoNormalMonoCenter.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -44,4 +44,3 @@ public: }; #endif // !_edoNormalMonoCenter_h - diff --git a/edo/src/edoNormalMulti.h b/edo/src/edoNormalMulti.h index 54f695b1..9a602e73 100644 --- a/edo/src/edoNormalMulti.h +++ b/edo/src/edoNormalMulti.h @@ -1,8 +1,8 @@ // (c) Thales group, 2010 /* Authors: - Johann Dreo - Caner Candan + Johann Dreo + Caner Candan */ #ifndef _edoNormalMulti_h diff --git a/edo/src/edoNormalMultiCenter.h b/edo/src/edoNormalMultiCenter.h index e59c5634..c929ac56 100644 --- a/edo/src/edoNormalMultiCenter.h +++ b/edo/src/edoNormalMultiCenter.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoSampler.h b/edo/src/edoSampler.h index 4a0d9244..212e861c 100644 --- a/edo/src/edoSampler.h +++ b/edo/src/edoSampler.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoSamplerNormalMono.h b/edo/src/edoSamplerNormalMono.h index d628ba2f..b52ad283 100644 --- a/edo/src/edoSamplerNormalMono.h +++ b/edo/src/edoSamplerNormalMono.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or @@ -74,7 +74,7 @@ public: { AtomType mean = distrib.mean()[i]; AtomType variance = distrib.variance()[i]; - AtomType random = rng.normal(mean, variance); + AtomType random = rng.normal(mean, variance); assert(variance >= 0); diff --git a/edo/src/edoSamplerNormalMulti.h b/edo/src/edoSamplerNormalMulti.h index 889c2e54..2aa59950 100644 --- a/edo/src/edoSamplerNormalMulti.h +++ b/edo/src/edoSamplerNormalMulti.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoSamplerUniform.h b/edo/src/edoSamplerUniform.h index a7b4c316..dbb8f412 100644 --- a/edo/src/edoSamplerUniform.h +++ b/edo/src/edoSamplerUniform.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoUniform.h b/edo/src/edoUniform.h index 93d3b537..01cf3cb3 100644 --- a/edo/src/edoUniform.h +++ b/edo/src/edoUniform.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoUniformCenter.h b/edo/src/edoUniformCenter.h index 8284439b..22ce9516 100644 --- a/edo/src/edoUniformCenter.h +++ b/edo/src/edoUniformCenter.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/edoVectorBounds.h b/edo/src/edoVectorBounds.h index 3c00995f..c72a10c2 100644 --- a/edo/src/edoVectorBounds.h +++ b/edo/src/edoVectorBounds.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoCheckPoint.h b/edo/src/utils/edoCheckPoint.h index 90ba72e6..5ba25ac1 100644 --- a/edo/src/utils/edoCheckPoint.h +++ b/edo/src/utils/edoCheckPoint.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoFileSnapshot.cpp b/edo/src/utils/edoFileSnapshot.cpp index 40f1db68..1860ac0f 100644 --- a/edo/src/utils/edoFileSnapshot.cpp +++ b/edo/src/utils/edoFileSnapshot.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoFileSnapshot.h b/edo/src/utils/edoFileSnapshot.h index 43e6f088..17d04263 100644 --- a/edo/src/utils/edoFileSnapshot.h +++ b/edo/src/utils/edoFileSnapshot.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoHyperVolume.h b/edo/src/utils/edoHyperVolume.h index a1bf4e59..85bcf033 100644 --- a/edo/src/utils/edoHyperVolume.h +++ b/edo/src/utils/edoHyperVolume.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoPopStat.h b/edo/src/utils/edoPopStat.h index c8df5f96..4d5c9f10 100644 --- a/edo/src/utils/edoPopStat.h +++ b/edo/src/utils/edoPopStat.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoStat.h b/edo/src/utils/edoStat.h index 24dce9c4..de5b4d2d 100644 --- a/edo/src/utils/edoStat.h +++ b/edo/src/utils/edoStat.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoStatNormalMono.h b/edo/src/utils/edoStatNormalMono.h index 8cb28553..b16b3ae5 100644 --- a/edo/src/utils/edoStatNormalMono.h +++ b/edo/src/utils/edoStatNormalMono.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoStatNormalMulti.h b/edo/src/utils/edoStatNormalMulti.h index 74adb0ba..68af0735 100644 --- a/edo/src/utils/edoStatNormalMulti.h +++ b/edo/src/utils/edoStatNormalMulti.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/src/utils/edoStatUniform.h b/edo/src/utils/edoStatUniform.h index ab75e66b..8ccb93be 100644 --- a/edo/src/utils/edoStatUniform.h +++ b/edo/src/utils/edoStatUniform.h @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/test/t-bounderno.cpp b/edo/test/t-bounderno.cpp index 3f7a189b..ac294ce7 100644 --- a/edo/test/t-bounderno.cpp +++ b/edo/test/t-bounderno.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/test/t-continue.cpp b/edo/test/t-continue.cpp index 7206a0c3..2f2bd324 100644 --- a/edo/test/t-continue.cpp +++ b/edo/test/t-continue.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/test/t-edoEstimatorNormalMulti.cpp b/edo/test/t-edoEstimatorNormalMulti.cpp index 23324eef..431f6f98 100644 --- a/edo/test/t-edoEstimatorNormalMulti.cpp +++ b/edo/test/t-edoEstimatorNormalMulti.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/test/t-mean-distance.cpp b/edo/test/t-mean-distance.cpp index 6f3b84f6..a69bc8f1 100644 --- a/edo/test/t-mean-distance.cpp +++ b/edo/test/t-mean-distance.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/test/t-uniform.cpp b/edo/test/t-uniform.cpp index ec01ec7a..228ce5e2 100644 --- a/edo/test/t-uniform.cpp +++ b/edo/test/t-uniform.cpp @@ -1,6 +1,6 @@ /* -The Evolving Distribution Objects framework (EDO) is a template-based, -ANSI-C++ evolutionary computation library which helps you to write your +The Evolving Distribution Objects framework (EDO) is a template-based, +ANSI-C++ evolutionary computation library which helps you to write your own estimation of distribution algorithms. This library is free software; you can redistribute it and/or diff --git a/edo/test/test_cov_parameters.py b/edo/test/test_cov_parameters.py index 7a90f167..30688ca4 100755 --- a/edo/test/test_cov_parameters.py +++ b/edo/test/test_cov_parameters.py @@ -10,9 +10,9 @@ from numpy import arange if __name__ == '__main__': for p1 in list(arange(0.1, 1.1, 0.1)): - for p2 in list(arange(-1., 0., 0.1)) + list(arange(0., 1.1, 0.1)): - for p3 in list(arange(0.1, 1.1, 0.1)): - gen = '%d_%.1f_%.1f_%.1f_%.1f' % (PSIZE, MEAN, p1, p2, p3) - cmd = CMD % ( PSIZE, MEAN, p1, p2, p3, gen, gen ) - print cmd - system( cmd ) + for p2 in list(arange(-1., 0., 0.1)) + list(arange(0., 1.1, 0.1)): + for p3 in list(arange(0.1, 1.1, 0.1)): + gen = '%d_%.1f_%.1f_%.1f_%.1f' % (PSIZE, MEAN, p1, p2, p3) + cmd = CMD % ( PSIZE, MEAN, p1, p2, p3, gen, gen ) + print cmd + system( cmd ) diff --git a/eo/CHANGELOG b/eo/CHANGELOG index 09c7a2e6..56e4df4b 100644 --- a/eo/CHANGELOG +++ b/eo/CHANGELOG @@ -1274,11 +1274,11 @@ Date: Thu Feb 22 08:27:32 2007 +0000 * mutation.tmpl, quadCrossover.tmpl, stat.tmpl: Initialize formerly uninitialized variables. - + * README.tmpl: Hint to regular Templates/README for details. - + * README: Add documentation for adding new source-files. - + * Makefile.am.src-tmpl (noinst_HEADERS): Add (MyStruct_SOURCES): Move header files from here to the new noinst_HEADERS variable. @@ -1315,7 +1315,7 @@ Date: Sun Jan 14 18:56:31 2007 +0000 for automake finding the scripts of eo itself if we run it in a embedded subdirectory. (COPYING, INSTALL): create. - + * README: State more explicitly what a "complete installation" means. Give build-instructions for moved directories. @@ -1359,9 +1359,9 @@ Author: kuepper Date: Mon Dec 18 11:17:55 2006 +0000 * TODO.html, README.html: Remove these old files. - + * AUTHORS, COPYING, ForRelease, NEWS, ToDo: Update for release. - + * eo.cfg (PROJECT_NUMBER): Bump version to 1.0 Author: kuepper @@ -1373,7 +1373,7 @@ Author: kuepper Date: Sun Dec 17 22:59:53 2006 +0000 * README: Better links to Templates/ - + * configure.in: Bump version to 1.0-beta2. Author: kuepper @@ -1402,11 +1402,11 @@ Date: Sat Dec 16 21:55:03 2006 +0000 * EO.tpl, MyStructEA.cpp, MyStructSEA.cpp, make_MyStruct.cpp: Use correct names for includes. - + * README.manual: This is a copy of the old README. - + * README: Describe the new way and setup of creating a new EO project. - + * createEOproject.sh, Makefile.am.src-tmpl, Makefile.am.top-tmpl: * configure.ac.tmpl: New files to create a standalone EO project from templates. @@ -1435,7 +1435,7 @@ Author: kuepper Date: Mon Dec 4 22:27:41 2006 +0000 * Makefile.am: Add t-eoRNG - + * t-eoRNG.cpp: Start test for random number generator. Author: kuepper @@ -1472,11 +1472,11 @@ Author: kuepper Date: Sun Dec 3 10:41:54 2006 +0000 * mainpage.html: update, add link to Niko Hansen's comparison - + * README: Add more specific note about tutorial. - + * configure.in: Bump version to 1.0-beta1 - + * tutorial/Makefile.am: Add all necessary files, including html and Templates to distribution. @@ -1517,13 +1517,13 @@ Author: kuepper Date: Sat Dec 2 10:18:57 2006 +0000 * eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned. - + * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. - + * t-eoGenOp.cpp (init): Do not add std::ends to end of string, as this results in escape-codes (^@) to be printed at runtime and is not necessary anyway. - + * test/t-eoSymreg.cpp (SymregNode::operator()): Initialize r1 and r2 to avoid compiler warnings. @@ -1531,7 +1531,7 @@ Author: kuepper Date: Sat Dec 2 09:39:13 2006 +0000 * eoRNG.h: Cleanup docs and document /all/ members. - + * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. Author: kuepper @@ -1548,9 +1548,9 @@ Author: kuepper Date: Fri Dec 1 20:08:51 2006 +0000 * Makefile.am: Update for release-distribution. - + * Makefile.am: Add missing CMA header for distribution. - + * Makefile.am: Add missing header for distribution. Author: kuepper @@ -1603,7 +1603,7 @@ Author: kuepper Date: Thu Nov 16 12:52:46 2006 +0000 * configure.in (AC_DEBUG): add test - + * acinclude.m4 (AC_DEBUG): Define debug-feature and set DEBUG, NODEBUG, or NDEBUG according to its value. @@ -1613,10 +1613,10 @@ Date: Thu Nov 16 12:35:46 2006 +0000 * make_genotype_real.h (eoEsChromInit): Rewrite vecSigmaInit-handling: If sigmaInit is relative (%), do not read vecSigmaInit. Otherwise always use vecSigmaInit with default all values of sigmaInit. - + * eoParser.h (eoParser::getORcreateParam): Make this a real if-then-else clause around ptParam (found or not). - + * eoParam.h (eoValueParam::setValue): Document. (eoValueParam >::setValue): Allow delimiters ',' and ';'. A plain ' ' does not work, as it is not correctly read by @@ -1973,9 +1973,9 @@ Date: Sun Oct 2 21:42:08 2005 +0000 - add a user-option for gnuplot-support - separate gnuplot-code into declaration and implementation, so we can define at EO-build-time whether to use it or not. - + Adopt code and Makefiles to above changes. - + Some minor fixes. Author: kuepper @@ -2311,7 +2311,7 @@ Date: Thu Dec 23 15:29:07 2004 +0000 Adjust code to perform to C++ standard according to gcc-3.4 interpretation... (Have not compiled/checked/changed paradisEO.) - + That is, the current code compiles with gcc-3.4 and the checks (besides t-MGE1bit) all pass. @@ -2362,7 +2362,7 @@ Date: Fri Nov 5 08:57:34 2004 +0000 easily read as a parameter) - eoIntBound and all other integer-equivalent of the classes in eoRealBound.h Note that there is no equivalent to eoRealVectorBounds for vector of integers - + In file eo, I have added the 2 includes of eoRealBounds.h and eoIntBounds.h The first one was already there by chance, through eoUniformInit.h @@ -2569,13 +2569,13 @@ Author: kuepper Date: Fri Sep 17 16:53:31 2004 +0000 Updated build-prcess to be completely under automake control. - + For the tutorial the old Makefiles are saved as Makefile.simple in all the respective directories. - + Use generated config.h instead of command-line passing of preprocessor flags. - + Updated support files from current automake. Author: kuepper @@ -3300,7 +3300,7 @@ Date: Sun Jan 5 16:31:50 2003 +0000 Added pyeo. Some changes needed to be made for include files and the like in some files (and some bugs were fixed as well [Marc: eoOneToOneBreeder was a mess]) - + eoFunctor.h now contains static functor_category members, this shouldn't hurt anyone. Author: maartenkeijzer @@ -3398,7 +3398,7 @@ Date: Wed Sep 18 12:40:46 2002 +0000 A new readFrom & printOn function for EO.h Now it CAN handle VALID/INVALID fitnesses. - + The problems are over at last Author: cahon @@ -3592,7 +3592,7 @@ Date: Mon Jun 17 04:13:45 2002 +0000 Adding the truncation selectors. 2 versions: eoTruncatedSelectOne is an eoSelectOne, and - eoTruncatedSelectMany works like an eoSelectMany (but is NOT) + eoTruncatedSelectMany works like an eoSelectMany (but is NOT) Author: jeggermo Date: Mon Jun 10 14:10:35 2002 +0000 @@ -3609,7 +3609,7 @@ Date: Mon May 13 11:31:32 2002 +0000 EO::printOn has been changed so that the printOn function will always print a valid fitness value even if the fitness is invalid - + Jeroen Author: jeggermo @@ -3827,7 +3827,7 @@ Date: Mon Apr 15 12:56:35 2002 +0000 eoParseTree printOn and readFrom functions changed for compatibility with paradisEO - + The fitness is now printed in the same way as in eoBit Author: evomarc @@ -4138,9 +4138,9 @@ Date: Mon Feb 4 14:28:00 2002 +0000 the gpsymreg code has been slightly altered to allow compilation using the Intel C++ Compiler for Linux. - + Other compilers should not be affected. - + A slightly different makefile is needed Author: jeggermo @@ -4317,7 +4317,7 @@ Date: Tue Dec 4 21:15:16 2001 +0000 some template classes and functions which did not need to be templates have been changed to normal classes and functions with hard coded typed - + This might help with M$VC++ 6.0 compatibility Author: jeggermo @@ -4537,8 +4537,8 @@ Date: Sat Nov 10 09:02:17 2001 +0000 Small modifications here and there to be MSVC++ compatible Mainly, time.h -> ctime - definition of loop index out of loops when multiply used - no typename in declaration using template typename + definition of loop index out of loops when multiply used + no typename in declaration using template typename Author: evomarc Date: Sat Nov 10 06:59:02 2001 +0000 @@ -4628,15 +4628,15 @@ Date: Sat Nov 3 22:10:11 2001 +0000 the name of the eoGpDepthInitializer class (initializer for parse_tree's has been changed to - + eoParseTreeDepthInit but backward compatibility is maintained by using a #define statement: - + #define eoGpDepthInitializer eoParseTreeDepthInit - + The initializer for strongly typed GP has been changed to eoStParseTreeDepthInit - + the gpsymreg application has been changed to use the new name Author: jeggermo @@ -4839,7 +4839,7 @@ Author: jeggermo Date: Tue Jul 17 08:58:52 2001 +0000 small documentation change for eoParseTree.h. - + added a depth initializer for strongly typed genetic programming added subtree xover for strongly typed genetic programming added branch mutation for strongly typed genetic programming @@ -4862,7 +4862,7 @@ Date: Wed Jul 4 04:44:30 2001 +0000 Adding eoPopEvalFunc, that handles evaluation globally: it receives two populations, parents and offspring, and does whatever necessary. The subclass eoPopLoopEval does the simple loop on the offspring. - + eoEasyEA was subsequently modified to handle an eoPopEval passed in Ctor, but also to encapsulate an eoEvalFunc into an eoPopLoopEval tranparently. @@ -4874,7 +4874,7 @@ Date: Tue Jul 3 12:56:44 2001 +0000 Modified eoEaseyEA accordingly - you can either pass an eoEvalFunc, as before (it is then encapsulated into an eoPopLoopEval that does the good old loop on the offspring - or directly pass a full eoPopEvalFunc - + Small modification also in make_op_es -> keyword "none" is now recognized for one of the crossover of either object variables or stdev's @@ -4883,9 +4883,9 @@ Date: Mon Jul 2 13:31:04 2001 +0000 Changed the directory structure for gp now: eoParseTree <-- the eoParseTree class - eoParseTreeDepthInit <-- the eoParseTree depth initializer (eoGpDepthInitializer) - eoParseTreeOp <-- the operators (xover and mutation) - + eoParseTreeDepthInit <-- the eoParseTree depth initializer (eoGpDepthInitializer) + eoParseTreeOp <-- the operators (xover and mutation) + base documentation written for: * eoParseTree * eoGpDepthInitializer @@ -4895,9 +4895,9 @@ Date: Mon Jul 2 13:31:04 2001 +0000 * eoExpansionMutation * eoCollapseSubtreeMutation * eoHoistMutation - + I also created a group ParseTree which contains all classes related to eoParseTree - + eoGpMutate.h has been removed (merged with eoParseTree operators into eoParseTreeOp Author: jeggermo @@ -4978,16 +4978,16 @@ Author: jeggermo Date: Thu Jun 28 14:03:59 2001 +0000 new Mutation operators for eoParseTree in src/gp/eoGpMutate.h - + a symbolic regression example program added to the app-dir - + configure.in and Makefile(s).am changed Author: jeggermo Date: Thu Jun 28 13:55:14 2001 +0000 Additional mutation operators for eoParseTree - + * Point Mutation * Expansion Mutation * Collapse Subtree Mutation @@ -5195,7 +5195,7 @@ Date: Wed May 2 10:42:32 2001 +0000 src/es/eoEsGlobalXover.h and src/es/eoEsLocalXover.h for crossover src/es/make_XXX_es.h for user-input test/t-eoEsAll.cpp to test - + However, an old bug appeared: className was not const in eoGenOp (and derived classes) so I had to change that throughtout the hierarchy @@ -5212,7 +5212,7 @@ Date: Mon Apr 30 13:24:42 2001 +0000 Changed the interface of make_genotype - now templatized by the EOT and not the fitness - this is mandatory for ES genoptypes as it allows to choose the type of gentype at run-time (from existing types, of course!) - + Also moved make_help.cpp into utils dir (otherwise you'd had to maintain a copy into each representation dir!). @@ -5224,7 +5224,7 @@ Date: Mon Apr 30 13:01:07 2001 +0000 Changed the interface of make_genotype - now templatized by the EOT and not the fitness - this is mandatory for ES genoptypes as it allows to choose the type of gentype at run-time (from existing types, of course!) - + Also moved make_help.cpp into utils dir (otherwise you'd had to maintain a copy into each representation dir!). @@ -5427,7 +5427,7 @@ Date: Wed Apr 4 03:47:33 2001 +0000 Added the signal handling - see eoCtrlCContinue.h I've disabled it in case of MSC as I don't know if this works there ... - + Also added a couple of "virtual" in the ga dir Author: evomarc @@ -5455,7 +5455,7 @@ Date: Wed Mar 28 09:00:54 2001 +0000 FDCStat and FileSnapshot: better error messageing Scalar fitness: is now a vector of doubles exercise3.1 added gnuplot again - + Don't know about eoCombinedContinue Author: evomarc @@ -5646,7 +5646,7 @@ Author: maartenkeijzer Date: Mon Mar 12 16:00:58 2001 +0000 EO: added overloaded printing of fitness (for vectors and pairs) - + Various bugs and ommissions in eoPerf2Worth and eoSelectFromWorth Author: maartenkeijzer @@ -5658,12 +5658,12 @@ Author: maartenkeijzer Date: Sat Mar 10 14:02:23 2001 +0000 Changed the populator to be a) more efficient and b) more useable - + It is no longer derived from eoPop, it now gets a destination population. This saves a lot of copying. The semantics has changed a little as well. It is now an _infinite_ iterator. operator++ will *not* dispense new individuals, but will merely stay at the end. To get a new indy, use operator*() as before. - + eoEasyEA now checks the checkpoint *after* making a generation and clears the offspring eoGeneralBreeder is changed to reflect the changes in eoPopulator eoSequentialSelect now uses setup() rather than init() @@ -5717,7 +5717,7 @@ Date: Mon Feb 19 12:23:13 2001 +0000 To be able to use the primitive std::generate function, added a set of wrappers in eoSTLFunctor.h that have the copy semantics most STL functions expect (namely pass-by-value rather then pass-by-reference). - + Updated test/Makefile.am to also test t-eoRandom Author: evomarc @@ -5736,14 +5736,14 @@ Author: maartenkeijzer Date: Sat Feb 17 10:51:31 2001 +0000 eoVector is back (eoFixedLength and eoVariableLength are gone) - + Also: introducing eoRndGenerators.h for eoRndGenerator derived classes: - + eoNormalGenerator eoUniformGenerator eoBooleanGenerator eoNegExpGenerator - + Note the suffix that are added to aid in determining what these classes do Author: evomarc @@ -5829,13 +5829,13 @@ Date: Wed Feb 14 14:09:16 2001 +0000 Author: maartenkeijzer Date: Wed Feb 14 10:35:26 2001 +0000 - + Changed the signature of eoMon, eoBin and eoQuadOp to return a bool, without invalidating fitness. Added a set of invalidators to take over that job (see for instance eoSGA and eoSGATransform how this can transparantly used) - + Derived eoState from eoFunctorStore (for convenience, from a design perspective this may sound wrong) - + Added a wrap_op function that does the wrapping for you (see eoOpContainer how this made this functor exceedingly less hairy). Checked all the tests removed the eoGeneric*Op family (not needed anymore) and of course changed all the operators to reflect the change (and found a few that didn't @@ -5865,24 +5865,24 @@ Author: maartenkeijzer Date: Tue Feb 13 12:38:19 2001 +0000 fixed a bug: the parser now correctly parses parameters of the form - + -Pvalue - + This will now produce 'value'. The buggy parser would parse 'alue' here. I am truly and deeply ashamed to have created such an off-by-one error. - + Marc assumed this was wanted behaviour (so that it should read: -P=value) I must admit that this is a logical conclusion, though it was merely a side-effect of the error. To not force Marc to rewrite the tutorial and his way of working with EO, I decided to make a feature out of the bug, so that now the parser will parse: - + -Pvalue -P=value - + and of course the true and blue: - + -Parameter=value - + I will now go and check if I sent out some crappy papers caused by this bug (as I've been using eo!) Author: maartenkeijzer @@ -5894,14 +5894,14 @@ Author: maartenkeijzer Date: Mon Feb 12 13:58:51 2001 +0000 Ok, updated the Makefile.am again to use the - + make check - + Command I picked up in the automake documentation (RTFM, you know) - + Tagged a lot of header functions in the GnuPlot files with 'inline', so they can be used from more than one sourcefile. - + Ok, now the interesting news. Started a new library libga (not to be confused with Matthew's GaLib). Here I suggest we put a fairly complete and configurable genetic algorithm. Just to see how far we can stretch ourselves and also to have @@ -5920,7 +5920,7 @@ Author: maartenkeijzer Date: Sun Feb 11 16:25:03 2001 +0000 Removed small bug in reading outside a buffer in eoParser::readFrom - + This caused the parser to crash when a simple flag of the form program -f was given. @@ -6014,8 +6014,8 @@ Date: Fri Feb 9 05:09:26 2001 +0000 I also changed - the eoQuadratic into eoQuad (as dicussed with Maarten) - the eoBin into eoBit, with more appropriate names for the "binary" - operators (that can be unary!) as no one protested when I posted on - eodev list + operators (that can be unary!) as no one protested when I posted on + eodev list Author: evomarc Date: Wed Feb 7 05:15:18 2001 +0000 @@ -6039,7 +6039,7 @@ Date: Wed Feb 7 05:04:24 2001 +0000 Added selection methods eoBestSelect always return the best individual eoSequentialSelect a selectOne version of eoDetSelect (uses an index to - return next offspring from sorted pop) + return next offspring from sorted pop) Author: evomarc Date: Thu Feb 1 05:27:36 2001 +0000 @@ -6061,7 +6061,7 @@ Date: Wed Jan 31 18:38:39 2001 +0000 every generation) which is different from the continuous monitoring (same file/plot is angemented every generation). This lead to a number of modifications in many files in utils dir - + But now we can watch on-line - fitness spreadout - FDC plots @@ -6078,7 +6078,7 @@ Date: Mon Jan 29 10:25:44 2001 +0000 Added the truncate and the hasNoBoundAtAll methods in eoRealBounds. The former simply set values to the boundary values in case they are out The latter allows to short-cut all bound-checks when no need - + SOme day I will put this in utils, and have a eoRealBounds.cpp in the pre-compiled library @@ -6129,12 +6129,12 @@ Date: Sat Jan 27 07:43:58 2001 +0000 eo everything that is general to any representation es.h everything about real representation (in es dir) ga.h everything related to bitstring representation (in ga dir) - + To be continued by gp.h, and ... - + This has lead to some slight modifications in test file eobin and all tutorial examples files... - + I've also added in utils eoDistance, generic functor to compute distances, including also the generic Euclidian distance @@ -6145,9 +6145,9 @@ Date: Sat Jan 27 07:41:46 2001 +0000 eo everything that is general to any representation es.h everything about real representation (in es dir) ga.h everything related to bitstring representation (in ga dir) - + To be continued by gp.h, and ... - + This has lead to some slight modifications in test file eobin and all tutorial examples files... @@ -6405,7 +6405,7 @@ Date: Tue Jan 2 07:03:57 2001 +0000 permanent parameters (eoParser only holds references), and egcs did not allow to create them by reference, i.e. in the line eoValueParam & blablaParam(...); - + So now everything is done in the main_function, and 3 lines are needed to create and read every paramter (sigh ...) @@ -6483,16 +6483,16 @@ Date: Tue Dec 19 18:41:19 2000 +0000 THe big eoReplacement update: The interface for eoReplacement is now eoPop&, eoPop& (i.e. no const) and the result must be in the first argument in the end. - + Hence it is possible to do SSGA and all intermediate replacmeent procedures - + The classes derived from eoMergeReduce.h are now in a separate file The SSGA-like replcaement procedures are in eoReduceMerge.h A more general replacement can be found in eoSurviveAndDie.h (it could be made a littel more general - still open for upgrades). - + Also some accessors have been added to the eoPop (best and worse individuals) - + And include file eo has been updated Author: evomarc @@ -6630,16 +6630,16 @@ Author: evomarc Date: Mon Dec 4 06:58:43 2000 +0000 Added the lastCall construct: if the stopping condition becomes true in eoCheckPoint, - a method called lastCall is called for everything contained in that checkpoint - (stats, updaters and monitors). This can be extremely useful - - for stateSavers (see below) - - for monitoring things like rates of success of operators, where what you - are interested in is the final result only. + a method called lastCall is called for everything contained in that checkpoint + (stats, updaters and monitors). This can be extremely useful + - for stateSavers (see below) + - for monitoring things like rates of success of operators, where what you + are interested in is the final result only. Added of course a virtual method lastCall that does nothing by default in classes - eoBaseStat, eoBaseSortedStat, eoUpdater and eoMonitor + eoBaseStat, eoBaseSortedStat, eoUpdater and eoMonitor Added a boolean to control the save of the state in method eoCountedStateSaver::lastCall - so you can ask that the state is saved at final population, whatever happens. - I also added the corresponding constructor to take this into account. + so you can ask that the state is saved at final population, whatever happens. + I also added the corresponding constructor to take this into account. Author: evomarc Date: Mon Dec 4 05:55:59 2000 +0000 @@ -6822,8 +6822,8 @@ Author: evomarc Date: Tue Nov 28 06:46:37 2000 +0000 Modified the contructor: the default value for the delimiter is now " " - and I added a boolean argument to indicate whether or not we want to - overwrite an existing file with same name (default is overwrite). + and I added a boolean argument to indicate whether or not we want to + overwrite an existing file with same name (default is overwrite). Added the getFileName accessor. Author: evomarc @@ -7085,7 +7085,7 @@ Author: maartenkeijzer Date: Fri Oct 6 10:41:38 2000 +0000 Added an eoSortedStatBase for more efficient statistic calculations - + updated a few makefiles to include the html and latex docs with the distribution. @@ -7844,12 +7844,12 @@ Author: mac Date: Mon Mar 6 16:05:47 2000 +0000 Fixed bug in eoGOpSelector (missing break!) - + eoOp.h: binOp's second arg is const once more - + all dsp and dsw files were touched by msvc, but did add some stuff (which will be added to eo later) - + Hope this all works Author: mac @@ -7879,7 +7879,7 @@ Author: marc Date: Tue Feb 29 05:14:40 2000 +0000 wherease the command "cvs ci" is OK. - + Here we go: - added the virtual destructors of all classes, to suppress g++ annoying warnings when using -Wall option @@ -7930,7 +7930,7 @@ Date: Sat Feb 19 16:30:42 2000 +0000 Moved the static eoRNG rng to an extern eoRNG This external object is now defined in eoPersistent.cpp - + This should change... Author: mac diff --git a/eo/COPYING b/eo/COPYING index 2bb5b6e5..b8df7fd4 100644 --- a/eo/COPYING +++ b/eo/COPYING @@ -146,7 +146,7 @@ such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - + 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an @@ -457,7 +457,7 @@ DAMAGES. END OF TERMS AND CONDITIONS - How to Apply These Terms to Your New Libraries + How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that diff --git a/eo/ConfigureChecks.cmake b/eo/ConfigureChecks.cmake index a8ef34aa..ee687fdf 100644 --- a/eo/ConfigureChecks.cmake +++ b/eo/ConfigureChecks.cmake @@ -1,4 +1,3 @@ - # NOTE: only add something here if it is really needed by EO include(CheckIncludeFile) @@ -7,17 +6,17 @@ include(CheckSymbolExists) include(CheckFunctionExists) include(CheckLibraryExists) -check_library_exists(m cos "cos in libm" HAVE_LIBM) +check_library_exists(m cos "cos in libm" HAVE_LIBM) -check_include_files(cmath.h "cmath.h" HAVE_CMATH_H) -check_include_files(stdio.h "stdio.h" HAVE_STDIO_H) -check_include_files(stdlib.h "stdlib.h" HAVE_STDLIB_H) -check_include_files(string.h "string.h" HAVE_STRING_H) -check_include_files(strings.h "strings.h" HAVE_STRINGS_H) -check_include_files(malloc.h "malloc.h" HAVE_MALLOC_H) -check_include_files(limits.h "limits.h" HAVE_LIMITS_H) -check_include_files(unistd.h "unistd.h" HAVE_UNISTD_H) -check_include_files(stdint.h "stdint.h" HAVE_STDINT_H) +check_include_files(cmath.h "cmath.h" HAVE_CMATH_H) +check_include_files(stdio.h "stdio.h" HAVE_STDIO_H) +check_include_files(stdlib.h "stdlib.h" HAVE_STDLIB_H) +check_include_files(string.h "string.h" HAVE_STRING_H) +check_include_files(strings.h "strings.h" HAVE_STRINGS_H) +check_include_files(malloc.h "malloc.h" HAVE_MALLOC_H) +check_include_files(limits.h "limits.h" HAVE_LIMITS_H) +check_include_files(unistd.h "unistd.h" HAVE_UNISTD_H) +check_include_files(stdint.h "stdint.h" HAVE_STDINT_H) # Use check_symbol_exists to check for symbols in a reliable @@ -27,7 +26,4 @@ check_include_files(stdint.h "stdint.h" HAVE_STDINT_H) # specific order. Refer to the man page for each symbol for which a # check is to be added to get the proper set of headers. Example : -#check_symbol_exists(asymbol "symbole.h" HAVE_SYMBOLE) - - - +#check_symbol_exists(asymbol "symbole.h" HAVE_SYMBOLE) diff --git a/eo/INSTALL b/eo/INSTALL index 6336b026..89a45625 100644 --- a/eo/INSTALL +++ b/eo/INSTALL @@ -233,4 +233,3 @@ operates. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. - diff --git a/eo/LICENSE b/eo/LICENSE index 223ede7d..b8df7fd4 100644 --- a/eo/LICENSE +++ b/eo/LICENSE @@ -146,7 +146,7 @@ such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - + 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an @@ -457,7 +457,7 @@ DAMAGES. END OF TERMS AND CONDITIONS - How to Apply These Terms to Your New Libraries + How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that @@ -500,5 +500,3 @@ necessary. Here is a sample; alter the names: Ty Coon, President of Vice That's all there is to it! - - diff --git a/eo/NEWS b/eo/NEWS index 0f067e00..92beb69a 100644 --- a/eo/NEWS +++ b/eo/NEWS @@ -7,11 +7,11 @@ - GCC 4.3 compatibility - new versatile log system with several nested verbose levels - classes using intern verbose parameters marked as deprecated, please update your code accordingly if you use one of the following files: - eo/src/eoCombinedInit.h - eo/src/eoGenContinue.h - eo/src/eoProportionalCombinedOp.h - eo/src/utils/eoData.h - eo/src/utils/eoStdoutMonitor.h + eo/src/eoCombinedInit.h + eo/src/eoGenContinue.h + eo/src/eoProportionalCombinedOp.h + eo/src/utils/eoData.h + eo/src/utils/eoStdoutMonitor.h - an evaluator that throw an exception if a maximum eval numbers has been reached, independently of the number of generations - new monitor that can write on any ostream - new continuator that can catch POSIX system user signals @@ -33,10 +33,9 @@ - Add Microsoft Visual C++ project support files (for Visual Studio 2003 and 2005) - Upgrade Teamplates/ script to create a complete standalone EO project (using autotools) - Remove support for pre-standard C++ compiler (i.e. gcc-2.x), which allows to - clean up the code considerably. + clean up the code considerably. Assume availability of sstream and limits. * release 0.9.3z.1 (1. Oct. 2005) - Support gcc-3.4 and gcc.4.x. - Provide full automake/autoconf/configure support. - diff --git a/eo/README b/eo/README index 0ce22936..98cf75e1 100644 --- a/eo/README +++ b/eo/README @@ -1,8 +1,7 @@ - - EO README FILE + EO README FILE ======================================================================= - check latest news at http://eodev.sourceforge.net/ + check latest news at http://eodev.sourceforge.net/ ======================================================================= Welcome to EO, the Evolving Objects library. @@ -14,7 +13,7 @@ In case of any problem, please e-mail us at eodev-help@lists.sourceforge.net, eodev@egroups.com To get started, take a look at the tutorial, starting with - ./tutorial/html/eoTutorial.html + ./tutorial/html/eoTutorial.html The easiest way to start programming a new genome with all EO evolution engines handy is to create a new standalone EO project from @@ -23,11 +22,11 @@ an introduction;) ================================================================== - BUILDING EO + BUILDING EO ================================================================== The basic installation procedure goes the following: -Go to your build-directory and run +Go to your build-directory and run $(SRCDIR)/configure make make check @@ -50,7 +49,7 @@ specific about EO. =================================================================== - DIRECTORY STRUCTURE + DIRECTORY STRUCTURE =================================================================== After unpacking the archive file, you should end up with the following structure: @@ -63,7 +62,7 @@ structure: | | | +- ga bistring-genotypes source files | | - | +- es real-valued-genotypes source files + | +- es real-valued-genotypes source files | | | +- gp Genetic Programming source files | | @@ -74,9 +73,9 @@ structure: +-- tutorial TUTORIAL dir (indeed :-) | | | +- html all html files - start by browsing index.html - | | + | | | +- LessonX for X=1, 2, 3, ... : example of increasing complexity - | + | | | +-- doc DOCUMENTATION dir (generated by Doxygen) @@ -93,7 +92,7 @@ structure: | +-- app APPLICATIONS - one dir per separate application | | - | +- gprop GA/backpropagation for neural nets + | +- gprop GA/backpropagation for neural nets | | | +- mastermind the wellknown MasterMind game | @@ -103,7 +102,7 @@ structure: =================================================================== - NOTES + NOTES =================================================================== If you extracted a fresh snapshot from the cvs-repository, remember to run diff --git a/eo/app/gprop/CMakeLists.txt b/eo/app/gprop/CMakeLists.txt index e19df9bd..e37af2e5 100644 --- a/eo/app/gprop/CMakeLists.txt +++ b/eo/app/gprop/CMakeLists.txt @@ -18,15 +18,14 @@ LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) SET (GPROP_SOURCES gprop.cpp) # especially for Visual Studio -IF(NOT WIN32 OR CYGWIN) - ADD_EXECUTABLE(gprop ${GPROP_SOURCES}) +IF(NOT WIN32 OR CYGWIN) + ADD_EXECUTABLE(gprop ${GPROP_SOURCES}) ADD_DEPENDENCIES(gprop eo eoutils) - - TARGET_LINK_LIBRARIES(gprop eo eoutils) - + + TARGET_LINK_LIBRARIES(gprop eo eoutils) + SET(GPROP_VERSION ${GLOBAL_VERSION}) SET_TARGET_PROPERTIES(gprop PROPERTIES VERSION "${GPROP_VERSION}") ENDIF(NOT WIN32 OR CYGWIN) ###################################################################################### - diff --git a/eo/app/gprop/gprop.h b/eo/app/gprop/gprop.h index 98904186..db67c188 100644 --- a/eo/app/gprop/gprop.h +++ b/eo/app/gprop/gprop.h @@ -207,12 +207,12 @@ int correct(const mlp::net& net, const mlp::set& set) unsigned partial = 0; for (unsigned i = 0; i < s->output.size(); ++i) - if ((s->output[i] < 0.5 && net(s->input)[i] < 0.5) || - (s->output[i] > 0.5 && net(s->input)[i] > 0.5)) - ++partial; + if ((s->output[i] < 0.5 && net(s->input)[i] < 0.5) || + (s->output[i] > 0.5 && net(s->input)[i] > 0.5)) + ++partial; if (partial == s->output.size()) - ++sum; + ++sum; } return sum; diff --git a/eo/app/gprop/l2.h b/eo/app/gprop/l2.h index 011c6610..cff4a67c 100644 --- a/eo/app/gprop/l2.h +++ b/eo/app/gprop/l2.h @@ -29,7 +29,7 @@ namespace l2 //--------------------------------------------------------------------------- // error //--------------------------------------------------------------------------- - + real error(const mlp::net& net, const set& ts) { real error_ = 0.0; @@ -37,12 +37,12 @@ namespace l2 for (set::const_iterator s = ts.begin(); s != ts.end(); ++s) { vector out = net(s->input); - + for (unsigned i = 0; i < out.size(); ++i) { real target = s->output[i]; real value = out[i]; - error_ -= target * log(value + min_real) + + error_ -= target * log(value + min_real) + (1.0 - target) * log(1.0 - value + min_real); } } @@ -53,25 +53,25 @@ namespace l2 //------------------------------------------------------------------------- // l2 //------------------------------------------------------------------------- - + class net: public qp::net { public: net(mlp::net& n): qp::net(n) {} - + real error(const set& ts) { real error_ = 0; - + for (set::const_iterator s = ts.begin(); s != ts.end(); ++s) { forward(s->input); error_ -= backward(s->input, s->output); } - + return error_; } - + private: real backward(const vector& input, const vector& output) { @@ -84,7 +84,7 @@ namespace l2 { neuron& n = (*current_layer)[j]; real out = output[j]; - n.ndelta += n.delta = (out - n.out) / + n.ndelta += n.delta = (out - n.out) / (n.out * (1.0 - n.out) + min_real) * n.out * (1.0 - n.out); if (size() == 1) // monolayer @@ -92,21 +92,21 @@ namespace l2 else // multilayer for (unsigned k = 0; k < n.dxo.size(); ++k) n.dxo[k] += n.delta * (*backward_layer)[k].out; - - error_ += out * log(n.out + min_real) + + + error_ += out * log(n.out + min_real) + (1.0 - out) * log(1.0 - n.out + min_real); } - + // hidden layers while (++current_layer != rend()) { reverse_iterator forward_layer = current_layer - 1; - reverse_iterator backward_layer = current_layer + 1; - + reverse_iterator backward_layer = current_layer + 1; + for (unsigned j = 0; j < current_layer->size(); ++j) { neuron& n = (*current_layer)[j]; - real sum = 0; + real sum = 0; for (unsigned k = 0; k < forward_layer->size(); ++k) { neuron& nf = (*forward_layer)[k]; @@ -114,7 +114,7 @@ namespace l2 } n.delta = n.out * (1.0 - n.out) * sum; n.ndelta += n.delta; - + if (backward_layer == rend()) // first hidden layer n.dxo += n.delta * input; else // rest of hidden layers @@ -122,19 +122,19 @@ namespace l2 n.dxo[k] += n.delta * (*backward_layer)[k].out; } } - + return error_; } }; - + //--------------------------------------------------------------------------- - + } // namespace l2 //----------------------------------------------------------------------------- #endif // l2_h -// Local Variables: -// mode:C++ +// Local Variables: +// mode:C++ // End: diff --git a/eo/app/gprop/mlp.h b/eo/app/gprop/mlp.h index dbd12bda..c7c61282 100644 --- a/eo/app/gprop/mlp.h +++ b/eo/app/gprop/mlp.h @@ -45,7 +45,7 @@ namespace std { istream& operator>>(istream& is, mlp::vector& v) { for (mlp::vector::iterator vi = v.begin() ; vi != v.end() ; vi++) { - is >> *vi; + is >> *vi; } return is; } @@ -133,15 +133,15 @@ namespace mlp #ifdef HAVE_LIBYAML_CPP YAML_SERIALIZABLE_AUTO(neuron) void emit_yaml(YAML::Emitter&out) const { - out << YAML::BeginMap; - out << YAML::Key << "Class" << YAML::Value << "mlp::neuron"; - YAML_EMIT_MEMBER(out,bias); - YAML_EMIT_MEMBER(out,weight); - out << YAML::EndMap; + out << YAML::BeginMap; + out << YAML::Key << "Class" << YAML::Value << "mlp::neuron"; + YAML_EMIT_MEMBER(out,bias); + YAML_EMIT_MEMBER(out,weight); + out << YAML::EndMap; } void load_yaml(const YAML::Node& node) { - YAML_LOAD_MEMBER(node, bias); - YAML_LOAD_MEMBER(node, weight); + YAML_LOAD_MEMBER(node, bias); + YAML_LOAD_MEMBER(node, weight); } #endif }; @@ -213,17 +213,17 @@ namespace mlp { } #ifdef HAVE_LIBYAML_CPP friend ostream& operator<<(YAML::Emitter& e, const layer &l) { - e << ((std::vector)l); + e << ((std::vector)l); } friend void operator>>(const YAML::Node& n, layer &l) { - // These temporary variable shenanegins are necessary because - // the compiler gets very confused about which template operator>> - // function to use. - // The following does not work: n >> l; - // So we use a temporary variable thusly: - std::vector *obviously_a_vector = &l; - n >> *obviously_a_vector; + // These temporary variable shenanegins are necessary because + // the compiler gets very confused about which template operator>> + // function to use. + // The following does not work: n >> l; + // So we use a temporary variable thusly: + std::vector *obviously_a_vector = &l; + n >> *obviously_a_vector; } #endif @@ -243,7 +243,7 @@ namespace std { istream& operator>>(istream& is, mlp::layer& l) { for (mlp::layer::iterator li = l.begin() ; li != l.end() ; li++) { - is >> *li; + is >> *li; } return is; } @@ -277,15 +277,15 @@ namespace mlp { #ifdef HAVE_LIBYAML_CPP YAML_SERIALIZABLE_AUTO(net) void emit_members(YAML::Emitter&out) const { - const std::vector* me_as_layer_vector = this; - out << YAML::Key << "layers" << YAML::Value << *me_as_layer_vector; + const std::vector* me_as_layer_vector = this; + out << YAML::Key << "layers" << YAML::Value << *me_as_layer_vector; } void load_members(const YAML::Node& node) { - std::vector* me_as_layer_vector = this; - node["layers"] >> *me_as_layer_vector; + std::vector* me_as_layer_vector = this; + node["layers"] >> *me_as_layer_vector; } - #endif // HAVE_LIBYAML_CPP + #endif // HAVE_LIBYAML_CPP /** Virtual destructor */ virtual ~net() {}; @@ -303,14 +303,14 @@ namespace mlp { is >> layer_size; layer_sizes.push_back(layer_size); } - unsigned check_outputs; + unsigned check_outputs; is >> check_outputs; assert (check_outputs == num_outputs); init (num_inputs,num_outputs,layer_sizes); - // skip forward to pass up opening '<' char - char c=' '; - while (c!='<' && !is.eof()) { is >> c;} - for (iterator l =begin() ; l != end(); l++) { + // skip forward to pass up opening '<' char + char c=' '; + while (c!='<' && !is.eof()) { is >> c;} + for (iterator l =begin() ; l != end(); l++) { is >> *l; } do { is >> c; } while (c == ' ' && !is.eof()); @@ -351,15 +351,15 @@ namespace mlp { } void save(ostream &os) const { - // Save the number of inputs, number of outputs, and number of hidden layers + // Save the number of inputs, number of outputs, and number of hidden layers os << num_inputs() << "\n" << num_outputs() << "\n" << num_hidden_layers() << "\n"; - for(const_iterator l = begin(); l != end(); ++l) + for(const_iterator l = begin(); l != end(); ++l) os << l->size() << " "; - os << "\n"; - os << "< "; - for(const_iterator l = begin(); l != end(); ++l) + os << "\n"; + os << "< "; + for(const_iterator l = begin(); l != end(); ++l) os << *l << " "; - os << ">\n"; + os << ">\n"; } @@ -454,7 +454,7 @@ namespace mlp { void load(istream &is) { unsigned input_size, output_size; - is >> input_size >> output_size; + is >> input_size >> output_size; sample samp(input_size, output_size);; while (is >> samp) { push_back(samp); } } diff --git a/eo/app/gprop/mse.h b/eo/app/gprop/mse.h index 841a88e3..3fb62fa0 100644 --- a/eo/app/gprop/mse.h +++ b/eo/app/gprop/mse.h @@ -28,7 +28,7 @@ namespace mse //--------------------------------------------------------------------------- // error //--------------------------------------------------------------------------- - + real error(const mlp::net& net, const set& ts) { real error_ = 0.0; @@ -36,7 +36,7 @@ namespace mse for (set::const_iterator s = ts.begin(); s != ts.end(); ++s) { vector out = net(s->input); - + for (unsigned i = 0; i < out.size(); ++i) { real diff = s->output[i] - out[i]; @@ -49,26 +49,26 @@ namespace mse //------------------------------------------------------------------------- // mse //------------------------------------------------------------------------- - + class net: public qp::net { public: net(mlp::net& n): qp::net(n) {} - + real error(const set& ts) { real error_ = 0; - + for (set::const_iterator s = ts.begin(); s != ts.end(); ++s) { forward(s->input); error_ += backward(s->input, s->output); } error_ /= ts.size(); - + return error_; } - + private: real backward(const vector& input, const vector& output) { @@ -89,22 +89,22 @@ namespace mse else // multilayer for (unsigned k = 0; k < n.dxo.size(); ++k) n.dxo[k] += n.delta * (*backward_layer)[k].out; - + error_ += diff * diff; } - + // hidden layers while (++current_layer != rend()) { reverse_iterator forward_layer = current_layer - 1; reverse_iterator backward_layer = current_layer + 1; - + for (unsigned j = 0; j < current_layer->size(); ++j) { - + neuron& n = (*current_layer)[j]; real sum = 0; - + for (unsigned k = 0; k < forward_layer->size(); ++k) { neuron& nf = (*forward_layer)[k]; @@ -113,8 +113,8 @@ namespace mse n.delta = n.out * (1.0 - n.out) * sum; n.ndelta += n.delta; - - + + if (backward_layer == rend()) // first hidden layer n.dxo += n.delta * input; else // rest of hidden layers @@ -122,19 +122,19 @@ namespace mse n.dxo[k] += n.delta * (*backward_layer)[k].out; } } - + return error_; } }; //--------------------------------------------------------------------------- - + } // namespace mse //----------------------------------------------------------------------------- #endif // mse_h -// Local Variables: -// mode:C++ +// Local Variables: +// mode:C++ // End: diff --git a/eo/app/gprop/qp.h b/eo/app/gprop/qp.h index 068d1382..fb983675 100644 --- a/eo/app/gprop/qp.h +++ b/eo/app/gprop/qp.h @@ -41,55 +41,55 @@ namespace qp const real backtrack_step = 0.5; const real me_floor = 0.0001; const real mw_floor = 0.0001; - + //--------------------------------------------------------------------------- // neuron //--------------------------------------------------------------------------- - + struct neuron { mlp::neuron* n; real out, delta, ndelta, dbias1, dbias2; vector dweight1, dweight2, dxo; - - neuron(mlp::neuron& _n): - n(&_n), out(0), delta(0), ndelta(0), dbias1(0), dbias2(0), - dweight1(n->weight.size(), 0), - dweight2(n->weight.size(), 0), + + neuron(mlp::neuron& _n): + n(&_n), out(0), delta(0), ndelta(0), dbias1(0), dbias2(0), + dweight1(n->weight.size(), 0), + dweight2(n->weight.size(), 0), dxo(n->weight.size(), 0) {} - + void reset() { // underlaying neuron n->reset(); - + // addons out = delta = ndelta = dbias1 = dbias2 = 0; fill(dweight1.begin(), dweight1.end(), 0); fill(dweight2.begin(), dweight2.end(), 0); fill(dxo.begin(), dxo.end(), 0); } - + real operator()(const vector& input) { - return out = mlp::sigmoid(n->bias + dbias1 + + return out = mlp::sigmoid(n->bias + dbias1 + (n->weight + dweight1) * input); } }; - + std::ostream& operator<<(std::ostream& os, const neuron& n) { - return os << *n.n << " " << n.out << " " << n.delta << " " - << n.ndelta << " " << n.dbias1 << " " << n.dbias2 << " " + return os << *n.n << " " << n.out << " " << n.delta << " " + << n.ndelta << " " << n.dbias1 << " " << n.dbias2 << " " << n.dweight1 << " " << n.dweight2 << " " << n.dxo; } - - + + //--------------------------------------------------------------------------- // layer //--------------------------------------------------------------------------- - + class layer: public std::vector { public: @@ -102,16 +102,16 @@ namespace qp void reset() { for(iterator n = begin(); n != end(); ++n) - n->reset(); + n->reset(); } vector operator()(const vector& input) { vector output(size()); - + for(unsigned i = 0; i < output.size(); ++i) - output[i] = (*this)[i](input); - + output[i] = (*this)[i](input); + return output; } }; @@ -120,10 +120,10 @@ namespace qp //--------------------------------------------------------------------------- // net //--------------------------------------------------------------------------- - + class net: public std::vector { - public: + public: net(mlp::net& n) //: std::vector(n.begin(), n.end()) { reset(); } { for (mlp::net::iterator l = n.begin(); l != n.end(); ++l) @@ -135,27 +135,27 @@ namespace qp void reset() { for(iterator l = begin(); l != end(); ++l) - l->reset(); + l->reset(); } - - real train(const set& ts, - unsigned epochs, - real target_error, + + real train(const set& ts, + unsigned epochs, + real target_error, real tolerance, - real eta = eta_default, - real momentum = alpha_default, + real eta = eta_default, + real momentum = alpha_default, real lambda = lambda_default) { real error_ = max_real; - + while (epochs-- && error_ > target_error) { real last_error = error_; - + init_delta(); error_ = error(ts); - + if (error_ < last_error + tolerance) { coeff_adapt(eta, momentum, lambda); @@ -170,10 +170,10 @@ namespace qp error_ = last_error; } } - + return error_; } - + virtual real error(const set& ts) = 0; // protected: @@ -185,7 +185,7 @@ namespace qp input.swap(tmp); } } - + // private: void init_delta() { @@ -193,11 +193,11 @@ namespace qp for (layer::iterator n = l->begin(); n != l->end(); ++n) fill(n->dxo.begin(), n->dxo.end(), n->ndelta = 0.0); } - + void coeff_adapt(real& eta, real& momentum, real& lambda) { real me = 0, mw = 0, ew = 0; - + for (iterator l = begin(); l != end(); ++l) for (layer::iterator n = l->begin(); n != l->end(); ++n) { @@ -205,7 +205,7 @@ namespace qp mw += n->dweight1 * n->dweight1; ew += n->dxo * n->dweight1; } - + me = std::max(static_cast(sqrt(me)), me_floor); mw = std::max(static_cast(sqrt(mw)), mw_floor); eta *= (1.0 + 0.5 * ew / ( me * mw)); @@ -213,11 +213,11 @@ namespace qp lambda = lambda0 * me / mw; momentum = eta * lambda; #ifdef DEBUG - std::cout << me << " \t" << mw << " \t" << ew << " \t" + std::cout << me << " \t" << mw << " \t" << ew << " \t" << eta << " \t" << momentum << " \t" << lambda << std::endl; #endif // DEBUG } - + void weight_update(unsigned size, bool fire, real eta, real momentum) { for (iterator l = begin(); l != end(); ++l) @@ -239,13 +239,13 @@ namespace qp }; //--------------------------------------------------------------------------- - + } // namespace qp //----------------------------------------------------------------------------- #endif // qp_h -// Local Variables: -// mode:C++ +// Local Variables: +// mode:C++ // End: diff --git a/eo/app/gprop/vecop.h b/eo/app/gprop/vecop.h index 2654f2b1..dd4a23a8 100644 --- a/eo/app/gprop/vecop.h +++ b/eo/app/gprop/vecop.h @@ -160,14 +160,14 @@ template std::ostream& operator<<(std::ostream& os, const std::vector(os, " ")); os << v.back(); - } + } return os << '>'; } template std::istream& operator>>(std::istream& is, std::vector& v) { v.clear(); - + char c; is >> c; if (!is || c != '<') @@ -186,7 +186,7 @@ template std::istream& operator>>(std::istream& is, std::vector& v) } } while (is && c != '>'); } - + return is; } @@ -194,11 +194,11 @@ template std::istream& operator>>(std::istream& is, std::vector& v) // euclidean_distance //----------------------------------------------------------------------------- -template T euclidean_distance(const std::vector& v1, +template T euclidean_distance(const std::vector& v1, const std::vector& v2) { T sum = 0, tmp; - + for (unsigned i = 0; i < v1.size(); ++i) { tmp = v1[i] - v2[i]; @@ -211,4 +211,3 @@ template T euclidean_distance(const std::vector& v1, //----------------------------------------------------------------------------- #endif - diff --git a/eo/app/gpsymreg/CMakeLists.txt b/eo/app/gpsymreg/CMakeLists.txt index 45b561e1..1bb25867 100644 --- a/eo/app/gpsymreg/CMakeLists.txt +++ b/eo/app/gpsymreg/CMakeLists.txt @@ -18,8 +18,8 @@ LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) SET (GPSYMREG_SOURCES main.cpp) # no matter what is the OS, hopefully -ADD_EXECUTABLE(gpsymreg ${GPSYMREG_SOURCES}) - +ADD_EXECUTABLE(gpsymreg ${GPSYMREG_SOURCES}) + ADD_DEPENDENCIES(gpsymreg eo eoutils) ###################################################################################### @@ -36,4 +36,3 @@ SET_TARGET_PROPERTIES(gpsymreg PROPERTIES VERSION "${GPSYMREG_VERSION}") TARGET_LINK_LIBRARIES(gpsymreg eo eoutils) ###################################################################################### - diff --git a/eo/app/gpsymreg/fitness.h b/eo/app/gpsymreg/fitness.h index 90047cc7..d4fdb505 100644 --- a/eo/app/gpsymreg/fitness.h +++ b/eo/app/gpsymreg/fitness.h @@ -14,7 +14,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - jeggermo@liacs.nl + jeggermo@liacs.nl */ #ifndef _FITNESS_FUNCTION_H @@ -225,4 +225,3 @@ class RegFitness: public eoEvalFunc< eoParseTree > }; #endif - diff --git a/eo/app/gpsymreg/main.cpp b/eo/app/gpsymreg/main.cpp index 98823e34..6d3318ff 100644 --- a/eo/app/gpsymreg/main.cpp +++ b/eo/app/gpsymreg/main.cpp @@ -30,7 +30,7 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es - jeggermo@liacs.nl + jeggermo@liacs.nl */ @@ -146,25 +146,25 @@ int main(int argc, char *argv[]) // the parameters are passed on as well - RegFitness eval(generationCounter, initSequence, parameter); + RegFitness eval(generationCounter, initSequence, parameter); // Depth Initializor, set for Ramped Half and Half Initialization - eoParseTreeDepthInit initializer(parameter.InitMaxDepth, initSequence, true, true); + eoParseTreeDepthInit initializer(parameter.InitMaxDepth, initSequence, true, true); // create the initial population - Pop pop(parameter.population_size, initializer); + Pop pop(parameter.population_size, initializer); // and evaluate the individuals - apply(eval, pop); + apply(eval, pop); @@ -335,10 +335,3 @@ int main(int argc, char *argv[]) } - - - - - - - diff --git a/eo/app/gpsymreg/node.h b/eo/app/gpsymreg/node.h index 85aa4479..02b0279b 100644 --- a/eo/app/gpsymreg/node.h +++ b/eo/app/gpsymreg/node.h @@ -3,18 +3,18 @@ it under the terms of the GNU 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 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 - jeggermo@liacs.nl + jeggermo@liacs.nl */ #ifndef _NODE_H @@ -33,13 +33,13 @@ using namespace std; /* A new Operation and Node class for even more flexibility. Improvements over the t-eoSymreg code are: - + * No hardcoded functions or operators. The Operation and Node class below allow you to specify your own unary and binary functions as well as binary operators (like +,-,*,/). Moreover you can detemine if you want to allow primitve subroutines with either one or two arguments. - - If a Node has a subroutine Operation it will take evaluate the first + + If a Node has a subroutine Operation it will take evaluate the first (and possible second) child branch and use them as input variables for the remaining second (or third) child branch. */ @@ -47,20 +47,20 @@ using namespace std; typedef enum {Variable, UFunction, BFunction, BOperator, Const} Type; -typedef double (*BinaryFunction)(const double,const double); +typedef double (*BinaryFunction)(const double,const double); typedef double (*UnaryFunction)(const double); struct Operation { public: - + typedef unsigned int VariableID; typedef string Label; - + // if your compiler allows you to have nameless unions you can make this a // union by removing the //'s below - + //union //{ UnaryFunction uFunction; @@ -68,34 +68,34 @@ struct Operation VariableID id; double constant; //}; - - - + + + Label label; Type type; - + // the default constructor results in a constant with value 0 Operation() : constant(0), label("0"), type(Const){}; // two possible constructors for Unary Functions Operation(UnaryFunction _uf, Label _label): uFunction(_uf), label(_label), type(UFunction) {}; Operation(Label _label, UnaryFunction _uf): uFunction(_uf), label(_label), type(UFunction) {}; - + // Watch out there are two constructors using pointers two binary functions: // Binary Function (printed as label(subtree0,subtree1) (e.g. pow(x,y)) // Binary Operator (printed as (subtree0 label subtree1) (e.g. x^y) // The difference is purely cosmetic. - + // If you specify the label before the function pointer -> Binary Function Operation(Label _label, BinaryFunction _bf): bFunction(_bf), label(_label), type(BFunction) {}; // If you specify the function pointer before the label -> Binary Operator Operation(BinaryFunction _bf, Label _label): bFunction(_bf), label(_label), type(BOperator) {}; - + // A constructor for variables Operation(VariableID _id, Label _label): id(_id), label(_label), type(Variable) {}; // A constructor for constants Operation(double _constant, Label _label): constant(_constant), label(_label), type(Const) {}; - - + + Operation(const Operation &_op) { switch(_op.type) @@ -110,7 +110,7 @@ struct Operation label = _op.label; }; virtual ~Operation(){}; - + }; @@ -118,14 +118,14 @@ class Node { private: Operation op; - + public: - + Node(void): op(Operation()){}; Node(Operation &_op) : op(_op){}; virtual ~Node(void) {} - - int arity(void) const + + int arity(void) const { switch(op.type) { @@ -134,53 +134,53 @@ class Node case BFunction: return 2; case BOperator: return 2; case Const: return 0; - } - return 0; + } + return 0; } - + void randomize(void) {} - + template void operator()(double& result, Children args, vector &var) const { double result0; double result1; - - + + switch(op.type) { case Variable: result = var[op.id%var.size()]; //%var.size() used in the case of Subroutines and as a security measure break; case UFunction: args[0].apply(result0, var); - result = op.uFunction(result0); + result = op.uFunction(result0); break; - case BFunction: + case BFunction: case BOperator: args[0].apply(result0, var); - args[1].apply(result1, var); + args[1].apply(result1, var); result = op.bFunction(result0,result1); break; case Const: result = op.constant; - break; - + break; + } - + } - + template void operator()(string& result, Children args) const { - + string subtree0; string subtree1; string subtree2; - + switch(op.type) { - - case Variable: + + case Variable: case Const: result += op.label; break; - + case UFunction: result += op.label; result += "("; args[0].apply(subtree0); @@ -195,7 +195,7 @@ class Node args[1].apply(subtree1); result += subtree1; result += ")"; - break; + break; case BOperator: result += "("; args[0].apply(subtree0); result += subtree0; @@ -204,16 +204,16 @@ class Node result += subtree1; result += ")"; break; - default: result += "ERROR in Node::operator(string,...) \n"; break; + default: result += "ERROR in Node::operator(string,...) \n"; break; } } - + Operation getOp(void) const {return op;} - + }; - - + + @@ -230,7 +230,7 @@ class Node std::ostream& operator<<(std::ostream& os, const Node& eot) { Operation op(eot.getOp()); - + os << (eot.getOp()).label; return os; } diff --git a/eo/app/gpsymreg/parameters.h b/eo/app/gpsymreg/parameters.h index 4cd23ec0..ed9a0257 100644 --- a/eo/app/gpsymreg/parameters.h +++ b/eo/app/gpsymreg/parameters.h @@ -3,18 +3,18 @@ it under the terms of the GNU 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 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 - jeggermo@liacs.nl + jeggermo@liacs.nl */ #ifndef _PARAMETERS_FUNCTION_H @@ -28,7 +28,7 @@ using namespace std; struct Parameters{ unsigned int nGenerations; // -G - unsigned population_size; // -P + unsigned population_size; // -P unsigned offspring_size; // -O unsigned int MaxSize; // -S unsigned int InitMaxDepth; // -D @@ -41,72 +41,72 @@ struct Parameters{ Parameters(int argc, char **argv) { eoParser parser(argc,argv); - + // generations eoValueParam paramGenerations(1, "generations", "Generations", 'G', false); parser.processParam( paramGenerations ); nGenerations = paramGenerations.value(); cerr << "nGenerations= " << nGenerations << endl; - + // populationsize eoValueParam paramPopulationSize(10, "populationsize", "PopulationSize", 'P', false); parser.processParam( paramPopulationSize ); population_size = paramPopulationSize.value(); cerr << "population_size= " << population_size << endl; - + // offspringsize eoValueParam paramOffspringSize(population_size, "offspringsize", "OffspringSize", 'O', false); parser.processParam( paramOffspringSize ); offspring_size = paramOffspringSize.value(); cerr << "offspring_size= " << offspring_size << endl; - + // maxsize eoValueParam paramMaxSize(15, "maxsize", "MaxSize", 'S', false); parser.processParam( paramMaxSize ); MaxSize = paramMaxSize.value(); cerr << "MaxSize= " << MaxSize << endl; - + // initialmaxdepth eoValueParam paramInitialMaxDepth(4, "initialmaxdepth", "InitialMaxDepth", 'D', false); parser.processParam( paramInitialMaxDepth ); InitMaxDepth = paramInitialMaxDepth.value(); cerr << "InitMaxDepth= " << InitMaxDepth << endl; - + // randomseed eoValueParam paramRandomSeed(1, "randomseed", "Random Seed", 'R', false); parser.processParam( paramRandomSeed ); randomseed = paramRandomSeed.value(); cerr << "randomseed= " << randomseed << endl; - - + + // crossover-rate eoValueParam paramXover(0.75, "crossoverrate", "crossover rate", 'x', false); parser.processParam(paramXover ); xover_rate = paramXover.value(); cerr << "xover_rate= " << xover_rate << endl; - + //mutation-rate eoValueParam paramMutation(0.25, "mutationrate", "mutation rate", 'm', false); parser.processParam(paramMutation ); mutation_rate = paramMutation.value(); cerr << "mutation_rate= " << mutation_rate << endl; - + //tournament size eoValueParam paramTournamentSize(5, "tournamentsize", "tournament size", 't', false); parser.processParam(paramTournamentSize ); tournamentsize = paramTournamentSize.value(); cerr << "Tournament Size= " << tournamentsize << endl; - - + + if (parser.userNeedsHelp()) { - parser.printHelp(cout); - exit(1); + parser.printHelp(cout); + exit(1); } }; - + ~Parameters(){}; -}; +}; #endif diff --git a/eo/app/mastermind/CMakeLists.txt b/eo/app/mastermind/CMakeLists.txt index d07e9741..6fde0887 100644 --- a/eo/app/mastermind/CMakeLists.txt +++ b/eo/app/mastermind/CMakeLists.txt @@ -18,8 +18,8 @@ LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) SET (MASTERMIND_SOURCES mastermind.cpp) # no matter what is the OS, hopefully -ADD_EXECUTABLE(mastermind ${MASTERMIND_SOURCES}) - +ADD_EXECUTABLE(mastermind ${MASTERMIND_SOURCES}) + ADD_DEPENDENCIES(mastermind eo eoutils) ###################################################################################### @@ -36,4 +36,3 @@ SET_TARGET_PROPERTIES(mastermind PROPERTIES VERSION "${MASTERMIND_VERSION}") TARGET_LINK_LIBRARIES(mastermind eo eoutils) ###################################################################################### - diff --git a/eo/app/mastermind/mastermind.cpp b/eo/app/mastermind/mastermind.cpp index 9a2ed163..c1788991 100644 --- a/eo/app/mastermind/mastermind.cpp +++ b/eo/app/mastermind/mastermind.cpp @@ -51,8 +51,8 @@ int main(int argc, char** argv) } catch (exception& e) { - cerr << argv[0] << ": " << e.what() << endl; - exit(EXIT_FAILURE); + cerr << argv[0] << ": " << e.what() << endl; + exit(EXIT_FAILURE); } return 0; diff --git a/eo/config.guess b/eo/config.guess index 9b9789b1..2784e1b2 100755 --- a/eo/config.guess +++ b/eo/config.guess @@ -3,7 +3,7 @@ # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003 Free Software Foundation, Inc. -timestamp='2004-03-03' +timestamp='2011-05-05' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -186,7 +186,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in fi ;; *) - os=netbsd + os=netbsd ;; esac # The OS release @@ -270,7 +270,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) - UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on @@ -342,7 +342,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in echo i370-ibm-openedition exit 0 ;; *:OS400:*:*) - echo powerpc-ibm-os400 + echo powerpc-ibm-os400 exit 0 ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} @@ -419,23 +419,23 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} + echo m68k-atari-mint${UNAME_RELEASE} exit 0 ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} - exit 0 ;; + exit 0 ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} + echo m68k-atari-mint${UNAME_RELEASE} exit 0 ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) - echo m68k-milan-mint${UNAME_RELEASE} - exit 0 ;; + echo m68k-milan-mint${UNAME_RELEASE} + exit 0 ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) - echo m68k-hades-mint${UNAME_RELEASE} - exit 0 ;; + echo m68k-hades-mint${UNAME_RELEASE} + exit 0 ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) - echo m68k-unknown-mint${UNAME_RELEASE} - exit 0 ;; + echo m68k-unknown-mint${UNAME_RELEASE} + exit 0 ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit 0 ;; @@ -504,8 +504,8 @@ EOF echo m88k-motorola-sysv3 exit 0 ;; AViiON:dgux:*:*) - # DG/UX returns AViiON for all architectures - UNAME_PROCESSOR=`/usr/bin/uname -p` + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ @@ -614,52 +614,52 @@ EOF 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` - sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` - case "${sc_cpu_version}" in - 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 - 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 - 532) # CPU_PA_RISC2_0 - case "${sc_kernel_bits}" in - 32) HP_ARCH="hppa2.0n" ;; - 64) HP_ARCH="hppa2.0w" ;; + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 - esac ;; - esac + esac ;; + esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c - #define _HPUX_SOURCE - #include - #include + #define _HPUX_SOURCE + #include + #include - int main () - { - #if defined(_SC_KERNEL_BITS) - long bits = sysconf(_SC_KERNEL_BITS); - #endif - long cpu = sysconf (_SC_CPU_VERSION); + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); - switch (cpu) - { - case CPU_PA_RISC1_0: puts ("hppa1.0"); break; - case CPU_PA_RISC1_1: puts ("hppa1.1"); break; - case CPU_PA_RISC2_0: - #if defined(_SC_KERNEL_BITS) - switch (bits) - { - case 64: puts ("hppa2.0w"); break; - case 32: puts ("hppa2.0n"); break; - default: puts ("hppa2.0"); break; - } break; - #else /* !defined(_SC_KERNEL_BITS) */ - puts ("hppa2.0"); break; - #endif - default: puts ("hppa1.0"); break; - } - exit (0); - } + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa @@ -739,22 +739,22 @@ EOF exit 0 ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd - exit 0 ;; + exit 0 ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi - exit 0 ;; + exit 0 ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd - exit 0 ;; + exit 0 ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd - exit 0 ;; + exit 0 ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd - exit 0 ;; + exit 0 ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit 0 ;; @@ -778,14 +778,14 @@ EOF exit 0 ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` - echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit 0 ;; + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; 5000:UNIX_System_V:4.*:*) - FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` - echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit 0 ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} @@ -919,7 +919,7 @@ EOF EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; - esac + esac objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null if test "$?" = 0 ; then LIBC="-libc1" ; else LIBC="" ; fi echo ${UNAME_MACHINE}-${VENDOR}-linux${LIBC} @@ -961,7 +961,7 @@ EOF s/.*supported targets: *// s/ .*// p'` - case "$ld_supported_targets" in + case "$ld_supported_targets" in elf32-i386) TENTATIVE="${UNAME_MACHINE}-${VENDOR}-linux" ;; @@ -1013,11 +1013,11 @@ EOF echo i386-sequent-sysv4 exit 0 ;; i*86:UNIX_SV:4.2MP:2.*) - # Unixware is an offshoot of SVR4, but it has its own version - # number series starting with 2... - # I am not positive that other SVR4 systems won't match this, + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. - # Use sysv4.2uw... so that sysv4* matches it. + # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit 0 ;; i*86:OS/2:*:*) @@ -1076,10 +1076,10 @@ EOF exit 0 ;; pc:*:*:*) # Left here for compatibility: - # uname -m prints for DJGPP always 'pc', but it prints nothing about - # the processor, so we play safe by assuming i386. + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. echo i386-pc-msdosdjgpp - exit 0 ;; + exit 0 ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit 0 ;; @@ -1114,8 +1114,8 @@ EOF /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) - /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && echo i486-ncr-sysv4 && exit 0 ;; + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4 && exit 0 ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit 0 ;; @@ -1149,9 +1149,9 @@ EOF fi exit 0 ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort - # says - echo i586-unisys-sysv4 - exit 0 ;; + # says + echo i586-unisys-sysv4 + exit 0 ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm @@ -1173,11 +1173,11 @@ EOF exit 0 ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then - echo mips-nec-sysv${UNAME_RELEASE} + echo mips-nec-sysv${UNAME_RELEASE} else - echo mips-unknown-sysv${UNAME_RELEASE} + echo mips-unknown-sysv${UNAME_RELEASE} fi - exit 0 ;; + exit 0 ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit 0 ;; @@ -1262,7 +1262,7 @@ EOF echo pdp10-unknown-its exit 0 ;; SEI:*:*:SEIUX) - echo mips-sei-seiux${UNAME_RELEASE} + echo mips-sei-seiux${UNAME_RELEASE} exit 0 ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` @@ -1289,11 +1289,11 @@ main () #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 - "4" + "4" #else "" #endif - ); exit (0); + ); exit (0); #endif #endif diff --git a/eo/config.h.cmake b/eo/config.h.cmake index 81699c23..24568be1 100644 --- a/eo/config.h.cmake +++ b/eo/config.h.cmake @@ -71,5 +71,3 @@ /* Define to `unsigned int' if does not define. */ #cmakedefine size_t - - diff --git a/eo/contrib/MGE/eoInitVirus.h b/eo/contrib/MGE/eoInitVirus.h index 082339c8..f4cb5307 100644 --- a/eo/contrib/MGE/eoInitVirus.h +++ b/eo/contrib/MGE/eoInitVirus.h @@ -19,8 +19,8 @@ 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 + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk */ //----------------------------------------------------------------------------- @@ -43,7 +43,7 @@ public: eoInitVirus(unsigned _combien, eoRndGenerator& _generator ) : combien(_combien), generator(_generator) {} - + virtual void operator()( eoVirus& chrom) { chrom.resize(combien); @@ -54,7 +54,7 @@ public: } chrom.invalidate(); } - + private : unsigned combien; /// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics @@ -68,7 +68,7 @@ public: eoInitVirus1bit(unsigned _combien, eoRndGenerator& _generator ) : combien(_combien), generator(_generator) {} - + virtual void operator()( eoVirus& chrom) { chrom.resize(combien); @@ -77,7 +77,7 @@ public: chrom.virusBitSet(0, true ); chrom.invalidate(); } - + private : unsigned combien; /// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics diff --git a/eo/contrib/boost/config.hpp b/eo/contrib/boost/config.hpp index 055a2785..176b4391 100644 --- a/eo/contrib/boost/config.hpp +++ b/eo/contrib/boost/config.hpp @@ -1,8 +1,8 @@ // Boost config.hpp configuration header file ------------------------------// -// (C) Copyright John Maddock 2002. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2002. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for most recent version. @@ -57,14 +57,3 @@ #include #endif // BOOST_CONFIG_HPP - - - - - - - - - - - diff --git a/eo/contrib/boost/config/abi_prefix.hpp b/eo/contrib/boost/config/abi_prefix.hpp index 1733dc03..a1d93a2a 100644 --- a/eo/contrib/boost/config/abi_prefix.hpp +++ b/eo/contrib/boost/config/abi_prefix.hpp @@ -1,7 +1,7 @@ // abi_prefix header -------------------------------------------------------// // © Copyright John Maddock 2003 - + // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). diff --git a/eo/contrib/boost/config/abi_suffix.hpp b/eo/contrib/boost/config/abi_suffix.hpp index 6339da63..f9eb493d 100644 --- a/eo/contrib/boost/config/abi_suffix.hpp +++ b/eo/contrib/boost/config/abi_suffix.hpp @@ -1,7 +1,7 @@ // abi_sufffix header -------------------------------------------------------// // © Copyright John Maddock 2003 - + // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). @@ -19,5 +19,3 @@ #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif - - diff --git a/eo/contrib/boost/config/auto_link.hpp b/eo/contrib/boost/config/auto_link.hpp index 0c36f7b0..8a3c2e19 100644 --- a/eo/contrib/boost/config/auto_link.hpp +++ b/eo/contrib/boost/config/auto_link.hpp @@ -18,13 +18,13 @@ USAGE: Before including this header you must define one or more of define the following macros: BOOST_LIB_NAME: Required: A string containing the basename of the library, - for example boost_regex. + for example boost_regex. BOOST_LIB_TOOLSET: Optional: the base name of the toolset. BOOST_DYN_LINK: Optional: when set link to dll rather than static library. BOOST_LIB_DIAGNOSTIC: Optional: when set the header will print out the name - of the library selected (useful for debugging). + of the library selected (useful for debugging). BOOST_AUTO_LINK_NOMANGLE: Specifies that we should link to BOOST_LIB_NAME.lib, - rather than a mangled-name version. + rather than a mangled-name version. These macros will be undef'ed at the end of the header, further this header has no include guards - so be sure to include it only once from your library! @@ -56,13 +56,13 @@ BOOST_LIB_TOOLSET: The compiler toolset name (vc6, vc7, bcb5 etc). BOOST_LIB_THREAD_OPT: "-mt" for multithread builds, otherwise nothing. BOOST_LIB_RT_OPT: A suffix that indicates the runtime library used, - contains one or more of the following letters after - a hiphen: + contains one or more of the following letters after + a hiphen: - s static runtime (dynamic if not present). - d debug build (release if not present). - g debug/diagnostic runtime (release if not present). - p STLPort Build. + s static runtime (dynamic if not present). + d debug build (release if not present). + g debug/diagnostic runtime (release if not present). + p STLPort Build. BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. @@ -342,13 +342,3 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. #if defined(BOOST_AUTO_LINK_NOMANGLE) # undef BOOST_AUTO_LINK_NOMANGLE #endif - - - - - - - - - - diff --git a/eo/contrib/boost/limits.hpp b/eo/contrib/boost/limits.hpp index f468dbce..85607208 100644 --- a/eo/contrib/boost/limits.hpp +++ b/eo/contrib/boost/limits.hpp @@ -1,5 +1,4 @@ - -// (C) Copyright John maddock 1999. +// (C) Copyright John maddock 1999. // (C) David Abrahams 2002. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -33,7 +32,7 @@ namespace std { template<> - class numeric_limits + class numeric_limits { public: @@ -82,11 +81,11 @@ namespace std BOOST_STATIC_CONSTANT(bool, traps = false); BOOST_STATIC_CONSTANT(bool, tinyness_before = false); BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero); - + }; template<> - class numeric_limits + class numeric_limits { public: @@ -135,9 +134,9 @@ namespace std BOOST_STATIC_CONSTANT(bool, traps = false); BOOST_STATIC_CONSTANT(bool, tinyness_before = false); BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero); - + }; } -#endif +#endif #endif diff --git a/eo/contrib/eoAged.h b/eo/contrib/eoAged.h index c4c02fc3..0fa525ae 100644 --- a/eo/contrib/eoAged.h +++ b/eo/contrib/eoAged.h @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- // eoAge.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -38,7 +38,7 @@ using namespace std; //----------------------------------------------------------------------------- /** eoAge is a template class that adds an age to an object.\\ -Requisites for template instantiation are that the object must admit a default ctor +Requisites for template instantiation are that the object must admit a default ctor and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, printOn, readFrom. @see eoObject @@ -55,7 +55,7 @@ class eoAged: public Object /// Virtual dtor. They are needed in virtual class hierarchies virtual ~eoAged() {}; - + ///returns the age of the object unsigned long Age() const {return age;} @@ -67,7 +67,7 @@ class eoAged: public Object readFrom and printOn are directly inherited from eo1d */ //@{ - /** Return the class id. This should be redefined in each class; but + /** Return the class id. This should be redefined in each class; but it's got code as an example of implementation. Only "leaf" classes can be non-virtual. */ @@ -83,7 +83,7 @@ class eoAged: public Object _is >> age; } - + /** * Write object. It's called printOn since it prints the object _on_ a stream. * @param _os A ostream. @@ -93,7 +93,7 @@ class eoAged: public Object _os << age; } //@} - + private: /** Default Constructor. \\ @@ -106,4 +106,3 @@ class eoAged: public Object }; #endif EOAGE_H - diff --git a/eo/contrib/eoDrawable.h b/eo/contrib/eoDrawable.h index 221bf2c1..a614042f 100644 --- a/eo/contrib/eoDrawable.h +++ b/eo/contrib/eoDrawable.h @@ -1,9 +1,9 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + //----------------------------------------------------------------------------- -// eoDrawable.h +// eoDrawable.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,38 +27,38 @@ //----------------------------------------------------------------------------- -using namespace std; +using namespace std; //----------------------------------------------------------------------------- // eoDrawable //----------------------------------------------------------------------------- - -/** eoDrawable is a template class that adds a drawing interface to an object.\\ -Requisites for template instantiation are that the object must admit a default ctor -and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, -eoDrawables can be drawn on any two-dimensional surface; it can be added to any -object with above characteristics. -@see eoObject -*/ + +/** eoDrawable is a template class that adds a drawing interface to an object. +Requisites for template instantiation are that the object must admit a default ctor +and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, +eoDrawables can be drawn on any two-dimensional surface; it can be added to any +object with above characteristics. +@see eoObject +*/ template class eoDrawable { public: - /// Main ctor from an already built Object. - eoDrawable( const Object& _o): Object( _o ){}; + /// Main ctor from an already built Object. + eoDrawable( const Object& _o): Object( _o ){}; /// Copy constructor. - eoDrawable( const eoDrawable& _d): Object( _d ){}; - - /// Virtual dtor. They are needed in virtual class hierarchies - virtual ~eoDrawable() {}; - - - /**Draws the object. It must be redefined in any subclass, it´s impossible - to have a general drawing method - @param _x, _y coorinates */ - virtual void draw( unsigned _x, unsigned _y) = 0; - -}; + eoDrawable( const eoDrawable& _d): Object( _d ){}; -#endif EODRAWABLE_H + /// Virtual dtor. They are needed in virtual class hierarchies + virtual ~eoDrawable() {}; + + + /**Draws the object. It must be redefined in any subclass, it´s impossible + to have a general drawing method + @param _x, _y coorinates */ + virtual void draw( unsigned _x, unsigned _y) = 0; + +}; + +#endif //! EODRAWABLE_H diff --git a/eo/install_symlink.py.cmake b/eo/install_symlink.py.cmake index 0a867f4b..145d67a1 100755 --- a/eo/install_symlink.py.cmake +++ b/eo/install_symlink.py.cmake @@ -9,9 +9,9 @@ PREFIX = "/usr" DATA = { 'dirs': [ "%s/share/%s" % (PREFIX, NAME) ], 'links': [ ("%s/src" % SOURCE, "%s/include/%s" % (PREFIX, NAME)), - ("%s/doc" % BINARY, "%s/share/%s/doc" % (PREFIX, NAME)), - ("%s/%s.pc" % (BINARY, NAME), "%s/lib/pkgconfig/%s.pc" % (PREFIX, NAME)), - ] + ("%s/doc" % BINARY, "%s/share/%s/doc" % (PREFIX, NAME)), + ("%s/%s.pc" % (BINARY, NAME), "%s/lib/pkgconfig/%s.pc" % (PREFIX, NAME)), + ] } LIBRARIES = ["libcma.a", "libeo.a", "libeoutils.a", "libes.a", "libga.a"] @@ -21,8 +21,8 @@ import os, sys def isroot(): if os.getuid() != 0: - print '[WARNING] you have to be root' - return False + print '[WARNING] you have to be root' + return False return True def uninstall(): @@ -41,11 +41,11 @@ def data(): if __name__ == '__main__': if not isroot(): - sys.exit() + sys.exit() if len(sys.argv) < 2: - print 'Usage: %s [install|uninstall|data]' % sys.argv[0] - sys.exit() + print 'Usage: %s [install|uninstall|data]' % sys.argv[0] + sys.exit() if sys.argv[1] == 'install': install() elif sys.argv[1] == 'uninstall': uninstall() diff --git a/eo/test/ChangeLog b/eo/test/ChangeLog index 0167b10a..74702538 100644 --- a/eo/test/ChangeLog +++ b/eo/test/ChangeLog @@ -14,12 +14,12 @@ * test/t-eoSymreg.cpp (SymregNode::operator()): Initialize r1 and r2 to avoid compiler warnings. - - + + 2006-07-02 Thomas Legrand * test/t-eoEasyPSO.cpp: added PSO test - + * test/Makefile.am: added PSO test @@ -28,9 +28,9 @@ * test/t-eoSyncEasyPSO.cpp: added synchronous PSO test * test/t-eoEasyPSO.cpp: customized PSO test (initialization) * test/Makefile.am: added synchronous PSO test - + * Local Variables: * coding: iso-8859-1 * mode: flyspell * fill-column: 80 - * End: \ No newline at end of file + * End: diff --git a/eo/test/RoyalRoad.h b/eo/test/RoyalRoad.h index b49e4741..5592f3cd 100644 --- a/eo/test/RoyalRoad.h +++ b/eo/test/RoyalRoad.h @@ -18,7 +18,7 @@ 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 + Marc.Schoenauer@polytechnique.fr CVS Info: $Date: 2001-06-21 12:03:17 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/test/RoyalRoad.h,v 1.3 2001-06-21 12:03:17 jmerelo Exp $ $Author: jmerelo $ */ @@ -51,7 +51,7 @@ class RoyalRoad: public eoEvalFunc { _eo.fitness( fitness ); } }; - + private: unsigned div; diff --git a/eo/test/binary_value.h b/eo/test/binary_value.h index 793e9de6..59dc4cc3 100644 --- a/eo/test/binary_value.h +++ b/eo/test/binary_value.h @@ -4,7 +4,7 @@ /** Just the simple function that takes binary value of a chromosome and sets the fitnes. - @param _chrom A binary chromosome + @param _chrom A binary chromosome */ template double binary_value(const Chrom& _chrom) diff --git a/eo/test/boxplot.py b/eo/test/boxplot.py index bf6e84b5..20273c18 100755 --- a/eo/test/boxplot.py +++ b/eo/test/boxplot.py @@ -5,11 +5,11 @@ import sys if __name__ == '__main__': if len(sys.argv) < 2: - print 'Usage: boxplot.py [Results files, ...]' - sys.exit() + print 'Usage: boxplot.py [Results files, ...]' + sys.exit() for i in range(1, len(sys.argv)): - pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) + pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] ) pylab.xlabel('iterations') pylab.show() diff --git a/eo/test/fitness_traits.cpp b/eo/test/fitness_traits.cpp index 19edb27a..4af0e34b 100644 --- a/eo/test/fitness_traits.cpp +++ b/eo/test/fitness_traits.cpp @@ -101,7 +101,7 @@ struct fitness_traits< pair > /* end fitness_traits.h */ -/* EO.h +/* EO.h The Fitness template argument is there for backward compatibility reasons @@ -236,7 +236,7 @@ public : { if (!fitness_traits::needs_mapping) { - throw runtime_error("eoPop: no scaling needed, yet a scaling function is defined"); + throw runtime_error("eoPop: no scaling needed, yet a scaling function is defined"); } (*p2w)(*this); @@ -429,5 +429,3 @@ int main() std::cout << e.what() << std::endl; } } - - diff --git a/eo/test/real_value.h b/eo/test/real_value.h index 8bedd6b9..8b58d317 100644 --- a/eo/test/real_value.h +++ b/eo/test/real_value.h @@ -2,8 +2,8 @@ //----------------------------------------------------------------------------- -/** Just a simple function that takes an eoEsBase and sets the fitnes - to sphere +/** Just a simple function that takes an eoEsBase and sets the fitnes + to sphere @param _ind vector */ @@ -14,6 +14,3 @@ double real_value(const std::vector& _ind) sum += _ind[i] * _ind[i]; return sum/_ind.size(); } - - - diff --git a/eo/test/run_tests b/eo/test/run_tests index ebaec0af..22b9644a 100755 --- a/eo/test/run_tests +++ b/eo/test/run_tests @@ -1,7 +1,7 @@ #!/bin/sh echo "Testing -h" -./t-eoCheckpointing -h +./t-eoCheckpointing -h echo "Finished" diff --git a/eo/test/t-eo.cpp b/eo/test/t-eo.cpp index 22fcb5be..f2c0e177 100644 --- a/eo/test/t-eo.cpp +++ b/eo/test/t-eo.cpp @@ -8,8 +8,7 @@ int main() // EO objects can be printed with stream operators std::cout << "chrom1 = " << chrom1 << std::endl - << "chrom2 = " << chrom2 << std::endl; - + << "chrom2 = " << chrom2 << std::endl; + return 0; } - diff --git a/eo/test/t-eo2dVector.cc b/eo/test/t-eo2dVector.cc index bce0e82b..0288fdc5 100644 --- a/eo/test/t-eo2dVector.cc +++ b/eo/test/t-eo2dVector.cc @@ -37,14 +37,14 @@ main() C c1( 5,6,1 ); cout << "Default constructor with values: " << endl << c1 << endl; - + } { eoUniform aleat( 1,10 ); C c1( 5,6, aleat ); cout << "Random constructor: " << endl << c1 << endl; - + } { C c1( 3,4,1 ), c2( c1 ); @@ -111,12 +111,12 @@ main() cout << "Number of Columns: " << endl << c1.numOfCols() << endl; } - + { cout << "Class Name: " << endl << c1.className() << endl; } - + cout << "-----------------------------------------------------" << endl << "Catching exceptions: " << endl diff --git a/eo/test/t-eoCMAES.cpp b/eo/test/t-eoCMAES.cpp index 912d5128..07b59509 100644 --- a/eo/test/t-eoCMAES.cpp +++ b/eo/test/t-eoCMAES.cpp @@ -1,4 +1,3 @@ - #include #include @@ -123,6 +122,3 @@ int main(int argc, char* argv[]) { cout << "Fitness achieved = " << pop[0].fitness() << endl; cout << "Function evaluations = " << evals.value() << endl; } - - - diff --git a/eo/test/t-eoCheckpointing.cpp b/eo/test/t-eoCheckpointing.cpp index 5562ccb0..134b05cc 100644 --- a/eo/test/t-eoCheckpointing.cpp +++ b/eo/test/t-eoCheckpointing.cpp @@ -1,4 +1,3 @@ - // to avoid long name warnings #ifdef _MSC_VER #pragma warning(disable:4786) @@ -113,38 +112,38 @@ int the_main(int argc, char **argv) if (parser.userNeedsHelp()) { - parser.printHelp(std::cout); - return 0; + parser.printHelp(std::cout); + return 0; } // Either load or initialize if (load_name.value() != "") { - state.load(load_name.value()); // load the rest + state.load(load_name.value()); // load the rest } else { - // else + // else - // initialize rng and population + // initialize rng and population - rng.reseed(seed.value()); + rng.reseed(seed.value()); - pop.resize(2); + pop.resize(2); - pop[0].fitness(1); - pop[1].fitness(2); + pop[0].fitness(1); + pop[1].fitness(2); } while(checkpoint(pop)) { - pop[0].fitness(pop[0].fitness() + 1); + pop[0].fitness(pop[0].fitness() + 1); - time_t now = time(0); + time_t now = time(0); - while (time(0) == now) {} // wait a second to test timed saver + while (time(0) == now) {} // wait a second to test timed saver - std::cout << "gen " << generationCounter.value() << std::endl; + std::cout << "gen " << generationCounter.value() << std::endl; } // run the algorithm @@ -152,9 +151,9 @@ int the_main(int argc, char **argv) // Save when needed if (save_name.value() != "") { - std::string file_name = save_name.value(); - save_name.value() = ""; // so that it does not appear in the parser section of the state file - state.save(file_name); + std::string file_name = save_name.value(); + save_name.value() = ""; // so that it does not appear in the parser section of the state file + state.save(file_name); } return 1; @@ -164,11 +163,11 @@ int main(int argc, char **argv) { try { - the_main(argc, argv); + the_main(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << std::endl; + std::cout << "Exception: " << e.what() << std::endl; } } diff --git a/eo/test/t-eoDualFitness.cpp b/eo/test/t-eoDualFitness.cpp index 90b35ed7..6b8fd6e1 100644 --- a/eo/test/t-eoDualFitness.cpp +++ b/eo/test/t-eoDualFitness.cpp @@ -1,4 +1,3 @@ - #include #include @@ -13,16 +12,16 @@ class DualSphere : public eoEvalFunc public: virtual void operator()( EOT & x ) { - if( x.invalid() ) { return; } + if( x.invalid() ) { return; } - double sum = 0; - int sign = 1; - for( unsigned int i=0, s=x.size(); i0 ? true : false ) ); + x.fitness( std::make_pair( sum, sign>0 ? true : false ) ); } }; @@ -60,7 +59,7 @@ int main() pop.push_back( sol4 ); // on the sphere function everyone has the same fitness of 1 if( test(pop, 0) != 0 ) { - exit(1); + exit(1); } pop.erase(pop.begin(),pop.end()); @@ -75,7 +74,7 @@ int main() pop.push_back( sol3 ); pop.push_back( sol4 ); if( test(pop, 1) != 1 ) { - exit(1); + exit(1); } // test on a random normal distribution @@ -84,7 +83,6 @@ int main() pop = eoPop( 1000000, init_N ); double iqr = test(pop, 1.09); if( iqr < 1.08 || iqr > 1.11 ) { - exit(1); + exit(1); } } - diff --git a/eo/test/t-eoESAll.cpp b/eo/test/t-eoESAll.cpp index 07949404..3a77b629 100644 --- a/eo/test/t-eoESAll.cpp +++ b/eo/test/t-eoESAll.cpp @@ -37,34 +37,34 @@ int main_function(int argc, char *argv[]) eoParser parser(argc, argv); // for user-parameter reading eoState state; // keeps all things allocated eoValueParam& simpleParam = parser.getORcreateParam(true, "Isotropic", - "Isotropic self-adaptive mutation", - 'i', "ES mutation"); + "Isotropic self-adaptive mutation", + 'i', "ES mutation"); eoValueParam& stdevsParam = parser.getORcreateParam(false, "Stdev", - "One self-adaptive stDev per variable", - 's', "ES mutation"); + "One self-adaptive stDev per variable", + 's', "ES mutation"); eoValueParam& corrParam = parser.getORcreateParam(false, "Correl", - "Use correlated mutations", - 'c', "ES mutation"); + "Use correlated mutations", + 'c', "ES mutation"); // Run the appropriate algorithm if (simpleParam.value() == false) { - std::cout << "Using eoReal" << std::endl; - runAlgorithm(eoReal(), parser, state); + std::cout << "Using eoReal" << std::endl; + runAlgorithm(eoReal(), parser, state); } else if (stdevsParam.value() == false) { - std::cout << "Using eoEsSimple" << std::endl; - runAlgorithm(eoEsSimple(), parser, state); + std::cout << "Using eoEsSimple" << std::endl; + runAlgorithm(eoEsSimple(), parser, state); } else if (corrParam.value() == false) { - std::cout << "Using eoEsStdev" << std::endl; - runAlgorithm(eoEsStdev(), parser, state); + std::cout << "Using eoEsStdev" << std::endl; + runAlgorithm(eoEsStdev(), parser, state); } else { - std::cout << "Using eoEsFull" << std::endl; - runAlgorithm(eoEsFull(), parser, state); + std::cout << "Using eoEsFull" << std::endl; + runAlgorithm(eoEsFull(), parser, state); } return 0; } @@ -83,11 +83,11 @@ int main(int argc, char **argv) #endif try { - main_function(argc, argv); + main_function(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << '\n'; + std::cout << "Exception: " << e.what() << '\n'; } } diff --git a/eo/test/t-eoESFull.cpp b/eo/test/t-eoESFull.cpp index 7a217b58..7c5e84d9 100644 --- a/eo/test/t-eoESFull.cpp +++ b/eo/test/t-eoESFull.cpp @@ -34,7 +34,7 @@ int main_function(int argc, char *argv[]) // Define Parameters and load them eoValueParam& seed = parser.createParam(static_cast(time(0)), - "seed", "Random number seed"); + "seed", "Random number seed"); eoValueParam& load_name = parser.createParam(string(), "Load","Load a state file",'L'); eoValueParam& save_name = parser.createParam(string(), "Save","Saves a state file",'S'); eoValueParam& stdevs = parser.createParam(false, "Stdev", "Use adaptive mutation rates", 's'); @@ -62,23 +62,23 @@ int main_function(int argc, char *argv[]) // Run the appropriate algorithm if (stdevs.value() == false && corr.value() == false) { - runAlgorithm(eoEsSimple() ,parser, state, bounds, load_name); + runAlgorithm(eoEsSimple() ,parser, state, bounds, load_name); } else if (corr.value() == true) { - runAlgorithm(eoEsFull(),parser, state, bounds, load_name); + runAlgorithm(eoEsFull(),parser, state, bounds, load_name); } else { - runAlgorithm(eoEsStdev(), parser, state, bounds, load_name); + runAlgorithm(eoEsStdev(), parser, state, bounds, load_name); } // and save if (!save_name.value().empty()) { - string file_name = save_name.value(); - save_name.value() = ""; // so that it does not appear in the parser section of the state file - state.save(file_name); + string file_name = save_name.value(); + save_name.value() = ""; // so that it does not appear in the parser section of the state file + state.save(file_name); } return 0; @@ -98,11 +98,11 @@ int main(int argc, char **argv) try { - main_function(argc, argv); + main_function(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << '\n'; + std::cout << "Exception: " << e.what() << '\n'; } return 1; @@ -120,7 +120,7 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _ if (lambda_rate.value() < 1.0f) { - throw logic_error("lambda_rate must be larger than 1 in a comma strategy"); + throw logic_error("lambda_rate must be larger than 1 in a comma strategy"); } // Initialization @@ -137,8 +137,8 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _ } else { - // evaluate initial population - apply(eval, pop); + // evaluate initial population + apply(eval, pop); } // Ok, time to set up the algorithm diff --git a/eo/test/t-eoEasyEA.cpp b/eo/test/t-eoEasyEA.cpp index afda2362..ba3035d2 100644 --- a/eo/test/t-eoEasyEA.cpp +++ b/eo/test/t-eoEasyEA.cpp @@ -16,12 +16,12 @@ main() // a chromosome randomizer eoBinRandom random; -// the populations: - eoPop pop; +// the populations: + eoPop pop; // Evaluation eoEvalFuncPtr eval( binary_value ); - + for (i = 0; i < POP_SIZE; ++i) { Chrom chrom(CHROM_SIZE); @@ -29,12 +29,12 @@ main() eval(chrom); pop.push_back(chrom); } - + std::cout << "population:" << std::endl; for (i = 0; i < pop.size(); ++i) std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; - + // selection eoLottery lottery; @@ -45,7 +45,7 @@ main() eoBreeder breeder( propSel ); propSel.addOp(bitflip, 0.25); propSel.addOp(xover, 0.75); - + // replacement eoInclusion inclusion; @@ -65,11 +65,10 @@ main() std::cout << "exception: " << e.what() << std::endl;; exit(EXIT_FAILURE); } - + std::cout << "pop" << std::endl; for (i = 0; i < pop.size(); ++i) std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; - + return 0; } - diff --git a/eo/test/t-eoEasyPSO.cpp b/eo/test/t-eoEasyPSO.cpp index 96e5b004..af290e13 100644 --- a/eo/test/t-eoEasyPSO.cpp +++ b/eo/test/t-eoEasyPSO.cpp @@ -19,7 +19,7 @@ double real_value (const Particle & _particle) { double sum = 0; for (unsigned i = 0; i < _particle.size ()-1; i++) - sum += pow(_particle[i],2); + sum += pow(_particle[i],2); return (sum); } @@ -50,15 +50,15 @@ int main() // perform position initialization pop.append (POP_SIZE, random); - + // topology eoLinearTopology topology(NEIGHBORHOOD_SIZE); // the full initializer eoInitializer init(eval,veloRandom,localInit,topology,pop); init(); - - + + // bounds eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5); @@ -71,33 +71,32 @@ int main() // Terminators eoGenContinue genCont1 (50); eoGenContinue genCont2 (50); - + // PS flight eoEasyPSO pso1(genCont1, eval, velocity, flight); eoEasyPSO pso2(init,genCont2, eval, velocity, flight); - + // flight try { - pso1(pop); - std::cout << "FINAL POPULATION AFTER PSO n°1:" << std::endl; + pso1(pop); + std::cout << "FINAL POPULATION AFTER PSO n°1:" << std::endl; for (i = 0; i < pop.size(); ++i) - std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; - - pso2(pop); - std::cout << "FINAL POPULATION AFTER PSO n°2:" << std::endl; + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + + pso2(pop); + std::cout << "FINAL POPULATION AFTER PSO n°2:" << std::endl; for (i = 0; i < pop.size(); ++i) - std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; } catch (std::exception& e) { - std::cout << "exception: " << e.what() << std::endl;; - exit(EXIT_FAILURE); + std::cout << "exception: " << e.what() << std::endl;; + exit(EXIT_FAILURE); } - + return 0; } - diff --git a/eo/test/t-eoExtendedVelocity.cpp b/eo/test/t-eoExtendedVelocity.cpp index c42fb4c6..3fca3f30 100644 --- a/eo/test/t-eoExtendedVelocity.cpp +++ b/eo/test/t-eoExtendedVelocity.cpp @@ -66,11 +66,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << " in t-eoExtendedVelocity" << std::endl; + std::cout << "Exception: " << e.what() << " in t-eoExtendedVelocity" << std::endl; } return EXIT_SUCCESS; } diff --git a/eo/test/t-eoExternalEO.cpp b/eo/test/t-eoExternalEO.cpp index aae16985..8246863f 100644 --- a/eo/test/t-eoExternalEO.cpp +++ b/eo/test/t-eoExternalEO.cpp @@ -4,7 +4,7 @@ #endif #include -#include // runtime_error +#include // runtime_error #include #include @@ -61,9 +61,9 @@ bool UserDefMutate(UserDefStruct& a) a = RandomStruct(); // just for testing if (rng.flip(0.1f)) - a.d = UserDefStruct::test; + a.d = UserDefStruct::test; else - a.d = UserDefStruct::another; + a.d = UserDefStruct::another; return true; } @@ -72,13 +72,13 @@ bool UserDefBinCrossover(UserDefStruct& a, const UserDefStruct& b) std::cout << "UserDefBinCrossover\n"; if (rng.flip(0.5)) - a.a = b.a; + a.a = b.a; if (rng.flip(0.5)) - a.b = b.b; + a.b = b.b; if (rng.flip(0.5)) - a.c = b.c; + a.c = b.c; if (rng.flip(0.5)) - a.d = b.d; + a.d = b.d; return true; } @@ -86,13 +86,13 @@ bool UserDefQuadCrossover(UserDefStruct& a, UserDefStruct& b) { std::cout << "UserDefQuadCrossover\n"; if (rng.flip(0.5)) - swap(a.a, b.a); + swap(a.a, b.a); if (rng.flip(0.5)) - swap(a.b, b.b); + swap(a.b, b.b); if (rng.flip(0.5)) - swap(a.c, b.c); + swap(a.c, b.c); if (rng.flip(0.5)) - swap(a.d, b.d); + swap(a.d, b.d); return true; } diff --git a/eo/test/t-eoFitnessAssembled.cpp b/eo/test/t-eoFitnessAssembled.cpp index 5a492aed..018d739a 100644 --- a/eo/test/t-eoFitnessAssembled.cpp +++ b/eo/test/t-eoFitnessAssembled.cpp @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // t-eoFitnessAssembled.cpp // Marc Wintermantel & Oliver Koenig @@ -11,19 +11,19 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es - Marc.Schoenauer@inria.fr - mak@dhi.dk + Marc.Schoenauer@inria.fr + mak@dhi.dk */ //----------------------------------------------------------------------------- #include @@ -32,7 +32,7 @@ #include "eoScalarFitnessAssembled.h" void test_eoScalarFitnessAssembledClass(){ - + // Create instances eoAssembledMinimizingFitness A,B,C(5, 1.3, "C value"); @@ -53,9 +53,9 @@ void test_eoScalarFitnessAssembledClass(){ std::cout << "C= " << C << std::endl; std::cout << "Printing values and descriptions: " << std::endl; std::cout << "A: "; A.printAll( std::cout ); std::cout << std::endl; - std::cout << "B: "; B.printAll( std::cout ); std::cout << std::endl; + std::cout << "B: "; B.printAll( std::cout ); std::cout << std::endl; std::cout << "C: "; C.printAll( std::cout ); std::cout << std::endl; - + A.resize(8, 100.3, "A resized"); std::cout << "Resized A: "; A.printAll( std::cout ); std::cout << std::endl; @@ -68,7 +68,7 @@ void test_eoScalarFitnessAssembledClass(){ F=A; G= 7.5; std::cout << "F = A : " << F << "\t G = 7.5 : " << G << std::endl; - + // Comparing... std::cout << "AB: " << (A>B) << std::endl; @@ -80,15 +80,15 @@ void test_eoScalarFitnessAssembledClass(){ int main(){ - + std::cout << "-----------------------------------" << std::endl; std::cout << "START t-eoFitnessAssembled" << std::endl; try{ // Test the fitness class itself test_eoScalarFitnessAssembledClass(); - - + + } catch(std::exception& e){ @@ -102,4 +102,3 @@ int main(){ return 0; } - diff --git a/eo/test/t-eoFitnessAssembledEA.cpp b/eo/test/t-eoFitnessAssembledEA.cpp index 6369ac57..e0453567 100644 --- a/eo/test/t-eoFitnessAssembledEA.cpp +++ b/eo/test/t-eoFitnessAssembledEA.cpp @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // t-eoFitnessAssembledEA.cpp // Marc Wintermantel & Oliver Koenig @@ -11,19 +11,19 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es - Marc.Schoenauer@inria.fr - mak@dhi.dk + Marc.Schoenauer@inria.fr + mak@dhi.dk */ //----------------------------------------------------------------------------- #ifdef HAVE_CONFIG_H @@ -41,7 +41,7 @@ #include // Definition of representation #include // Uniformly initializes real vector in bounds #include // Initialization of a genotype -#include // Base class for fitness evaluation +#include // Base class for fitness evaluation #include // Variation operators using standard Real operators #include // The fitness class typedef eoReal Indi; @@ -51,7 +51,7 @@ typedef eoReal Indi; #include // The stopping criterion #include // Outputs (stats, population dumps, ...) #include // Evolution engine (selection and replacement) -#include // simple call to the algo.stays there for consistency reasons +#include // simple call to the algo.stays there for consistency reasons // Define a fitness class template @@ -59,9 +59,9 @@ class eoAssembledEvalFunc : public eoEvalFunc{ public: // Constructor defining number and descriptions of fitness terms eoAssembledEvalFunc() { - + // Define a temporary fitness object to have access to its static traits - typename EOT::Fitness tmpfit(3, 0.0); + typename EOT::Fitness tmpfit(3, 0.0); tmpfit.setDescription(0,"Fitness"); tmpfit.setDescription(1,"Some Value"); tmpfit.setDescription(2,"Other Value"); @@ -70,27 +70,27 @@ public: void operator()(EOT& _eo){ - // Define temporary fitness object + // Define temporary fitness object // (automatically gets initialized with size given in constructor) typename EOT::Fitness tmpfit; - + // Eval some dummy fitness double sum1=0.0, sum2=0.0; for (unsigned i=0; i < _eo.size(); ++i){ sum1 += _eo[i]*_eo[i]; sum2 += fabs(_eo[i]) + fabs(_eo[i]); } - + // Store some fitness terms tmpfit[1]= sum1; tmpfit[2]= sum2; - + // Store the fitness tmpfit = (sum1 + sum2)/_eo.size(); // Pass it _eo.fitness( tmpfit ); - + } }; @@ -99,14 +99,14 @@ void make_help(eoParser & _parser); // now use all of the above, + representation dependent things int main(int argc, char* argv[]){ - + std::cout << "-----------------------------------" << std::endl; std::cout << "START t-eoFitnessAssembledEA" << std::endl; try{ // Parser & State - eoParser parser(argc, argv); // for user-parameter reading + eoParser parser(argc, argv); // for user-parameter reading eoState state; // keeps all things allocated //// @@ -120,7 +120,7 @@ int main(int argc, char* argv[]){ // The genotype eoRealInitBounded& init = do_make_genotype(parser, state, Indi() ); - + // The variation operators eoGenOp& op = do_make_op(parser, state, init); @@ -158,7 +158,7 @@ int main(int argc, char* argv[]){ std::cout << "Final Population\n"; pop.sortedPrintOn(std::cout); std::cout << std::endl; - + } catch(std::exception& e) { diff --git a/eo/test/t-eoFunctor.cpp b/eo/test/t-eoFunctor.cpp index b0bf5249..f309eebc 100644 --- a/eo/test/t-eoFunctor.cpp +++ b/eo/test/t-eoFunctor.cpp @@ -1,4 +1,3 @@ - #include #include @@ -13,7 +12,7 @@ class Tester : public eoInit public : void operator()(int& i) { - i=1; + i=1; } }; diff --git a/eo/test/t-eoGA.cpp b/eo/test/t-eoGA.cpp index effac3b0..fafed297 100644 --- a/eo/test/t-eoGA.cpp +++ b/eo/test/t-eoGA.cpp @@ -21,7 +21,7 @@ int main(int argc, char* argv[]) ///// FIRST, problem or representation dependent stuff ////////////////////////////////////////////////////// - // The evaluation fn - encapsulated into an eval counter for output + // The evaluation fn - encapsulated into an eval counter for output eoEvalFuncPtr mainEval( binary_value ); eoEvalFuncCounter eval(mainEval); diff --git a/eo/test/t-eoGenOp.cpp b/eo/test/t-eoGenOp.cpp index 910474f9..c959a3bb 100644 --- a/eo/test/t-eoGenOp.cpp +++ b/eo/test/t-eoGenOp.cpp @@ -19,7 +19,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: mkeijzer@dhi.dk - Marc.Schoenauer@polytechnique.fr + Marc.Schoenauer@polytechnique.fr */ //----------------------------------------------------------------------------- @@ -38,10 +38,10 @@ struct Dummy : public EO Dummy(std::string _s="") : s(_s) {} void printOn(std::ostream & _os) const - { - EO::printOn(_os); - _os << " - " << s ; - } + { + EO::printOn(_os); + _os << " - " << s ; + } std::string s; }; @@ -179,9 +179,9 @@ void init(eoPop & _pop, unsigned _pSize) for (unsigned i=0; i<_pSize; i++) { std::ostringstream os; - os << i; - _pop[i] = Dummy(os.str()); - _pop[i].fitness(i); + os << i; + _pop[i] = Dummy(os.str()); + _pop[i].fitness(i); } } @@ -190,7 +190,7 @@ int the_main(int argc, char **argv) { eoParser parser(argc, argv); eoValueParam parentSizeParam( - parser.createParam(unsigned(10), "parentSize", "Parent size",'P')); + parser.createParam(unsigned(10), "parentSize", "Parent size",'P')); pSize = parentSizeParam.value(); // global variable eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); @@ -201,8 +201,8 @@ int the_main(int argc, char **argv) // i.e. in case you need parameters somewhere else, postpone these if (parser.userNeedsHelp()) { - parser.printHelp(std::cout); - exit(1); + parser.printHelp(std::cout); + exit(1); } ////////////////////////////////// define operators @@ -379,11 +379,11 @@ int main(int argc, char **argv) { try { - the_main(argc, argv); + the_main(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << std::endl; + std::cout << "Exception: " << e.what() << std::endl; } } diff --git a/eo/test/t-eoIQRStat.cpp b/eo/test/t-eoIQRStat.cpp index 60bcff8f..e49dc38d 100644 --- a/eo/test/t-eoIQRStat.cpp +++ b/eo/test/t-eoIQRStat.cpp @@ -1,4 +1,3 @@ - #include #include #include @@ -39,7 +38,7 @@ int main() pop.push_back( sol4 ); // on the sphere function everyone has the same fitness of 1 if( test(pop, 0) != 0 ) { - exit(1); + exit(1); } pop.erase(pop.begin(),pop.end()); @@ -54,7 +53,7 @@ int main() pop.push_back( sol3 ); pop.push_back( sol4 ); if( test(pop, 1) != 1 ) { - exit(1); + exit(1); } // test on a random normal distribution @@ -63,7 +62,6 @@ int main() pop = eoPop( 1000000, init_N ); double iqr = test(pop, 1.09); if( iqr < 1.08 || iqr > 1.11 ) { - exit(1); + exit(1); } } - diff --git a/eo/test/t-eoInitPermutation.cpp b/eo/test/t-eoInitPermutation.cpp index 4090128b..e4a683b1 100644 --- a/eo/test/t-eoInitPermutation.cpp +++ b/eo/test/t-eoInitPermutation.cpp @@ -32,9 +32,9 @@ bool check_permutation(const Chrom & _chrom) std::cout << " Error: Wrong permutation !" << std::endl; std::string s; s.append( " Wrong permutation in t-eoInitPermutation"); - throw std::runtime_error( s ); + throw std::runtime_error( s ); } - return true; + return true; } int main() @@ -44,13 +44,13 @@ int main() // a chromosome randomizer eoInitPermutation random(CHROM_SIZE); - - // the population: + + // the population: eoPop pop; - + // Evaluation eoEvalFuncPtr eval( real_value ); - + for (i = 0; i < POP_SIZE; ++i) { Chrom chrom(CHROM_SIZE); @@ -61,7 +61,7 @@ int main() check_permutation(chrom); pop.push_back(chrom); } - + return 0; } diff --git a/eo/test/t-eoOrderXover.cpp b/eo/test/t-eoOrderXover.cpp index f44b8c69..32e44dad 100644 --- a/eo/test/t-eoOrderXover.cpp +++ b/eo/test/t-eoOrderXover.cpp @@ -38,13 +38,13 @@ int main() // a chromosome randomizer eoInitPermutation random(CHROM_SIZE); - - // the population: + + // the population: eoPop pop; - + // Evaluation //eoEvalFuncPtr eval( real_value ); - + for (i = 0; i < POP_SIZE; ++i) { Chrom chrom(CHROM_SIZE); @@ -52,18 +52,18 @@ int main() //eval(chrom); pop.push_back(chrom); } - + // a shift mutation eoOrderXover cross; - + for (i = 0; i < POP_SIZE; ++i) std::cout << " Initial chromosome n�" << i << " : " << pop[i] << "..." << std::endl; cross(pop[0],pop[1]); cross(pop[1],pop[2]); - + for (i = 0; i < POP_SIZE; ++i) { - std::cout << " Initial chromosome n�" << i << " becomes : " << pop[i] << " after orderXover" << std::endl; + std::cout << " Initial chromosome n�" << i << " becomes : " << pop[i] << " after orderXover" << std::endl; check_permutation(pop[i]); } return 0; diff --git a/eo/test/t-eoPBIL.cpp b/eo/test/t-eoPBIL.cpp index adba787f..1d2654b8 100644 --- a/eo/test/t-eoPBIL.cpp +++ b/eo/test/t-eoPBIL.cpp @@ -98,14 +98,14 @@ int main(int argc, char* argv[]) // now create the snapshot monitor eoValueParam& plotDistribParam = parser.getORcreateParam(false, "plotDistrib", - "Plot Distribution", '\0', - "Output - Graphical"); + "Plot Distribution", '\0', + "Output - Graphical"); if (plotDistribParam.value()) { #ifdef HAVE_GNUPLOT unsigned frequency=1; // frequency of plots updates eoGnuplot1DSnapshot *distribSnapshot = new eoGnuplot1DSnapshot(ptDirNameParam->value(), - frequency, "distrib"); + frequency, "distrib"); state.storeFunctor(distribSnapshot); // add the distribution (it is an eoValueParam >) distribSnapshot->add(distrib); @@ -117,7 +117,7 @@ int main(int argc, char* argv[]) // the algorithm: EDA // don't know where else to put the population size! unsigned popSize = parser.getORcreateParam(unsigned(100), "popSize", - "Population Size", 'P', "Algorithm").value(); + "Population Size", 'P', "Algorithm").value(); eoSimpleEDA eda(update, eval, popSize, checkpoint); ///// End of construction of the algorith diff --git a/eo/test/t-eoRNG.cpp b/eo/test/t-eoRNG.cpp index 4ff94170..1ece31a0 100644 --- a/eo/test/t-eoRNG.cpp +++ b/eo/test/t-eoRNG.cpp @@ -24,21 +24,21 @@ int main() double sigma(5.); double sum(0.); for(size_t i=0; i sigma / 0.68) { - cerr << "Normal distribution seems out of bounds; " - << "rerun to make sure it wasn't a statistical outlier" << endl; - return -1; + cerr << "Normal distribution seems out of bounds; " + << "rerun to make sure it wasn't a statistical outlier" << endl; + return -1; } sum = 0.; for(size_t i=0; i sigma / 0.68) { - cerr << "Normal distribution seems out of bounds; " - << "rerun to make sure it wasn't a statistical outlier" << endl; - return -1; + cerr << "Normal distribution seems out of bounds; " + << "rerun to make sure it wasn't a statistical outlier" << endl; + return -1; } return 0; } diff --git a/eo/test/t-eoReal.cpp b/eo/test/t-eoReal.cpp index 851e1982..163b0ea8 100644 --- a/eo/test/t-eoReal.cpp +++ b/eo/test/t-eoReal.cpp @@ -20,9 +20,9 @@ int main(int argc, char* argv[]) ///// FIRST, problem or representation dependent stuff ////////////////////////////////////////////////////// - // The evaluation fn - encapsulated into an eval counter for output - eoEvalFuncPtr&> - mainEval( real_value ); + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + mainEval( real_value ); eoEvalFuncCounter eval(mainEval); // the genotype - through a genotype initializer diff --git a/eo/test/t-eoReplacement.cpp b/eo/test/t-eoReplacement.cpp index a0f02406..fc44543d 100644 --- a/eo/test/t-eoReplacement.cpp +++ b/eo/test/t-eoReplacement.cpp @@ -5,10 +5,10 @@ #pragma warning(disable:4786) #endif -#include // runtime_error +#include // runtime_error //----------------------------------------------------------------------------- -// tt.cpp: +// tt.cpp: // //----------------------------------------------------------------------------- @@ -37,7 +37,7 @@ public : //----------------------------------------------------------------------------- int the_main(int argc, char **argv) -{ +{ eoParser parser(argc, argv); eoValueParam parentSizeParam(10, "parentSize", "Parent size",'P'); parser.processParam( parentSizeParam ); @@ -73,13 +73,13 @@ int the_main(int argc, char **argv) if (parser.userNeedsHelp()) { - parser.printHelp(std::cout); - exit(1); + parser.printHelp(std::cout); + exit(1); } unsigned i; - std::cout << "Testing the replacements\nParents SIze = " << pSize + std::cout << "Testing the replacements\nParents SIze = " << pSize << " and offspring size = " << oSize << std::endl; rng.reseed(42); @@ -213,11 +213,11 @@ int main(int argc, char **argv) { try { - the_main(argc, argv); + the_main(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << std::endl; + std::cout << "Exception: " << e.what() << std::endl; } } diff --git a/eo/test/t-eoRingTopology.cpp b/eo/test/t-eoRingTopology.cpp index e7d7488d..de2824c2 100644 --- a/eo/test/t-eoRingTopology.cpp +++ b/eo/test/t-eoRingTopology.cpp @@ -19,15 +19,15 @@ double f (const Indi & _indi) int main_function(int argc, char **argv) { //Parameters - const unsigned int VEC_SIZE = 2; - const unsigned int POP_SIZE = 10; - const unsigned int NEIGHBORHOOD_SIZE= 3; + const unsigned int VEC_SIZE = 2; + const unsigned int POP_SIZE = 10; + const unsigned int NEIGHBORHOOD_SIZE= 3; rng.reseed (33); eoEvalFuncPtr plainEval(f); eoEvalFuncCounter < Indi > eval (plainEval); eoUniformGenerator < double >uGen (0., 5.); - eoInitFixedLength < Indi > random (VEC_SIZE, uGen); + eoInitFixedLength < Indi > random (VEC_SIZE, uGen); eoUniformGenerator < double >sGen (-1., 1.); eoVelocityInitFixedLength < Indi > veloRandom (VEC_SIZE, sGen); eoFirstIsBestInit < Indi > localInit; @@ -57,11 +57,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << " in t-eoRingTopology" << std::endl; + std::cout << "Exception: " << e.what() << " in t-eoRingTopology" << std::endl; } } diff --git a/eo/test/t-eoRoulette.cpp b/eo/test/t-eoRoulette.cpp index 5c350122..d6f63b8a 100644 --- a/eo/test/t-eoRoulette.cpp +++ b/eo/test/t-eoRoulette.cpp @@ -1,4 +1,3 @@ - #include #include #include @@ -29,22 +28,22 @@ int test_select() } Select select; - + unsigned ndraws = 10000; - + for (unsigned i = 0; i < ndraws; ++i) { const TestEO& eo = select(pop); - + counts[eo.index]++; } cout << "Threshold = " << 1./sqrt(double(ndraws)) << endl; - + for (unsigned i = 0; i < 4; ++i) { cout << counts[i]/ndraws << ' '; - + double c = counts[i]/ndraws; if (fabs(c - probs[i]) > 1./sqrt((double)ndraws)) { @@ -52,7 +51,7 @@ int test_select() return 1; } } - + cout << endl; return 0; } @@ -62,7 +61,6 @@ int main() rng.reseed(44); if (test_select >()) return 1; - + return test_select >(); } - diff --git a/eo/test/t-eoSecondsElapsedContinue.cpp b/eo/test/t-eoSecondsElapsedContinue.cpp index e6e59a61..d6124c22 100644 --- a/eo/test/t-eoSecondsElapsedContinue.cpp +++ b/eo/test/t-eoSecondsElapsedContinue.cpp @@ -1,4 +1,3 @@ - #ifdef HAVE_CONFIG_H #include #endif @@ -29,5 +28,3 @@ int main() { return 0; } - - diff --git a/eo/test/t-eoSelect.cpp b/eo/test/t-eoSelect.cpp index d62e5ade..23d76c48 100644 --- a/eo/test/t-eoSelect.cpp +++ b/eo/test/t-eoSelect.cpp @@ -121,8 +121,8 @@ eoValueParam tournamentSizeParam = parser.createParam(unsigned(2), "to if (parser.userNeedsHelp()) { - parser.printHelp(std::cout); - exit(0); + parser.printHelp(std::cout); + exit(0); } // hard-coded directory name ... @@ -155,7 +155,7 @@ eoValueParam tournamentSizeParam = parser.createParam(unsigned(2), "to // random seed eoValueParam& seedParam = parser.createParam(uint32_t(0), "seed", - "Random number seed", 'S'); + "Random number seed", 'S'); if (seedParam.value() == 0) seedParam.value() = time(0); rng.reseed(seedParam.value()); @@ -212,11 +212,11 @@ int main(int argc, char **argv) { try { - the_main(argc, argv); + the_main(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << std::endl; - return 1; + std::cout << "Exception: " << e.what() << std::endl; + return 1; } } diff --git a/eo/test/t-eoSharing.cpp b/eo/test/t-eoSharing.cpp index a68820be..86721b09 100644 --- a/eo/test/t-eoSharing.cpp +++ b/eo/test/t-eoSharing.cpp @@ -230,11 +230,11 @@ int main(int argc, char **argv) { try { - the_main(argc, argv); + the_main(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << std::endl; - return 1; + std::cout << "Exception: " << e.what() << std::endl; + return 1; } } diff --git a/eo/test/t-eoShiftMutation.cpp b/eo/test/t-eoShiftMutation.cpp index afc27749..15c4e6b9 100644 --- a/eo/test/t-eoShiftMutation.cpp +++ b/eo/test/t-eoShiftMutation.cpp @@ -47,13 +47,13 @@ int main() // a chromosome randomizer eoInitPermutation random(CHROM_SIZE); - - // the population: + + // the population: eoPop pop; - + // Evaluation eoEvalFuncPtr eval( real_value ); - + for (i = 0; i < POP_SIZE; ++i) { Chrom chrom(CHROM_SIZE); @@ -61,10 +61,10 @@ int main() eval(chrom); pop.push_back(chrom); } - + // a shift mutation eoShiftMutation shift; - + for (i = 0; i < POP_SIZE; ++i) { std::cout << " Initial chromosome n°" << i << " : " << pop[i] << "..." << std::endl; @@ -72,7 +72,7 @@ int main() std::cout << " ... becomes : " << pop[i] << " after shift mutation" << std::endl; check_permutation(pop[i]); } - + return 0; } diff --git a/eo/test/t-eoStateAndParser.cpp b/eo/test/t-eoStateAndParser.cpp index 80551279..a851cb59 100644 --- a/eo/test/t-eoStateAndParser.cpp +++ b/eo/test/t-eoStateAndParser.cpp @@ -89,22 +89,22 @@ int the_main(int argc, char **argv) if (parser.userNeedsHelp()) { - parser.printHelp(std::cout); - return 0; + parser.printHelp(std::cout); + return 0; } // Either load or initialize if (load_name.value() != "") { - state.load(load_name.value()); // load the rest + state.load(load_name.value()); // load the rest } else { - // else + // else - // initialize rng and population + // initialize rng and population - rng.reseed(seed.value()); + rng.reseed(seed.value()); } // run the algorithm @@ -112,13 +112,13 @@ int the_main(int argc, char **argv) // Save when needed if (save_name.value() != "") { - std::string file_name = save_name.value(); - save_name.value() = ""; // so that it does not appear in the parser section of the state file - state.save(file_name); + std::string file_name = save_name.value(); + save_name.value() = ""; // so that it does not appear in the parser section of the state file + state.save(file_name); } for (int i = 0; i < 100; ++i) - rng.rand(); + rng.rand(); std::cout << "a random number is " << rng.random(1024) << std::endl;; @@ -129,11 +129,11 @@ int main(int argc, char **argv) { try { - the_main(argc, argv); + the_main(argc, argv); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << std::endl; + std::cout << "Exception: " << e.what() << std::endl; } } diff --git a/eo/test/t-eoSwapMutation.cpp b/eo/test/t-eoSwapMutation.cpp index f2c33789..3099d707 100644 --- a/eo/test/t-eoSwapMutation.cpp +++ b/eo/test/t-eoSwapMutation.cpp @@ -48,13 +48,13 @@ int main() // a chromosome randomizer eoInitPermutation random(CHROM_SIZE); - - // the population: + + // the population: eoPop pop; - + // Evaluation eoEvalFuncPtr eval( real_value ); - + for (i = 0; i < POP_SIZE; ++i) { Chrom chrom(CHROM_SIZE); @@ -62,11 +62,11 @@ int main() eval(chrom); pop.push_back(chrom); } - - + + // a swap mutation eoSwapMutation swap; - + for (i = 0; i < POP_SIZE; ++i) { std::cout << " Initial chromosome n°" << i << " : " << pop[i] << "..." << std::endl; @@ -74,7 +74,7 @@ int main() std::cout << " ... becomes : " << pop[i] << " after swap mutation" << std::endl; check_permutation(pop[i]); } - + return 0; } diff --git a/eo/test/t-eoSymreg.cpp b/eo/test/t-eoSymreg.cpp index f9aebd06..d332789b 100644 --- a/eo/test/t-eoSymreg.cpp +++ b/eo/test/t-eoSymreg.cpp @@ -23,57 +23,57 @@ public : // arity function, need this function! int arity() const { return op == X? 0 : 2; } - void randomize() {} + void randomize() {} // evaluation function, single case, using first argument to give value of variable template void operator()(double& result, Children args, double var) const { - double r1(0.), r2(0.); - if (arity() == 2) - { - args[0].apply(r1, var); - args[1].apply(r2, var); - } - switch (op) - { - case Plus : result = r1 + r2; break; - case Min : result = r1 - r2; break; - case Mult : result = r1 * r2; break; - case PDiv : { - if (r2 == 0.0) - // protection a la Koza, realistic implementations - // should maybe throw an exception - result = 1.0; - else - result = r1 / r2; - break; - } - case X : result = var; break; - } + double r1(0.), r2(0.); + if (arity() == 2) + { + args[0].apply(r1, var); + args[1].apply(r2, var); + } + switch (op) + { + case Plus : result = r1 + r2; break; + case Min : result = r1 - r2; break; + case Mult : result = r1 * r2; break; + case PDiv : { + if (r2 == 0.0) + // protection a la Koza, realistic implementations + // should maybe throw an exception + result = 1.0; + else + result = r1 / r2; + break; + } + case X : result = var; break; + } } /// 'Pretty' print to ostream function template - void operator()(string& result, Children args) const + void operator()(string& result, Children args) const { - static const string lb = "("; - static const string rb = ")"; - char opStr[4] = " "; - opStr[1] = op; + static const string lb = "("; + static const string rb = ")"; + char opStr[4] = " "; + opStr[1] = op; if (arity() == 0) { - result = "x"; - return; - } - // else - string r1; - args[0].apply(r1); - result = lb + r1; - result += opStr; - args[1].apply(r1); - result += r1 + rb; + result = "x"; + return; + } + // else + string r1; + args[0].apply(r1); + result = lb + r1; + result += opStr; + args[1].apply(r1); + result += r1 + rb; } Operator getOp() const { return op; } @@ -99,7 +99,7 @@ static SymregNode init_sequence[5] = {SymregNode::X, SymregNode::Plus, SymregNod // template <> // bool lt_arity(const SymregNode &node1, const SymregNode &node2) // { -// return (node1.arity() < node2.arity()); +// return (node1.arity() < node2.arity()); // } // #endif @@ -166,16 +166,16 @@ public : vector outputs; outputs.resize(inputs.size()); - double fitness = 0.0; + double fitness = 0.0; for (unsigned i = 0; i < inputs.size(); ++i) - { + { _eo.apply(outputs[i], inputs[i]); - fitness += (outputs[i] - target[i]) * (outputs[i] - target[i]); - } + fitness += (outputs[i] - target[i]) * (outputs[i] - target[i]); + } - fitness /= (double) target.size(); - fitness = sqrt(fitness); + fitness /= (double) target.size(); + fitness = sqrt(fitness); if (fitness > 1e+20) fitness = 1e+20; @@ -197,11 +197,11 @@ void print_best(eoPop& pop) for (unsigned i = 1; i < pop.size(); ++i) { - if (best < pop[i].fitness()) - { - best = pop[i].fitness(); - index = i; - } + if (best < pop[i].fitness()) + { + best = pop[i].fitness(); + index = i; + } } std::cout << "\t"; diff --git a/eo/test/t-eoSyncEasyPSO.cpp b/eo/test/t-eoSyncEasyPSO.cpp index f9acba24..68d9838b 100644 --- a/eo/test/t-eoSyncEasyPSO.cpp +++ b/eo/test/t-eoSyncEasyPSO.cpp @@ -19,7 +19,7 @@ double real_value (const Particle & _particle) { double sum = 0; for (unsigned i = 0; i < _particle.size ()-1; i++) - sum += pow(_particle[i],2); + sum += pow(_particle[i],2); return (sum); } @@ -50,15 +50,15 @@ int main() // perform position initialization pop.append (POP_SIZE, random); - + // topology eoLinearTopology topology(NEIGHBORHOOD_SIZE); // the full initializer eoInitializer init(eval,veloRandom,localInit,topology,pop); init(); - - + + // bounds eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5); @@ -71,32 +71,32 @@ int main() // Terminators eoGenContinue genCont1 (50); eoGenContinue genCont2 (50); - + // PS flight eoSyncEasyPSO pso1(genCont1, eval, velocity, flight); eoSyncEasyPSO pso2(init,genCont2, eval, velocity, flight); - + // flight try { - pso1(pop); - std::cout << "FINAL POPULATION AFTER SYNC PSO n°1:" << std::endl; + pso1(pop); + std::cout << "FINAL POPULATION AFTER SYNC PSO n°1:" << std::endl; for (i = 0; i < pop.size(); ++i) - std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; - - pso2(pop); - std::cout << "FINAL POPULATION AFTER SYNC PSO n°2:" << std::endl; + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + + pso2(pop); + std::cout << "FINAL POPULATION AFTER SYNC PSO n°2:" << std::endl; for (i = 0; i < pop.size(); ++i) - std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; } catch (std::exception& e) { - std::cout << "exception: " << e.what() << std::endl;; - exit(EXIT_FAILURE); + std::cout << "exception: " << e.what() << std::endl;; + exit(EXIT_FAILURE); } - + return 0; } diff --git a/eo/test/t-eoTwoOptMutation.cpp b/eo/test/t-eoTwoOptMutation.cpp index 95e713a6..60ef89a1 100644 --- a/eo/test/t-eoTwoOptMutation.cpp +++ b/eo/test/t-eoTwoOptMutation.cpp @@ -48,13 +48,13 @@ int main() // a chromosome randomizer eoInitPermutation random(CHROM_SIZE); - - // the population: + + // the population: eoPop pop; - + // Evaluation eoEvalFuncPtr eval( real_value ); - + for (i = 0; i < POP_SIZE; ++i) { Chrom chrom(CHROM_SIZE); @@ -62,10 +62,10 @@ int main() eval(chrom); pop.push_back(chrom); } - + // a twoOpt mutation eoTwoOptMutation twoOpt; - + for (i = 0; i < POP_SIZE; ++i) { std::cout << " Initial chromosome n°" << i << " : " << pop[i] << "..." << std::endl; @@ -73,7 +73,7 @@ int main() std::cout << " ... becomes : " << pop[i] << " after twoOpt mutation" << std::endl; check_permutation(pop[i]); } - + return 0; } diff --git a/eo/test/t-eoUniform.cpp b/eo/test/t-eoUniform.cpp index 04c23e5c..c4f188d4 100644 --- a/eo/test/t-eoUniform.cpp +++ b/eo/test/t-eoUniform.cpp @@ -16,7 +16,7 @@ main() { for ( unsigned i = 0; i < 100; i ++) { std::cout << u1() << "\t" << u2() << "\t" << u3() << std::endl; } - + } //----------------------------------------------------------------------------- diff --git a/eo/test/t-eoVirus.cpp b/eo/test/t-eoVirus.cpp index 347a7896..8ecdf207 100644 --- a/eo/test/t-eoVirus.cpp +++ b/eo/test/t-eoVirus.cpp @@ -67,11 +67,10 @@ int main() // Chrom Transmision std::cout << "Chrom transmission--------" << std::endl; - VirusTransmission vt; + VirusTransmission vt; vt( chrom2, chrom ); std::cout << chrom2 << std::endl; return 0; } - diff --git a/eo/test/t-eobin.cpp b/eo/test/t-eobin.cpp index 7c27e001..d857dd82 100644 --- a/eo/test/t-eobin.cpp +++ b/eo/test/t-eobin.cpp @@ -208,11 +208,11 @@ int main() try { - main_function(); + main_function(); } catch(std::exception& e) { - std::cout << "Exception: " << e.what() << '\n'; + std::cout << "Exception: " << e.what() << '\n'; } } diff --git a/eo/test/t-eofitness.cpp b/eo/test/t-eofitness.cpp index 1999e9fd..1cc55e65 100644 --- a/eo/test/t-eofitness.cpp +++ b/eo/test/t-eofitness.cpp @@ -18,11 +18,11 @@ int test_fitness(Fitness a, Fitness b) { // srand(time(0)); -// Fitness a = aval; //static_cast(rand()) / RAND_MAX; +// Fitness a = aval; //static_cast(rand()) / RAND_MAX; // Fitness b = bval; //static_cast(rand()) / RAND_MAX; std::cout.precision(2); - + unsigned repeat = 2; while (repeat--) { @@ -32,25 +32,25 @@ int test_fitness(Fitness a, Fitness b) std::cout << a << " < " << b << " is true" << std::endl; else std::cout << a << " < " << b << " is false" < "; if (a > b) std::cout << a << " > " << b << " is true" << std::endl; else std::cout << a << " > " << b << " is false" < 0 else 1 - iters = ( nonzero( P - p ) / ps ) * ( nonzero( D - d ) / ds ) - pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) - pylab.ylabel('%s - %s' % (cur, name)) - pylab.savefig( filename + '.pdf', format='pdf' ) - pylab.savefig( filename + '.png', format='png' ) - pylab.cla() - pylab.clf() + def generate( filenames ): + for cur in filenames: + filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s) + pylab.boxplot( get_boxplot_data( filename ) ) + nonzero = lambda x: x if x > 0 else 1 + iters = ( nonzero( P - p ) / ps ) * ( nonzero( D - d ) / ds ) + pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) ) + pylab.ylabel('%s - %s' % (cur, name)) + pylab.savefig( filename + '.pdf', format='pdf' ) + pylab.savefig( filename + '.png', format='png' ) + pylab.cla() + pylab.clf() - if not options.onlyVarTime: - generate( ['speedup', 'efficiency', 'dynamicity'] ) - if not options.onlyConstTime: - generate( ['variable_speedup', 'variable_efficiency', 'variable_dynamicity'] ) + if not options.onlyVarTime: + generate( ['speedup', 'efficiency', 'dynamicity'] ) + if not options.onlyConstTime: + generate( ['variable_speedup', 'variable_efficiency', 'variable_dynamicity'] ) def main(): if not options.onlyprint: - logging.info('creates first the new topic repository %s', options.topic) - os.mkdir( options.topic ) + logging.info('creates first the new topic repository %s', options.topic) + os.mkdir( options.topic ) logging.info('do all tests with r = %d and a common seed value = %d' % (options.nRun, options.seed)) @@ -133,24 +133,24 @@ def main(): F = options.fixedBound if options.measure is None or 1 in options.measure: - logging.info('(1) measure for all combinaisons of P n D') - do_measure( '1', 1*n, 10*n, 101*n, 1*n, 10*n, 101*n ) + logging.info('(1) measure for all combinaisons of P n D') + do_measure( '1', 1*n, 10*n, 101*n, 1*n, 10*n, 101*n ) if options.measure is None or 2 in options.measure: - logging.info('(2) measure for P \in [%d, %d[ with D fixed to %d' % (1*n, 101*n, F)) - do_measure( '2', 1*n, 1*n, 101*n, F, 1, F ) + logging.info('(2) measure for P \in [%d, %d[ with D fixed to %d' % (1*n, 101*n, F)) + do_measure( '2', 1*n, 1*n, 101*n, F, 1, F ) if options.measure is None or 3 in options.measure: - logging.info('(3) measure for P \in [%d, %d[ with ps = %d and D fixed to %d' % (1*n, 1001*n, 10*n, F)) - do_measure( '3', 1*n, 10*n, 1001*n, F, 1, F ) + logging.info('(3) measure for P \in [%d, %d[ with ps = %d and D fixed to %d' % (1*n, 1001*n, 10*n, F)) + do_measure( '3', 1*n, 10*n, 1001*n, F, 1, F ) if options.measure is None or 4 in options.measure: - logging.info('(4) measure for D \in [%d, %d[ with P fixed to %d' % (1*n, 101*n, F)) - do_measure( '4', F, 1, F, 1*n, 1*n, 101*n ) + logging.info('(4) measure for D \in [%d, %d[ with P fixed to %d' % (1*n, 101*n, F)) + do_measure( '4', F, 1, F, 1*n, 1*n, 101*n ) if options.measure is None or 5 in options.measure: - logging.info('(5) measure for D \in [%d, %d[ with ds = %d and P fixed to %d' % (1*n, 1001*n, 10*n, F)) - do_measure( '5', F, 1, F, 1*n, 10*n, 1001*n ) + logging.info('(5) measure for D \in [%d, %d[ with ds = %d and P fixed to %d' % (1*n, 1001*n, 10*n, F)) + do_measure( '5', F, 1, F, 1*n, 10*n, 1001*n ) # when executed, just run main(): if __name__ == '__main__': diff --git a/eo/test/t-selectOne.cpp b/eo/test/t-selectOne.cpp index e401188e..0647d5d2 100644 --- a/eo/test/t-selectOne.cpp +++ b/eo/test/t-selectOne.cpp @@ -3,8 +3,8 @@ //----------------------------------------------------------------------------- // t-selectOne.cpp // This program test the breeder object -// (c) GeNeura Team, 1998 -/* +// (c) GeNeura Team, 1998 +/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -20,7 +20,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - + */ //----------------------------------------------------------------------------- @@ -52,7 +52,7 @@ main() unsigned i; eoBinRandom random; - eoPop pop; + eoPop pop; // Create the population for (i = 0; i < POP_SIZE; ++i) { @@ -61,7 +61,7 @@ main() BinaryValue()(chrom); pop.push_back(chrom); } - + // print population std::cout << "population:" << std::endl; for (i = 0; i < pop.size(); ++i) diff --git a/eo/tutorial/Lesson1/CMakeLists.txt b/eo/tutorial/Lesson1/CMakeLists.txt index 614b8421..72862e03 100644 --- a/eo/tutorial/Lesson1/CMakeLists.txt +++ b/eo/tutorial/Lesson1/CMakeLists.txt @@ -10,23 +10,23 @@ INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### ### 3) Define your targets ###################################################################################### # no matter what is the OS, hopefully -ADD_EXECUTABLE(FirstBitGA FirstBitGA.cpp) -ADD_EXECUTABLE(FirstRealGA FirstRealGA.cpp) -ADD_EXECUTABLE(exercise1.3 exercise1.3.cpp) +ADD_EXECUTABLE(FirstBitGA FirstBitGA.cpp) +ADD_EXECUTABLE(FirstRealGA FirstRealGA.cpp) +ADD_EXECUTABLE(exercise1.3 exercise1.3.cpp) ADD_DEPENDENCIES(FirstBitGA ga eo eoutils) ADD_DEPENDENCIES(FirstRealGA ga eo eoutils) diff --git a/eo/tutorial/Lesson1/FirstBitGA.cpp b/eo/tutorial/Lesson1/FirstBitGA.cpp index ac53607a..cc187a81 100644 --- a/eo/tutorial/Lesson1/FirstBitGA.cpp +++ b/eo/tutorial/Lesson1/FirstBitGA.cpp @@ -78,10 +78,10 @@ void main_function(int argc, char **argv) { Indi v; // void individual, to be filled for (unsigned ivar=0; ivar gga(select, xover, CROSS_RATE, mutation, MUT_RATE, - eval, continuator); + eval, continuator); // Apply algo to pop - that's it! gga(pop); @@ -156,11 +156,11 @@ int main(int argc, char **argv) try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson1/FirstRealGA.cpp b/eo/tutorial/Lesson1/FirstRealGA.cpp index 09db59e6..074c5ae8 100644 --- a/eo/tutorial/Lesson1/FirstRealGA.cpp +++ b/eo/tutorial/Lesson1/FirstRealGA.cpp @@ -78,10 +78,10 @@ void main_function(int argc, char **argv) { Indi v; // void individual, to be filled for (unsigned ivar=0; ivar gga(select, xover, CROSS_RATE, mutation, MUT_RATE, - eval, continuator); + eval, continuator); // Apply algo to pop - that's it! gga(pop); @@ -151,11 +151,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson1/Makefile.simple b/eo/tutorial/Lesson1/Makefile.simple index 093ca852..cca13043 100644 --- a/eo/tutorial/Lesson1/Makefile.simple +++ b/eo/tutorial/Lesson1/Makefile.simple @@ -5,11 +5,11 @@ DIR_EO = ../../src .SUFFIXES: .cpp # Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++ -# However, if you are using this Makefile within xemacs, +# However, if you are using this Makefile within xemacs, # and have problems with the interpretation of the output (and its colors) # then you should use c++ instead (make CXX=c++ will do) -.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a .cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp @@ -21,5 +21,5 @@ lesson1 : $(firstGA) all : $(ALL) -clean : +clean : @/bin/rm $(ALL) *.o *~ diff --git a/eo/tutorial/Lesson1/exercise1.3.cpp b/eo/tutorial/Lesson1/exercise1.3.cpp index abd62a0b..89965d51 100644 --- a/eo/tutorial/Lesson1/exercise1.3.cpp +++ b/eo/tutorial/Lesson1/exercise1.3.cpp @@ -18,7 +18,7 @@ //----------------------------------------------------------------------------- // Include the corresponding file -#include // bitstring representation & operators +#include // bitstring representation & operators // define your individuals typedef eoBit Indi; // A bitstring with fitness double @@ -151,11 +151,11 @@ int main(int argc, char **argv) try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson2/CMakeLists.txt b/eo/tutorial/Lesson2/CMakeLists.txt index db3e0e98..23669155 100644 --- a/eo/tutorial/Lesson2/CMakeLists.txt +++ b/eo/tutorial/Lesson2/CMakeLists.txt @@ -10,23 +10,23 @@ INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### ### 3) Define your targets ###################################################################################### # no matter what is the OS, hopefully -ADD_EXECUTABLE(FirstBitEA FirstBitEA.cpp) -ADD_EXECUTABLE(FirstRealEA FirstRealEA.cpp) -ADD_EXECUTABLE(exercise2.3 exercise2.3.cpp) +ADD_EXECUTABLE(FirstBitEA FirstBitEA.cpp) +ADD_EXECUTABLE(FirstRealEA FirstRealEA.cpp) +ADD_EXECUTABLE(exercise2.3 exercise2.3.cpp) ###################################################################################### ### 4) Optionnal diff --git a/eo/tutorial/Lesson2/FirstBitEA.cpp b/eo/tutorial/Lesson2/FirstBitEA.cpp index 13da7895..fd508a55 100644 --- a/eo/tutorial/Lesson2/FirstBitEA.cpp +++ b/eo/tutorial/Lesson2/FirstBitEA.cpp @@ -182,11 +182,11 @@ int main(int argc, char **argv) try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson2/FirstRealEA.cpp b/eo/tutorial/Lesson2/FirstRealEA.cpp index 8901c381..6c259b3b 100644 --- a/eo/tutorial/Lesson2/FirstRealEA.cpp +++ b/eo/tutorial/Lesson2/FirstRealEA.cpp @@ -52,7 +52,7 @@ void main_function(int argc, char **argv) const float P_MUT = 0.5; // mutation probability const double EPSILON = 0.01; // range for real uniform mutation - double SIGMA = 0.3; // std dev. for normal mutation + double SIGMA = 0.3; // std dev. for normal mutation // some parameters for chosing among different operators const double hypercubeRate = 0.5; // relative weight for hypercube Xover const double segmentRate = 0.5; // relative weight for segment Xover @@ -181,11 +181,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson2/Makefile.simple b/eo/tutorial/Lesson2/Makefile.simple index 1aec1710..d5cba225 100644 --- a/eo/tutorial/Lesson2/Makefile.simple +++ b/eo/tutorial/Lesson2/Makefile.simple @@ -1,5 +1,5 @@ ### This Makefile is part of the tutorial of the EO library -# Unlike other Makefiles in EO, it is not using the automake/autoconf +# Unlike other Makefiles in EO, it is not using the automake/autoconf # so that it stays easy to understant (you are in the tutorial, remember!) # MS, Oct. 2002 @@ -10,11 +10,11 @@ DIR_EO = ../../src .SUFFIXES: .cpp # Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++ -# However, if you are using this Makefile within xemacs, +# However, if you are using this Makefile within xemacs, # and have problems with the interpretation of the output (and its colors) # then you should use c++ instead (make CXX=c++ will do) -.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a .cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp @@ -26,7 +26,7 @@ lesson2 : $(firstEA) all : $(ALL) -clean : +clean : @/bin/rm $(ALL) *.o *~ FirstRealEA : real_value.h diff --git a/eo/tutorial/Lesson2/binary_value.h b/eo/tutorial/Lesson2/binary_value.h index f2f5d6ca..66d2823e 100644 --- a/eo/tutorial/Lesson2/binary_value.h +++ b/eo/tutorial/Lesson2/binary_value.h @@ -4,7 +4,7 @@ /** Just a simple function that takes binary value of a chromosome and sets the fitnes. - @param _chrom A binary chromosome + @param _chrom A binary chromosome */ // INIT double binary_value(const std::vector& _chrom) @@ -14,4 +14,3 @@ double binary_value(const std::vector& _chrom) sum += _chrom[i]; return sum; } - diff --git a/eo/tutorial/Lesson2/exercise2.3.cpp b/eo/tutorial/Lesson2/exercise2.3.cpp index dc39e5d9..c1b51aa0 100644 --- a/eo/tutorial/Lesson2/exercise2.3.cpp +++ b/eo/tutorial/Lesson2/exercise2.3.cpp @@ -20,7 +20,7 @@ // REPRESENTATION //----------------------------------------------------------------------------- // Include the corresponding file -#include // bitstring representation & operators +#include // bitstring representation & operators // define your individuals typedef eoBit Indi; // A bitstring with fitness double @@ -186,11 +186,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson2/real_value.h b/eo/tutorial/Lesson2/real_value.h index cc32e633..866e2941 100644 --- a/eo/tutorial/Lesson2/real_value.h +++ b/eo/tutorial/Lesson2/real_value.h @@ -1,8 +1,8 @@ #include //----------------------------------------------------------------------------- -/** Just a simple function that takes an vector and sets the fitnes +/** Just a simple function that takes an vector and sets the fitnes to the sphere function. Please use doubles not float!!! - @param _ind A floatingpoint vector + @param _ind A floatingpoint vector */ // INIT @@ -15,6 +15,3 @@ double real_value(const std::vector& _ind) } return -sum; } - - - diff --git a/eo/tutorial/Lesson3/CMakeLists.txt b/eo/tutorial/Lesson3/CMakeLists.txt index b3e7c0a7..a59f4a63 100644 --- a/eo/tutorial/Lesson3/CMakeLists.txt +++ b/eo/tutorial/Lesson3/CMakeLists.txt @@ -10,23 +10,23 @@ INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### ### 3) Define your targets ###################################################################################### # no matter what is the OS, hopefully -ADD_EXECUTABLE(SecondBitEA SecondBitEA.cpp) -ADD_EXECUTABLE(SecondRealEA SecondRealEA.cpp) -ADD_EXECUTABLE(exercise3.1 exercise3.1.cpp) +ADD_EXECUTABLE(SecondBitEA SecondBitEA.cpp) +ADD_EXECUTABLE(SecondRealEA SecondRealEA.cpp) +ADD_EXECUTABLE(exercise3.1 exercise3.1.cpp) ADD_DEPENDENCIES(SecondBitEA ga eoutils eo) ADD_DEPENDENCIES(SecondRealEA ga eoutils eo) @@ -62,4 +62,3 @@ INSTALL(TARGETS SecondRealEA RUNTIME DESTINATION share/eo/examples/Lesson3 COMPO INSTALL(TARGETS exercise3.1 RUNTIME DESTINATION share/eo/examples/Lesson3 COMPONENT examples) ###################################################################################### - diff --git a/eo/tutorial/Lesson3/Makefile.simple b/eo/tutorial/Lesson3/Makefile.simple index 186791f2..3e63424d 100644 --- a/eo/tutorial/Lesson3/Makefile.simple +++ b/eo/tutorial/Lesson3/Makefile.simple @@ -1,5 +1,5 @@ ### This Makefile is part of the tutorial of the EO library -# Unlike other Makefiles in EO, it is not using the automake/autoconf +# Unlike other Makefiles in EO, it is not using the automake/autoconf # so that it stays easy to understant (you are in the tutorial, remember!) # MS, Oct. 2002 @@ -10,11 +10,11 @@ DIR_EO = ../../src .SUFFIXES: .cpp # Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++ -# However, if you are using this Makefile within xemacs, +# However, if you are using this Makefile within xemacs, # and have problems with the interpretation of the output (and its colors) # then you should use c++ instead (make CXX=c++ will do) -.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a .cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp @@ -29,5 +29,5 @@ all : $(ALL) SecondBitEA : binary_value.h SecondRealEA : real_value.h -clean : +clean : @/bin/rm $(ALL) *.o *.sav *.xg *.status *~ diff --git a/eo/tutorial/Lesson3/SecondBitEA.cpp b/eo/tutorial/Lesson3/SecondBitEA.cpp index 0507bc5c..92e18128 100644 --- a/eo/tutorial/Lesson3/SecondBitEA.cpp +++ b/eo/tutorial/Lesson3/SecondBitEA.cpp @@ -126,8 +126,8 @@ void main_function(int argc, char **argv) // i.e. in case you need parameters somewhere else, postpone these if (parser.userNeedsHelp()) { - parser.printHelp(cout); - exit(1); + parser.printHelp(cout); + exit(1); } if (statusParam.value() != "") { @@ -337,11 +337,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson3/SecondRealEA.cpp b/eo/tutorial/Lesson3/SecondRealEA.cpp index 2ae69fd8..b5ca0c80 100644 --- a/eo/tutorial/Lesson3/SecondRealEA.cpp +++ b/eo/tutorial/Lesson3/SecondRealEA.cpp @@ -104,8 +104,8 @@ void main_function(int argc, char **argv) // i.e. in case you need parameters somewhere else, postpone these if (parser.userNeedsHelp()) { - parser.printHelp(cout); - exit(1); + parser.printHelp(cout); + exit(1); } if (statusName != "") { @@ -318,11 +318,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson3/binary_value.h b/eo/tutorial/Lesson3/binary_value.h index f2f5d6ca..66d2823e 100644 --- a/eo/tutorial/Lesson3/binary_value.h +++ b/eo/tutorial/Lesson3/binary_value.h @@ -4,7 +4,7 @@ /** Just a simple function that takes binary value of a chromosome and sets the fitnes. - @param _chrom A binary chromosome + @param _chrom A binary chromosome */ // INIT double binary_value(const std::vector& _chrom) @@ -14,4 +14,3 @@ double binary_value(const std::vector& _chrom) sum += _chrom[i]; return sum; } - diff --git a/eo/tutorial/Lesson3/exercise3.1.cpp b/eo/tutorial/Lesson3/exercise3.1.cpp index 50531e09..f21e5930 100644 --- a/eo/tutorial/Lesson3/exercise3.1.cpp +++ b/eo/tutorial/Lesson3/exercise3.1.cpp @@ -24,7 +24,7 @@ // REPRESENTATION //----------------------------------------------------------------------------- // Include the corresponding file -#include // bitstring representation & operators +#include // bitstring representation & operators // define your genotype and fitness types typedef eoBit Indi; @@ -126,8 +126,8 @@ void main_function(int argc, char **argv) // i.e. in case you need parameters somewhere else, postpone these if (parser.userNeedsHelp()) { - parser.printHelp(cout); - exit(1); + parser.printHelp(cout); + exit(1); } if (statusParam.value() != "") { @@ -393,11 +393,11 @@ int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson3/real_value.h b/eo/tutorial/Lesson3/real_value.h index 7fe002b6..525bf393 100644 --- a/eo/tutorial/Lesson3/real_value.h +++ b/eo/tutorial/Lesson3/real_value.h @@ -1,8 +1,8 @@ #include //----------------------------------------------------------------------------- -/** Just a simple function that takes an vector and sets the fitnes +/** Just a simple function that takes an vector and sets the fitnes to the sphere function. Please use doubles not float!!! - @param _ind A floatingpoint vector + @param _ind A floatingpoint vector */ // INIT @@ -15,6 +15,3 @@ double real_value(const std::vector& _ind) } return sum; } - - - diff --git a/eo/tutorial/Lesson4/BitEA.cpp b/eo/tutorial/Lesson4/BitEA.cpp index fd6f1fbd..97a6cc43 100644 --- a/eo/tutorial/Lesson4/BitEA.cpp +++ b/eo/tutorial/Lesson4/BitEA.cpp @@ -10,7 +10,7 @@ using namespace std; int main(int argc, char* argv[]) -{ +{ try { @@ -29,7 +29,7 @@ int main(int argc, char* argv[]) ////////////////////////////////////////////////////// // EVAL - // The evaluation fn - encapsulated into an eval counter for output + // The evaluation fn - encapsulated into an eval counter for output eoEvalFuncPtr mainEval( binary_value ); eoEvalFuncCounter eval(mainEval); @@ -38,7 +38,7 @@ int main(int argc, char* argv[]) eoInit& init = make_genotype(parser, state, EOT()); // if you want to do sharing, you'll need a distance. - // here Hamming distance + // here Hamming distance eoHammingDistance dist; // OPERATORS @@ -74,7 +74,7 @@ int main(int argc, char* argv[]) // evaluate intial population AFTER help and status in case it takes time apply(eval, pop); // STOP - // print it out (sort witout modifying) + // print it out (sort witout modifying) cout << "Initial Population\n"; pop.sortedPrintOn(cout); cout << endl; @@ -82,7 +82,7 @@ int main(int argc, char* argv[]) // GENERATION run_ea(ga, pop); // run the ga // STOP - // print it out (sort witout modifying) + // print it out (sort witout modifying) cout << "Final Population\n"; pop.sortedPrintOn(cout); cout << endl; diff --git a/eo/tutorial/Lesson4/CMakeLists.txt b/eo/tutorial/Lesson4/CMakeLists.txt index 20e0cde4..739fed1b 100644 --- a/eo/tutorial/Lesson4/CMakeLists.txt +++ b/eo/tutorial/Lesson4/CMakeLists.txt @@ -21,7 +21,7 @@ EXECUTE_PROCESS( # COMMAND ${CMAKE_COMMAND} # ARGS -E copy_if_different # ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param -# ${EO_BINARY_DIR}/tutorial/Lesson4) +# ${EO_BINARY_DIR}/tutorial/Lesson4) #ADD_CUSTOM_TARGET(param DEPENDS ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param) #ADD_CUSTOM_COMMAND( # TARGET param @@ -29,7 +29,7 @@ EXECUTE_PROCESS( # COMMAND ${CMAKE_COMMAND} # ARGS -E copy_if_different # ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param -# ${EO_BINARY_DIR}/tutorial/Lesson4) +# ${EO_BINARY_DIR}/tutorial/Lesson4) ###################################################################################### ### 1) Include the sources @@ -44,23 +44,23 @@ INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### ### 3) Define your targets ###################################################################################### # no matter what is the OS, hopefully -ADD_EXECUTABLE(BitEA BitEA.cpp) -ADD_EXECUTABLE(RealEA RealEA.cpp) -ADD_EXECUTABLE(ESEA ESEA.cpp) +ADD_EXECUTABLE(BitEA BitEA.cpp) +ADD_EXECUTABLE(RealEA RealEA.cpp) +ADD_EXECUTABLE(ESEA ESEA.cpp) #ADD_DEPENDENCIES(BitEA es ga eo eoutils) #ADD_DEPENDENCIES(RealEA es ga eo eoutils) @@ -96,4 +96,3 @@ INSTALL(TARGETS RealEA RUNTIME DESTINATION share/eo/examples/Lesson4 COMPONENT e INSTALL(TARGETS ESEA RUNTIME DESTINATION share/eo/examples/Lesson4 COMPONENT examples) ###################################################################################### - diff --git a/eo/tutorial/Lesson4/ESEA.cpp b/eo/tutorial/Lesson4/ESEA.cpp index 1c1bd30c..6a2b51a2 100644 --- a/eo/tutorial/Lesson4/ESEA.cpp +++ b/eo/tutorial/Lesson4/ESEA.cpp @@ -20,14 +20,14 @@ using namespace std; #include "real_value.h" // the sphere fitness -// Now the main -/////////////// +// Now the main +/////////////// typedef eoMinimizingFitness FitT; template void runAlgorithm(EOT, eoParser& _parser, eoState& _state); - -int main_function(int argc, char *argv[]) + +int main_function(int argc, char *argv[]) { // Create the command-line parser eoParser parser(argc, argv); // for user-parameter reading @@ -55,33 +55,33 @@ int main_function(int argc, char *argv[]) cout << "Using eoEsStdev" << endl; runAlgorithm(eoEsStdev(), parser, state); } - else + else { cout << "Using eoEsFull" << endl; runAlgorithm(eoEsFull(), parser, state); } - return 0; + return 0; } // A main that catches the exceptions - + int main(int argc, char **argv) { try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } - + return 1; } /** The templatized main (sort of) - * quite similar to the main of other genotypes + * quite similar to the main of other genotypes * (e.g. t-eoReal and t-eoGA in test dir) */ template @@ -92,9 +92,9 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state) ///// FIRST, problem or representation dependent stuff ////////////////////////////////////////////////////// - // The evaluation fn - encapsulated into an eval counter for output - eoEvalFuncPtr&> - mainEval( real_value ); + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + mainEval( real_value ); eoEvalFuncCounter eval(mainEval); // the genotype - through a genotype initializer diff --git a/eo/tutorial/Lesson4/ESEA.param b/eo/tutorial/Lesson4/ESEA.param index 06df5c73..b5dc6d01 100644 --- a/eo/tutorial/Lesson4/ESEA.param +++ b/eo/tutorial/Lesson4/ESEA.param @@ -1,4 +1,3 @@ - ###### General ###### # --help=0 # -h : Prints this message # --stopOnUnknownParam=1 # Stop if unkown param entered @@ -17,7 +16,7 @@ --weakElitism=0 # -w : Old best parent replaces new worst offspring *if necessary* ###### Genotype Initialization ###### -# --vecSize=10 # -n : The number of variables +# --vecSize=10 # -n : The number of variables # --initBounds=10[-1,1] # -B : Bounds for initialization (MUST be bounded) --sigmaInit=0.3% # -s : Initial value for Sigmas (with a '%' -> scaled by the range of each variable) diff --git a/eo/tutorial/Lesson4/Makefile.simple b/eo/tutorial/Lesson4/Makefile.simple index 75bd41dd..72c02565 100644 --- a/eo/tutorial/Lesson4/Makefile.simple +++ b/eo/tutorial/Lesson4/Makefile.simple @@ -1,5 +1,5 @@ ### This Makefile is part of the tutorial of the EO library -# Unlike other Makefiles in EO, it is not using the automake/autoconf +# Unlike other Makefiles in EO, it is not using the automake/autoconf # so that it stays easy to understant (you are in the tutorial, remember!) # MS, Oct. 2002 @@ -10,11 +10,11 @@ DIR_EO = ../../src .SUFFIXES: .cpp # Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++ -# However, if you are using this Makefile within xemacs, +# However, if you are using this Makefile within xemacs, # and have problems with the interpretation of the output (and its colors) # then you should use c++ instead (make CXX=c++ will do) -.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a .cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c $*.cpp @@ -22,12 +22,12 @@ ALL = BitEA RealEA ESEA all : $(ALL) -BitEA : BitEA.o ; - $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/ga/libga.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +BitEA : BitEA.o ; + $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/ga/libga.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a RealEA : RealEA.o ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/es/libes.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a ESEA : ESEA.o ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.2\" -Wall -g -o $@ $< $(DIR_EO)/es/libes.a $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -clean : +clean : @/bin/rm $(ALL) *.o *.sav *.xg *.status *~ diff --git a/eo/tutorial/Lesson4/RealEA.cpp b/eo/tutorial/Lesson4/RealEA.cpp index 8002136c..1775b12b 100644 --- a/eo/tutorial/Lesson4/RealEA.cpp +++ b/eo/tutorial/Lesson4/RealEA.cpp @@ -20,9 +20,9 @@ int main(int argc, char* argv[]) ///// FIRST, problem or representation dependent stuff ////////////////////////////////////////////////////// - // The evaluation fn - encapsulated into an eval counter for output - eoEvalFuncPtr&> - mainEval( real_value ); + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + mainEval( real_value ); eoEvalFuncCounter eval(mainEval); // the genotype - through a genotype initializer diff --git a/eo/tutorial/Lesson4/RealEA.param b/eo/tutorial/Lesson4/RealEA.param index dba2db34..d1f8cfc4 100644 --- a/eo/tutorial/Lesson4/RealEA.param +++ b/eo/tutorial/Lesson4/RealEA.param @@ -1,4 +1,3 @@ - ###### General ###### # --help=0 # -h : Prints this message # --stopOnUnknownParam=1 # Stop if unkown param entered @@ -12,7 +11,7 @@ --weakElitism=0 # -w : Old best parent replaces new worst offspring *if necessary* ###### Genotype Initialization ###### -# --vecSize=10 # -n : The number of variables +# --vecSize=10 # -n : The number of variables # --initBounds=10[-1,1] # -B : Bounds for initialization (MUST be bounded) --sigmaInit=0.3% # -s : Initial value for Sigmas (with a '%' -> scaled by the range of each variable) diff --git a/eo/tutorial/Lesson4/binary_value.h b/eo/tutorial/Lesson4/binary_value.h index 188835fc..f8dd5891 100644 --- a/eo/tutorial/Lesson4/binary_value.h +++ b/eo/tutorial/Lesson4/binary_value.h @@ -4,7 +4,7 @@ /** Just a simple function that takes binary value of a chromosome and sets the fitnes. - @param _chrom A binary chromosome + @param _chrom A binary chromosome */ template double binary_value(const Chrom& _chrom) diff --git a/eo/tutorial/Lesson4/real_value.h b/eo/tutorial/Lesson4/real_value.h index 8f3a0df5..f8ef3e58 100644 --- a/eo/tutorial/Lesson4/real_value.h +++ b/eo/tutorial/Lesson4/real_value.h @@ -2,8 +2,8 @@ //----------------------------------------------------------------------------- -/** Just a simple function that takes an eoEsBase and sets the fitnes - to sphere +/** Just a simple function that takes an eoEsBase and sets the fitnes + to sphere @param _ind vector */ @@ -14,6 +14,3 @@ double real_value(const std::vector& _ind) sum += _ind[i] * _ind[i]; return sqrt(sum); } - - - diff --git a/eo/tutorial/Lesson5/CMakeLists.txt b/eo/tutorial/Lesson5/CMakeLists.txt index 224552e3..72852d04 100644 --- a/eo/tutorial/Lesson5/CMakeLists.txt +++ b/eo/tutorial/Lesson5/CMakeLists.txt @@ -9,22 +9,22 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### ### 3) Define your targets ###################################################################################### # no matter what is the OS, hopefully -ADD_EXECUTABLE(OneMaxEA OneMaxEA.cpp) -ADD_EXECUTABLE(OneMaxLibEA OneMaxLibEA.cpp make_OneMax.cpp) +ADD_EXECUTABLE(OneMaxEA OneMaxEA.cpp) +ADD_EXECUTABLE(OneMaxLibEA OneMaxLibEA.cpp make_OneMax.cpp) ADD_DEPENDENCIES(OneMaxEA es ga eo eoutils) ADD_DEPENDENCIES(OneMaxLibEA es ga eo eoutils) diff --git a/eo/tutorial/Lesson5/Makefile.simple b/eo/tutorial/Lesson5/Makefile.simple index bb865c10..ace0df58 100644 --- a/eo/tutorial/Lesson5/Makefile.simple +++ b/eo/tutorial/Lesson5/Makefile.simple @@ -1,5 +1,5 @@ ### This Makefile is part of the tutorial of the EO library -# Unlike other Makefiles in EO, it is not using the automake/autoconf +# Unlike other Makefiles in EO, it is not using the automake/autoconf # so that it stays easy to understant (you are in the tutorial, remember!) # MS, Oct. 2002 @@ -10,11 +10,11 @@ DIR_EO = ../../src .SUFFIXES: .cpp # Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++ -# However, if you are using this Makefile within xemacs, +# However, if you are using this Makefile within xemacs, # and have problems with the interpretation of the output (and its colors) # then you should use c++ instead (make CXX=c++ will do) -.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -o $@ $*.cpp $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a .cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c $*.cpp @@ -39,7 +39,7 @@ LIB_EO = $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a ALL = OneMaxEA OneMaxLibEA OneMaxEA : OneMaxEA.o - $(CXX) -g -o $@ OneMaxEA.o $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -lm + $(CXX) -g -o $@ OneMaxEA.o $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -lm OneMaxLibEA : OneMaxLibEA.o make_OneMax.o $(CXX) -g -o $@ OneMaxLibEA.o make_OneMax.o $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -lm @@ -53,4 +53,4 @@ clean : ; /bin/rm *.o $(ALL) ########## local dependencies OneMaxEA.o : $(COMMON_SOURCES) OneMaxEA.cpp OneMaxLibEA.o : $(COMMON_SOURCES) OneMaxLibEA.cpp -make_OneMax.o : make_OneMax.cpp eoOneMax.h +make_OneMax.o : make_OneMax.cpp eoOneMax.h diff --git a/eo/tutorial/Lesson5/OneMaxEA.cpp b/eo/tutorial/Lesson5/OneMaxEA.cpp index 1f3470f3..14a0f4c5 100644 --- a/eo/tutorial/Lesson5/OneMaxEA.cpp +++ b/eo/tutorial/Lesson5/OneMaxEA.cpp @@ -17,7 +17,7 @@ main file BitEA in tutorial/Lesson4 dir. Or you can wait until we do it :-) */ -// Miscilaneous include and declaration +// Miscilaneous include and declaration #include using namespace std; @@ -29,17 +29,17 @@ using namespace std; // include here whatever specific files for your representation // Basically, this should include at least the following -/** definition of representation: +/** definition of representation: * class eoOneMax MUST derive from EO for some fitness */ #include "eoOneMax.h" -/** definition of initilizqtion: +/** definition of initilizqtion: * class eoOneMaxInit MUST derive from eoInit */ #include "eoOneMaxInit.h" -/** definition of evaluation: +/** definition of evaluation: * class eoOneMaxEvalFunc MUST derive from eoEvalFunc * and should test for validity before doing any computation * see tutorial/Templates/evalFunc.tmpl @@ -51,19 +51,19 @@ using namespace std; //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // START fitness type: double or eoMaximizingFitness if you are maximizing // eoMinimizingFitness if you are minimizing -typedef eoMaximizingFitness MyFitT ; // type of fitness +typedef eoMaximizingFitness MyFitT ; // type of fitness // END fitness type //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // Then define your EO objects using that fitness type -typedef eoOneMax Indi; // ***MUST*** derive from EO +typedef eoOneMax Indi; // ***MUST*** derive from EO // create an initializer #include "make_genotype_OneMax.h" eoInit & make_genotype(eoParser& _parser, eoState&_state, Indi _eo) { return do_make_genotype(_parser, _state, _eo); -} +} // and the variation operaotrs #include "make_op_OneMax.h" @@ -75,7 +75,7 @@ eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) // Use existing modules to define representation independent routines // These are parser-based definitions of objects -// how to initialize the population +// how to initialize the population // it IS representation independent if an eoInit is given #include eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init) @@ -92,7 +92,7 @@ eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCo // outputs (stats, population dumps, ...) #include -eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } @@ -104,7 +104,7 @@ eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc // the instanciating fitnesses @@ -141,7 +141,7 @@ int main(int argc, char* argv[]) eoGenOp& op = make_op(parser, state, init); - //// Now the representation-independent things + //// Now the representation-independent things // // YOU SHOULD NOT NEED TO MODIFY ANYTHING BEYOND THIS POINT // unless you want to add specific statistics to the checkpoint diff --git a/eo/tutorial/Lesson5/OneMaxLibEA.cpp b/eo/tutorial/Lesson5/OneMaxLibEA.cpp index 42d25f92..febcca44 100644 --- a/eo/tutorial/Lesson5/OneMaxLibEA.cpp +++ b/eo/tutorial/Lesson5/OneMaxLibEA.cpp @@ -8,11 +8,11 @@ Template for creating a new representation in EO ================================================ This is the template main file for compiling after creating a -library. +library. See make_OneMax.cpp file. */ -// Miscilaneous include and declaration +// Miscilaneous include and declaration #include using namespace std; @@ -24,17 +24,17 @@ using namespace std; // include here whatever specific files for your representation // Basically, this should include at least the following -/** definition of representation: +/** definition of representation: * class eoOneMax MUST derive from EO for some fitness */ #include "eoOneMax.h" -/** definition of initilizqtion: +/** definition of initilizqtion: * class eoOneMaxInit MUST derive from eoInit */ #include "eoOneMaxInit.h" -/** definition of evaluation: +/** definition of evaluation: * class eoOneMaxEvalFunc MUST derive from eoEvalFunc * and should test for validity before doing any computation * see tutorial/Templates/evalFunc.tmpl @@ -46,12 +46,12 @@ using namespace std; // // START fitness type: double or eoMaximizingFitness if you are maximizing // eoMinimizingFitness if you are minimizing -typedef eoMinimizingFitness MyFitT ; // type of fitness +typedef eoMinimizingFitness MyFitT ; // type of fitness // END fitness type // // Then define your EO objects using that fitness type -typedef eoOneMax Indi; // ***MUST*** derive from EO +typedef eoOneMax Indi; // ***MUST*** derive from EO // create an initializer - done here and NOT in make_OneMax.cpp // because it is NOT representation independent @@ -59,7 +59,7 @@ typedef eoOneMax Indi; // ***MUST*** derive from EO eoInit & make_genotype(eoParser& _parser, eoState&_state, Indi _eo) { return do_make_genotype(_parser, _state, _eo); -} +} // same thing for the variation operaotrs #include "make_op_OneMax.h" @@ -70,7 +70,7 @@ eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) // The representation independent routines are simply declared here -// how to initialize the population +// how to initialize the population // it IS representation independent if an eoInit is given eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init); @@ -83,7 +83,7 @@ eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFu // evolution engine (selection and replacement) eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op); -// simple call to the algo. stays there for consistency reasons +// simple call to the algo. stays there for consistency reasons // no template for that one void run_ea(eoAlgo& _ga, eoPop& _pop); @@ -115,7 +115,7 @@ int main(int argc, char* argv[]) eoGenOp& op = make_op(parser, state, init); - //// Now the representation-independent things + //// Now the representation-independent things // // YOU SHOULD NOT NEED TO MODIFY ANYTHING BEYOND THIS POINT // unless you want to add specific statistics to the checkpoint diff --git a/eo/tutorial/Lesson5/eoOneMax.h b/eo/tutorial/Lesson5/eoOneMax.h index a85bb89f..e78b9050 100644 --- a/eo/tutorial/Lesson5/eoOneMax.h +++ b/eo/tutorial/Lesson5/eoOneMax.h @@ -11,7 +11,7 @@ Template for creating a new representation in EO #ifndef _eoOneMax_h #define _eoOneMax_h -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen @@ -20,7 +20,7 @@ Template for creating a new representation in EO * like eoVector for instance, if you handle a vector of something.... * If you create a structure from scratch, - * the only thing you need to provide are + * the only thing you need to provide are * a default constructor * IO routines printOn and readFrom * @@ -31,11 +31,11 @@ template< class FitT> class eoOneMax: public EO { public: /** Ctor: you MUST provide a default ctor. - * though such individuals will generally be processed + * though such individuals will generally be processed * by some eoInit object */ - eoOneMax() - { + eoOneMax() + { // START Code of default Ctor of an eoOneMax object // END Code of default Ctor of an eoOneMax object } @@ -54,7 +54,7 @@ public: // First write the fitness EO::printOn(_os); _os << ' '; - // START Code of default output + // START Code of default output /** HINTS * in EO we systematically write the sizes of things before the things @@ -66,7 +66,7 @@ public: // END Code of default output } - /** reading... + /** reading... * of course, your readFrom must be able to read what printOn writes!!! */ void readFrom(istream& _is) @@ -87,7 +87,7 @@ public: bool bTmp; _is >> bTmp; b[i] = bTmp; - } + } // END Code of input } @@ -108,4 +108,3 @@ private: // put all data here }; #endif - diff --git a/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h b/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h index b7f18746..e9c31d79 100644 --- a/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h +++ b/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h @@ -1,13 +1,13 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + The above line is usefulin Emacs-like editors */ - + /* Template for evaluator in EO, a functor that computes the fitness of an EO ========================================================================== */ - + #ifndef _eoOneMaxEvalFunc_h #define _eoOneMaxEvalFunc_h @@ -18,7 +18,7 @@ Template for evaluator in EO, a functor that computes the fitness of an EO // include the base definition of eoEvalFunc #include "eoEvalFunc.h" -/** +/** Always write a comment in this format before class definition if you want the class to be documented by Doxygen */ @@ -29,7 +29,7 @@ public: /// Ctor - no requirement // START eventually add or modify the anyVariable argument eoOneMaxEvalFunc() - // eoOneMaxEvalFunc( varType _anyVariable) : anyVariable(_anyVariable) + // eoOneMaxEvalFunc( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument { // START Code of Ctor of an eoOneMaxEvalFunc object @@ -39,7 +39,7 @@ public: /** Actually compute the fitness * * @param EOT & _eo the EO object to evaluate - * it should stay templatized to be usable + * it should stay templatized to be usable * with any fitness type */ void operator()(EOT & _eo) diff --git a/eo/tutorial/Lesson5/eoOneMaxInit.h b/eo/tutorial/Lesson5/eoOneMaxInit.h index 7d97ae7b..3622aa67 100644 --- a/eo/tutorial/Lesson5/eoOneMaxInit.h +++ b/eo/tutorial/Lesson5/eoOneMaxInit.h @@ -14,12 +14,12 @@ Template for EO objects initialization in EO // include the base definition of eoInit #include -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * * There is NO ASSUMPTION on the class GenoypeT. - * In particular, it does not need to derive from EO (e.g. to initialize + * In particular, it does not need to derive from EO (e.g. to initialize * atoms of an eoVector you will need an eoInit) */ template @@ -28,7 +28,7 @@ public: /// Ctor - no requirement // START eventually add or modify the anyVariable argument // eoOneMaxInit() - eoOneMaxInit( unsigned _vecSize) : vecSize(_vecSize) + eoOneMaxInit( unsigned _vecSize) : vecSize(_vecSize) // END eventually add or modify the anyVariable argument { // START Code of Ctor of an eoOneMaxInit object @@ -60,4 +60,3 @@ private: }; #endif - diff --git a/eo/tutorial/Lesson5/eoOneMaxMutation.h b/eo/tutorial/Lesson5/eoOneMaxMutation.h index 50e93109..42a840fe 100644 --- a/eo/tutorial/Lesson5/eoOneMaxMutation.h +++ b/eo/tutorial/Lesson5/eoOneMaxMutation.h @@ -32,10 +32,10 @@ public: eoOneMaxMutation() // eoOneMaxMutation( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument - { - // START Code of Ctor of an eoOneMaxEvalFunc object - // END Code of Ctor of an eoOneMaxEvalFunc object - } + { + // START Code of Ctor of an eoOneMaxEvalFunc object + // END Code of Ctor of an eoOneMaxEvalFunc object + } /// The class name. Used to display statistics string className() const { return "eoOneMaxMutation"; } @@ -45,19 +45,19 @@ public: * @param _genotype The parent genotype (will be modified) */ bool operator()(GenotypeT & _genotype) - { - bool isModified(true); - // START code for mutation of the _genotype object + { + bool isModified(true); + // START code for mutation of the _genotype object - /** Requirement - * if (_genotype has been modified) - * isModified = true; - * else - * isModified = false; - */ - return isModified; - // END code for mutation of the _genotype object - } + /** Requirement + * if (_genotype has been modified) + * isModified = true; + * else + * isModified = false; + */ + return isModified; + // END code for mutation of the _genotype object + } private: // START Private data of an eoOneMaxMutation object diff --git a/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h b/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h index 5a201bd0..b1094215 100644 --- a/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h +++ b/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h @@ -33,10 +33,10 @@ public: eoOneMaxQuadCrossover() // eoOneMaxQuadCrossover( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument - { - // START Code of Ctor of an eoOneMaxEvalFunc object - // END Code of Ctor of an eoOneMaxEvalFunc object - } + { + // START Code of Ctor of an eoOneMaxEvalFunc object + // END Code of Ctor of an eoOneMaxEvalFunc object + } /// The class name. Used to display statistics string className() const { return "eoOneMaxQuadCrossover"; } @@ -47,19 +47,19 @@ public: * @param _genotype2 The second parent */ bool operator()(GenotypeT& _genotype1, GenotypeT & _genotype2) - { - bool oneAtLeastIsModified(true); - // START code for crossover of _genotype1 and _genotype2 objects + { + bool oneAtLeastIsModified(true); + // START code for crossover of _genotype1 and _genotype2 objects - /** Requirement - * if (at least one genotype has been modified) // no way to distinguish - * oneAtLeastIsModified = true; - * else - * oneAtLeastIsModified = false; - */ - return oneAtLeastIsModified; - // END code for crossover of _genotype1 and _genotype2 objects - } + /** Requirement + * if (at least one genotype has been modified) // no way to distinguish + * oneAtLeastIsModified = true; + * else + * oneAtLeastIsModified = false; + */ + return oneAtLeastIsModified; + // END code for crossover of _genotype1 and _genotype2 objects + } private: // START Private data of an eoOneMaxQuadCrossover object diff --git a/eo/tutorial/Lesson5/make_OneMax.cpp b/eo/tutorial/Lesson5/make_OneMax.cpp index 29fa78e6..7c2c05ee 100644 --- a/eo/tutorial/Lesson5/make_OneMax.cpp +++ b/eo/tutorial/Lesson5/make_OneMax.cpp @@ -17,7 +17,7 @@ and src/es (for real vectors). */ -// Miscilaneous include and declaration +// Miscilaneous include and declaration #include using namespace std; @@ -29,7 +29,7 @@ using namespace std; // include here whatever specific files for your representation // Basically, this should include at least the following -/** definition of representation: +/** definition of representation: * class eoOneMax MUST derive from EO for some fitness */ #include "eoOneMax.h" @@ -43,12 +43,12 @@ using namespace std; // eoInit> & make_genotype(eoParser& _parser, eoState&_state, eoOneMax _eo) // { // return do_make_genotype(_parser, _state, _eo); -// } +// } // eoInit> & make_genotype(eoParser& _parser, eoState&_state, eoOneMax _eo) // { // return do_make_genotype(_parser, _state, _eo); -// } +// } // same thing for the variation operaotrs //--------------------------------------- @@ -65,7 +65,7 @@ using namespace std; // The following modules use ***representation independent*** routines -// how to initialize the population +// how to initialize the population // it IS representation independent if an eoInit is given #include eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) @@ -92,12 +92,12 @@ eoContinue >& make_continue(eoParser& _parser, eoS // outputs (stats, population dumps, ...) #include -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } @@ -114,7 +114,7 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoS return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); } -// simple call to the algo. stays there for consistency reasons +// simple call to the algo. stays there for consistency reasons // no template for that one #include void run_ea(eoAlgo >& _ga, eoPop >& _pop) @@ -126,4 +126,3 @@ void run_ea(eoAlgo >& _ga, eoPop * - * It could be here tempatized only on the fitness, as it can be used + * It could be here tempatized only on the fitness, as it can be used * to evolve structures with any fitness. - * However, for consistency reasons, it was finally chosen, as in - * the rest of EO, to templatize by the full EOT, as this eventually + * However, for consistency reasons, it was finally chosen, as in + * the rest of EO, to templatize by the full EOT, as this eventually * allows to choose the type of genotype at run time (see in es dir) * - * It returns an eoInit that can later be used to initialize + * It returns an eoInit that can later be used to initialize * the population (see make_pop.h). * * It uses a parser (to get user parameters) and a state (to store the memory) * the last argument is to disambiguate the call upon different instanciations. * - * WARNING: that last argument will generally be the result of calling - * the default ctor of EOT, resulting in most cases in an EOT + * WARNING: that last argument will generally be the result of calling + * the default ctor of EOT, resulting in most cases in an EOT * that is ***not properly initialized*** */ template eoInit & do_make_genotype(eoParameterLoader& _parser, eoState& _state, EOT) { - // read any useful parameter here from the parser + // read any useful parameter here from the parser // the param itself will belong to the parser (as far as memory is concerned) // paramType & param = _parser.createParam(deafultValue, "Keyword", "Comment to appear in help and status", 'c',"Section of status file").value(); diff --git a/eo/tutorial/Lesson5/make_op_OneMax.h b/eo/tutorial/Lesson5/make_op_OneMax.h index d19c8930..e157720f 100644 --- a/eo/tutorial/Lesson5/make_op_OneMax.h +++ b/eo/tutorial/Lesson5/make_op_OneMax.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_OneMax.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 @@ -19,8 +19,8 @@ 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 + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk */ //----------------------------------------------------------------------------- @@ -35,14 +35,14 @@ // combinations of simple eoOps (eoMonOp and eoQuadOp) #include -/** definition of mutation: +/** definition of mutation: * class eoOneMaxMonop MUST derive from eoMonOp */ #include "eoOneMaxMutation.h" -/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2): +/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2): * class eoOneMaxBinCrossover MUST derive from eoBinOp - * OR + * OR * class eoOneMaxQuadCrossover MUST derive from eoQuadOp */ // #include "eoOneMaxBinOp.h" @@ -61,9 +61,9 @@ * This function builds the operators that will be applied to the eoOneMax * * It uses a parser (to get user parameters), a state (to store the memory) - * the last parameter is an eoInit: if some operator needs some info + * the last parameter is an eoInit: if some operator needs some info * about the genotypes, the init has it all (e.g. bounds, ...) - * Simply do + * Simply do * EOT myEO; * _init(myEO); * and myEO is then an ACTUAL object @@ -85,7 +85,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit2) only - no time for the eoBinOp case // you can have more than one - combined in a proportional way - + // first, define the crossover objects and read their rates from the parser - - // A first crossover + + // A first crossover eoQuadOp *cross = new eoOneMaxQuadCrossover /* (varType _anyVariable) */; // store in the state _state.storeFunctor(cross); @@ -106,21 +106,21 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit *propXover = + eoPropCombinedQuadOp *propXover = new eoPropCombinedQuadOp(*cross, cross1Rate); // and of course stor it in the state _state.storeFunctor(propXover); - // Optional: A second(and third, and ...) crossover + // Optional: A second(and third, and ...) crossover // of course you must create the corresponding classes // and all ***MUST*** derive from eoQuadOp /* Uncomment if necessary - and replicate as many time as you need - cross = new eoOneMaxSecondCrossover(varType _anyVariable); + cross = new eoOneMaxSecondCrossover(varType _anyVariable); _state.storeFunctor(cross); - double cross2Rate = _parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value(); - propXover.add(*cross, cross2Rate); + double cross2Rate = _parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value(); + propXover.add(*cross, cross2Rate); */ // if you want some gentle output, the last one shoudl be like // propXover.add(*cross, crossXXXRate, true); @@ -130,12 +130,12 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit *mut = new eoOneMaxMutation/* (varType _anyVariable) */; _state.storeFunctor(mut); // its relative rate in the combination @@ -151,8 +151,8 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit(varType _anyVariable); _state.storeFunctor(mut); - double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); - propMutation.add(*mut, mut2Rate); + double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); + propMutation.add(*mut, mut2Rate); */ // if you want some gentle output, the last one shoudl be like // propMutation.add(*mut, mutXXXRate, true); @@ -170,7 +170,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit swarm + // population <=> swarm eoPop pop; /// EVALUATION @@ -78,8 +78,8 @@ void main_function(int argc, char **argv) ////////////// // ring topology eoRingTopology topology(NEIGHBORHOOD_SIZE); - - + + ///////////////////// // INITIALIZATION //////////////////// @@ -87,7 +87,7 @@ void main_function(int argc, char **argv) eoUniformGenerator uGen; eoInitFixedLength < Particle > random (VEC_SIZE, uGen); pop.append (POP_SIZE, random); - + // velocities initialization component eoUniformGenerator < double >sGen (VELOCITY_INIT_MIN, VELOCITY_INIT_MAX); eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); @@ -101,23 +101,23 @@ void main_function(int argc, char **argv) // - the first best positions of each particle // - setups the topology eoInitializer fullInit(eval,veloRandom,localInit,topology,pop); - + // Full initialization here to be able to print the initial population // Else: give the "init" component in the eoEasyPSO constructor fullInit(); - + ///////////// // OUTPUT //////////// // sort pop before printing it! pop.sort(); - + // Print (sorted) the initial population (raw printout) cout << "INITIAL POPULATION:" << endl; for (unsigned i = 0; i < pop.size(); ++i) - cout << "\t best fit=" << pop[i] << endl; + cout << "\t best fit=" << pop[i] << endl; + - /////////////// /// VELOCITY ////////////// @@ -148,7 +148,7 @@ void main_function(int argc, char **argv) //////////////////////////////////////// // standard PSO requires // stopping criteria, evaluation,velocity, flight - + eoEasyPSO pso(genCont, eval, velocity, flight); // Apply the algo to the swarm - that's it! @@ -159,7 +159,7 @@ void main_function(int argc, char **argv) pop.sort(); cout << "FINAL POPULATION:" << endl; for (unsigned i = 0; i < pop.size(); ++i) - cout << "\t best fit=" << pop[i] << endl; + cout << "\t best fit=" << pop[i] << endl; } @@ -167,14 +167,14 @@ void main_function(int argc, char **argv) // A main that catches the exceptions int main(int argc, char **argv) -{ +{ try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Lesson6/CMakeLists.txt b/eo/tutorial/Lesson6/CMakeLists.txt index b1e41453..8cc0b101 100644 --- a/eo/tutorial/Lesson6/CMakeLists.txt +++ b/eo/tutorial/Lesson6/CMakeLists.txt @@ -8,21 +8,21 @@ INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### ### 3) Define your targets ###################################################################################### -ADD_EXECUTABLE(BinaryPSO BinaryPSO.cpp) -ADD_EXECUTABLE(RealPSO RealPSO.cpp) +ADD_EXECUTABLE(BinaryPSO BinaryPSO.cpp) +ADD_EXECUTABLE(RealPSO RealPSO.cpp) ###################################################################################### ### 4) Optionnal @@ -49,4 +49,3 @@ INSTALL(TARGETS BinaryPSO RUNTIME DESTINATION share/eo/examples/Lesson6 COMPONEN INSTALL(TARGETS RealPSO RUNTIME DESTINATION share/eo/examples/Lesson6 COMPONENT examples) ###################################################################################### - diff --git a/eo/tutorial/Lesson6/Makefile.simple b/eo/tutorial/Lesson6/Makefile.simple index d9b5b64f..5cdc5a46 100644 --- a/eo/tutorial/Lesson6/Makefile.simple +++ b/eo/tutorial/Lesson6/Makefile.simple @@ -1,5 +1,5 @@ ### This Makefile is part of the tutorial of the EO library -# Unlike other Makefiles in EO, it is not using the automake/autoconf +# Unlike other Makefiles in EO, it is not using the automake/autoconf # so that it stays easy to understant (you are in the tutorial, remember!) # MS, Oct. 2002 @@ -10,12 +10,12 @@ DIR_EO = ../../src .SUFFIXES: .cpp # Warning: $(CXX) in Linux (RedHat and Mandrake at least) is g++ -# However, if you are using this Makefile within xemacs, +# However, if you are using this Makefile within xemacs, # and have problems with the interpretation of the output (and its colors) # then you should use c++ instead (make CXX=c++ will do) -.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp -#$(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a +.cpp: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -pg -o $@ $*.cpp +#$(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a .cpp.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp @@ -27,5 +27,5 @@ lesson6 : $(PSO) all : $(ALL) -clean : +clean : @/bin/rm $(ALL) *.o *.sav *.xg *.status *~ diff --git a/eo/tutorial/Lesson6/RealPSO.cpp b/eo/tutorial/Lesson6/RealPSO.cpp index 77d1167c..23f67100 100644 --- a/eo/tutorial/Lesson6/RealPSO.cpp +++ b/eo/tutorial/Lesson6/RealPSO.cpp @@ -27,7 +27,7 @@ FitT real_value (const Particle & _particle) { double sum = 0; for (unsigned i = 0; i < _particle.size(); i++) - sum += pow(_particle[i],2); + sum += pow(_particle[i],2); return (sqrt(sum)); } @@ -38,21 +38,21 @@ void main_function(int argc, char **argv) // PARAMETRES // all parameters are hard-coded! const unsigned int SEED = 42; // seed for random number generator - + const unsigned int MAX_GEN=100; const unsigned int VEC_SIZE = 2; const unsigned int POP_SIZE = 20; const unsigned int NEIGHBORHOOD_SIZE= 5; - + const double POS_INIT_MIN= -2; const double POS_INIT_MAX= 2; - + const double VELOCITY_INIT_MIN= -1; const double VELOCITY_INIT_MAX= 1; - + const double VELOCITY_MIN= -1.5; const double VELOCITY_MAX= 1.5; - + const double INERTIA= 1; const double LEARNING_FACTOR1= 1.7; const double LEARNING_FACTOR2= 2.3; @@ -64,9 +64,9 @@ void main_function(int argc, char **argv) // you'll aways get the same result, NOT a random run rng.reseed(SEED); - + /// SWARM - // population <=> swarm + // population <=> swarm eoPop pop; /// EVALUATION @@ -79,8 +79,8 @@ void main_function(int argc, char **argv) ////////////// // linear topology eoLinearTopology topology(NEIGHBORHOOD_SIZE); - - + + ///////////////////// // INITIALIZATION //////////////////// @@ -88,7 +88,7 @@ void main_function(int argc, char **argv) eoUniformGenerator < double >uGen (POS_INIT_MIN, POS_INIT_MAX); eoInitFixedLength < Particle > random (VEC_SIZE, uGen); pop.append (POP_SIZE, random); - + // velocities initialization component eoUniformGenerator < double >sGen (VELOCITY_INIT_MIN, VELOCITY_INIT_MAX); eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); @@ -102,23 +102,23 @@ void main_function(int argc, char **argv) // - the first best positions of each particle // - setups the topology eoInitializer fullInit(eval,veloRandom,localInit,topology,pop); - + // Full initialization here to be able to print the initial population // Else: give the "init" component in the eoEasyPSO constructor fullInit(); - + ///////////// // OUTPUT //////////// // sort pop before printing it! pop.sort(); - + // Print (sorted) the initial population (raw printout) cout << "INITIAL POPULATION:" << endl; for (unsigned i = 0; i < pop.size(); ++i) - cout << "\t best fit=" << pop[i] << endl; + cout << "\t best fit=" << pop[i] << endl; + - /////////////// /// VELOCITY ////////////// @@ -149,7 +149,7 @@ void main_function(int argc, char **argv) //////////////////////////////////////// // standard PSO requires // stopping criteria, evaluation,velocity, flight - + eoEasyPSO pso(genCont, eval, velocity, flight); // Apply the algo to the swarm - that's it! @@ -160,7 +160,7 @@ void main_function(int argc, char **argv) pop.sort(); cout << "FINAL POPULATION:" << endl; for (unsigned i = 0; i < pop.size(); ++i) - cout << "\t best fit=" << pop[i] << endl; + cout << "\t best fit=" << pop[i] << endl; } @@ -168,14 +168,14 @@ void main_function(int argc, char **argv) // A main that catches the exceptions int main(int argc, char **argv) -{ +{ try { - main_function(argc, argv); + main_function(argc, argv); } catch(exception& e) { - cout << "Exception: " << e.what() << '\n'; + cout << "Exception: " << e.what() << '\n'; } return 1; diff --git a/eo/tutorial/Makefile.simple b/eo/tutorial/Makefile.simple index 5b5d54b2..b82ca27f 100644 --- a/eo/tutorial/Makefile.simple +++ b/eo/tutorial/Makefile.simple @@ -3,22 +3,22 @@ SUBDIRS = Lesson1 Lesson2 Lesson3 Lesson4 Lesson5 Lesson6 all: for i in $(SUBDIRS); do cd $$i && $(MAKE) all; cd ..; done -lesson1 : +lesson1 : cd Lesson1; make -lesson2 : +lesson2 : cd Lesson2; make -lesson3 : +lesson3 : cd Lesson3; make -lesson4 : +lesson4 : cd Lesson4; make -lesson5 : +lesson5 : cd Lesson5; make -lesson6 : +lesson6 : cd Lesson6; make #empty dist and distdir to let top-level 'make' do its job diff --git a/eo/tutorial/README b/eo/tutorial/README index aecd143e..e9d99410 100644 --- a/eo/tutorial/README +++ b/eo/tutorial/README @@ -2,12 +2,11 @@ Eo Tutorial - corresponding to EO version 0.9.1+ To start the tutorial, read index.html in your favorite browser. -Many things are missing, including many solutions for the exercises, +Many things are missing, including many solutions for the exercises, the introduction to EC and most of the Component-based pages. -More important, all examples of this tutorial have only been tested -on a Linux computer, and the Makefile will not work with MS-Windows +More important, all examples of this tutorial have only been tested +on a Linux computer, and the Makefile will not work with MS-Windows systems. Any help is welcome! -Be patient ... +Be patient ... evoMarc - diff --git a/eo/tutorial/Templates/CMakeLists.txt.src-tmpl b/eo/tutorial/Templates/CMakeLists.txt.src-tmpl index 833fa2b4..ee23cd0d 100755 --- a/eo/tutorial/Templates/CMakeLists.txt.src-tmpl +++ b/eo/tutorial/Templates/CMakeLists.txt.src-tmpl @@ -1,5 +1,3 @@ - - ###################################################################################### ### 1) Include the sources ###################################################################################### @@ -16,14 +14,14 @@ INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/do) ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) +IF(NOT WIN32 OR CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) ENDIF(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) +IF(WIN32 AND NOT CYGWIN) LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +ENDIF(WIN32 AND NOT CYGWIN) ###################################################################################### @@ -33,7 +31,7 @@ ENDIF(WIN32 AND NOT CYGWIN) ### 3) Define your targets ###################################################################################### -ADD_EXECUTABLE(MyStructEA MyStructEA.cpp) +ADD_EXECUTABLE(MyStructEA MyStructEA.cpp) ###################################################################################### @@ -42,7 +40,6 @@ ADD_EXECUTABLE(MyStructEA MyStructEA.cpp) ### 4) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(MyStructEA eo eoutils ga es) +TARGET_LINK_LIBRARIES(MyStructEA eo eoutils ga es) ###################################################################################### - diff --git a/eo/tutorial/Templates/CMakeLists.txt.top-tmpl b/eo/tutorial/Templates/CMakeLists.txt.top-tmpl index e169d235..c653b681 100755 --- a/eo/tutorial/Templates/CMakeLists.txt.top-tmpl +++ b/eo/tutorial/Templates/CMakeLists.txt.top-tmpl @@ -1,7 +1,5 @@ - - ###################################################################################### -### 1) Main project config +### 1) Main project config ###################################################################################### # set the project name @@ -19,16 +17,16 @@ ENABLE_LANGUAGE(CXX) IF(NOT EO_SOURCE_DIR) SET( EO_SOURCE_DIR - EO_SRC_DIR CACHE STRING - "EO source directory" - FORCE) + EO_SRC_DIR CACHE STRING + "EO source directory" + FORCE) ENDIF(NOT EO_SOURCE_DIR) IF(NOT EO_BINARY_DIR) - SET( EO_BINARY_DIR - EO_BIN_DIR CACHE STRING - "EO binary directory" - FORCE) + SET( EO_BINARY_DIR + EO_BIN_DIR CACHE STRING + "EO binary directory" + FORCE) ENDIF(NOT EO_BINARY_DIR) ###################################################################################### diff --git a/eo/tutorial/Templates/ChangeLog b/eo/tutorial/Templates/ChangeLog index ffecdd09..2ede582e 100644 --- a/eo/tutorial/Templates/ChangeLog +++ b/eo/tutorial/Templates/ChangeLog @@ -35,12 +35,12 @@ * README.manual: This is a copy of the old README. * README: Describe the new way and setup of creating a new EO project. - + * createEOproject.sh, Makefile.am.src-tmpl, Makefile.am.top-tmpl: * configure.ac.tmpl: New files to create a standalone EO project from templates. - + * Local Variables: * coding: iso-8859-1 * mode: flyspell diff --git a/eo/tutorial/Templates/EO.tpl b/eo/tutorial/Templates/EO.tpl index 342681bc..959ad56a 100644 --- a/eo/tutorial/Templates/EO.tpl +++ b/eo/tutorial/Templates/EO.tpl @@ -370,8 +370,8 @@ public: void printOn(ostream& os) const { // First write the fitness - EO::printOn(os); - os << ' '; + EO::printOn(os); + os << ' '; // START Code of default output /** HINTS diff --git a/eo/tutorial/Templates/MyStructLibEA.cpp b/eo/tutorial/Templates/MyStructLibEA.cpp index 24fed341..54e9f2ff 100644 --- a/eo/tutorial/Templates/MyStructLibEA.cpp +++ b/eo/tutorial/Templates/MyStructLibEA.cpp @@ -8,11 +8,11 @@ Template for creating a new representation in EO ================================================ This is the template main file for compiling after creating a -"library", i.e. putting everything but the fitness in a separate file +"library", i.e. putting everything but the fitness in a separate file (make_MyStruct.cpp) and compiling it once and for all. */ -// Miscilaneous include and declaration +// Miscilaneous include and declaration #include using namespace std; @@ -24,17 +24,17 @@ using namespace std; // include here whatever specific files for your representation // Basically, this should include at least the following -/** definition of representation: +/** definition of representation: * class eoMyStruct MUST derive from EO for some fitness */ #include "eoMyStruct.h" -/** definition of initilizqtion: +/** definition of initilizqtion: * class eoMyStructInit MUST derive from eoInit */ #include "eoMyStructInit.h" -/** definition of evaluation: +/** definition of evaluation: * class eoMyStructEvalFunc MUST derive from eoEvalFunc * and should test for validity before doing any computation * see tutorial/Templates/evalFunc.tmpl @@ -46,12 +46,12 @@ using namespace std; // // START fitness type: double or eoMaximizingFitness if you are maximizing // eoMinimizingFitness if you are minimizing -typedef eoMinimizingFitness MyFitT ; // type of fitness +typedef eoMinimizingFitness MyFitT ; // type of fitness // END fitness type // // Then define your EO objects using that fitness type -typedef eoMyStruct Indi; // ***MUST*** derive from EO +typedef eoMyStruct Indi; // ***MUST*** derive from EO // create an initializer - done here and NOT in make_MyStruct.cpp // because it is NOT representation independent @@ -59,7 +59,7 @@ typedef eoMyStruct Indi; // ***MUST*** derive from EO eoInit & make_genotype(eoParser& _parser, eoState&_state, Indi _eo) { return do_make_genotype(_parser, _state, _eo); -} +} // same thing for the variation operaotrs #include "make_op_MyStruct.h" @@ -70,7 +70,7 @@ eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) // The representation independent routines are simply declared here -// how to initialize the population +// how to initialize the population // it IS representation independent if an eoInit is given eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init); @@ -83,7 +83,7 @@ eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFu // evolution engine (selection and replacement) eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op); -// simple call to the algo. stays there for consistency reasons +// simple call to the algo. stays there for consistency reasons // no template for that one void run_ea(eoAlgo& _ga, eoPop& _pop); @@ -115,7 +115,7 @@ int main(int argc, char* argv[]) eoGenOp& op = make_op(parser, state, init); - //// Now the representation-independent things + //// Now the representation-independent things // // YOU SHOULD NOT NEED TO MODIFY ANYTHING BEYOND THIS POINT // unless you want to add specific statistics to the checkpoint diff --git a/eo/tutorial/Templates/README b/eo/tutorial/Templates/README index 9ab2d6a7..33d9438e 100644 --- a/eo/tutorial/Templates/README +++ b/eo/tutorial/Templates/README @@ -19,10 +19,10 @@ When running bash, use this: You can freely move the created project around. However, whenever you change the location of the source- or build-directories, you need to -run +run touch configure.ac && autoreconf -in the source-directory and - make +in the source-directory and + make in the build-directory (which might or might not be the same for you). diff --git a/eo/tutorial/Templates/README.manual b/eo/tutorial/Templates/README.manual index 2683707c..38693d83 100644 --- a/eo/tutorial/Templates/README.manual +++ b/eo/tutorial/Templates/README.manual @@ -5,7 +5,7 @@ However, see there first for the creation of new projects. ======================================================================== This directory contains sample files that should make it easy to -create an EO algorithm to evolve any type of structure +create an EO algorithm to evolve any type of structure (EO comes with two examples, bitstrings and vector of real variables, so you'll need this as soon as you want to evolve something else). @@ -13,7 +13,7 @@ At the moment, only algorithms involving a scalar fitness (double) are implemented (see test dir for Pareto optimization of multiple- objective fitness - or be patient :-) -This file will help you to build the same algorithm than the ones +This file will help you to build the same algorithm than the ones in the Lesson4 of the tutorial, but with YOUR genotype instead of bitstrings or vector. More details in Lesson5 of the tutorial. @@ -30,7 +30,7 @@ mutation and the computation of its fitness. The helper script * create.sh * will create for you the files you need from the samples in tutorial/Templates dir, and all you'll have to do is to include the actual code where indicated in those files (between -keywords START and END). +keywords START and END). First, let's choose a name: let's call the new EO class eoAppli. All newly created classes will be named eoAppliXXX (in the file @@ -41,24 +41,24 @@ eoAppliXXX) 2- create the directory for your application (let's assume you call it APPLICATION): type in - mkdir APPLICATION + mkdir APPLICATION -3- go to the Templates dir +3- go to the Templates dir - cd Templates + cd Templates -and run the helper script create.sh with the following arguments +and run the helper script create.sh with the following arguments - ./create.sh Appli ../APPLICATION + ./create.sh Appli ../APPLICATION -4- cd to the APPLICATION dir (cd ../APPLICATION). +4- cd to the APPLICATION dir (cd ../APPLICATION). You should see there the following files: AppliEA.cpp the main file, includes all other, to be compiled Makefile with default target eoAppliEA eoAppli.h class eoAppli, FitT = template fitness eoAppliEvalFunc.h class for the computation of fotness eoAppliInit.h class for genotype initlialization - eoAppliMutation.h class for mutation + eoAppliMutation.h class for mutation eoAppliQuadCrossover.h class for (quadratic) crossover make_genotype_Appli.h helper function that create the initializer make_op_Appli.h helper function that creates the variatin operators @@ -78,11 +78,11 @@ HINT: look for keywords START and END and modify code in between. 6- Compile eoAppliEA.cpp. If your APPLICATION dir is in the tutorial dir, you don't need to modify Makefile. Just type in - % make + % make 7- Run the resulting program: - % eoAppliEA + % eoAppliEA The default output is one line per generation with the generation number, the number of evaluations performed, the best and average @@ -93,7 +93,7 @@ The algorithm stops by default after 100 generations. e.g. eoAppliEA.param, edit eoAppliEA.param (uncomment the lines you want to become active), and run - % eoAppliEA @eoAppliEA.param + % eoAppliEA @eoAppliEA.param (see the Lesson 5 of the tutorial for more details now). @@ -121,19 +121,19 @@ To add another operator, you have to create another class by mimicking what has been done for the first operator. For instance, let's suppose you want to create another mutation. -* duplicate the code for eoAppliMutation class +* duplicate the code for eoAppliMutation class * in the second version, change the class name (eoAppliMutation) into another name (let's say eoAppliBetterMutation) - you must change the name in the class declaration, in the constructor and in the className() method. * in the new eoAppliBetterMutation class, change the code for the operator() - and eventually the code for the constructor. -* in the make_op_Appli.h file, in the mutation section, uncomment the -lines +* in the make_op_Appli.h file, in the mutation section, uncomment the +lines mut = new eoAppliSecondMutation(varType _anyVariable); _state.storeFunctor(mut); - double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); - propMutation.add(*mut, mut2Rate); + double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); + propMutation.add(*mut, mut2Rate); and change the name of the class from eoAppliSecondMutation to your name eoAppliBetterMutation (you can also change the keyword from diff --git a/eo/tutorial/Templates/binCrossover.tmpl b/eo/tutorial/Templates/binCrossover.tmpl index 5adabe68..c3f44c5a 100644 --- a/eo/tutorial/Templates/binCrossover.tmpl +++ b/eo/tutorial/Templates/binCrossover.tmpl @@ -7,8 +7,8 @@ The above line is useful in Emacs-like editors Template for simple binary crossover operators ============================================== -Binary crossover operators modify the first genotype only, -based on the second +Binary crossover operators modify the first genotype only, +based on the second */ #ifndef eoMyStructBinCrossover_H @@ -16,14 +16,14 @@ based on the second #include -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * * THere is NO ASSUMPTION on the class GenoypeT. * In particular, it does not need to derive from EO */ -template +template class eoMyStructBinCrossover: public eoBinOp { public: @@ -31,8 +31,8 @@ public: * Ctor - no requirement */ // START eventually add or modify the anyVariable argument - eoMyStructBinCrossover() - // eoMyStructBinCrossover( varType _anyVariable) : anyVariable(_anyVariable) + eoMyStructBinCrossover() + // eoMyStructBinCrossover( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument { // START Code of Ctor of an eoMyStructEvalFunc object @@ -47,7 +47,7 @@ public: * @param _genotype1 The first genotype * @param _genotype2 The second genotype - const */ - bool operator()(GenotypeT & _genotype1, const GenotypeT & _genotype2) + bool operator()(GenotypeT & _genotype1, const GenotypeT & _genotype2) { // START code for crossover of _genotype1 and _genotype2 objects diff --git a/eo/tutorial/Templates/configure.ac.tmpl b/eo/tutorial/Templates/configure.ac.tmpl index cc52cebd..8c09bf41 100644 --- a/eo/tutorial/Templates/configure.ac.tmpl +++ b/eo/tutorial/Templates/configure.ac.tmpl @@ -21,11 +21,11 @@ AC_CHECK_HEADERS([eo], [], [AC_ERROR(Evolving Objects headers are required)]) dnl Checks for libraries. AC_LANG(C++) AC_CHECK_LIB([eoutils], [main], [], - AC_MSG_ERROR([Evolving Objects utility library is required.])) + AC_MSG_ERROR([Evolving Objects utility library is required.])) AC_CHECK_LIB([eo], [main], [], - AC_MSG_ERROR([Evolving Objects library is required.])) + AC_MSG_ERROR([Evolving Objects library is required.])) AC_CHECK_LIB([es], [main], [], - AC_MSG_ERROR([EO Evolutionary strategies library is required.])) + AC_MSG_ERROR([EO Evolutionary strategies library is required.])) dnl Checks for library functions. diff --git a/eo/tutorial/Templates/continue.tmpl b/eo/tutorial/Templates/continue.tmpl index 2ec5a7be..bfcee4d3 100644 --- a/eo/tutorial/Templates/continue.tmpl +++ b/eo/tutorial/Templates/continue.tmpl @@ -14,11 +14,11 @@ Template for continuator in EO, i.e. stopping conditions for EO algorithms // include the base definition of eoContinue #include -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * - * ATTENTION, class EOT *must* derive from EO, as operator() will + * ATTENTION, class EOT *must* derive from EO, as operator() will * be called with an eoPop */ template< class EOT> @@ -29,7 +29,7 @@ public: */ // START eventually add or modify the anyVariable argument eoMyStructContinue() - // eoMyStructBinCrossover( varType _anyVariable) : anyVariable(_anyVariable) + // eoMyStructBinCrossover( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument { // START Code of Ctor of an eoMyStructEvalFunc object @@ -41,7 +41,7 @@ public: * * @param _pop an eoPop */ - virtual bool operator() ( const eoPop& _pop ) + virtual bool operator() ( const eoPop& _pop ) { bool stopCondition ; // to store the stopping condition // START Code of computation of stopping condition @@ -62,4 +62,3 @@ private: }; #endif - diff --git a/eo/tutorial/Templates/createEOproject.sh b/eo/tutorial/Templates/createEOproject.sh index 57915340..9f932f90 100755 --- a/eo/tutorial/Templates/createEOproject.sh +++ b/eo/tutorial/Templates/createEOproject.sh @@ -12,7 +12,7 @@ endif if ($#argv < 1) then echo "Usage: $0 ApplicationName [TargetDirName]" - echo " This will create ../TargetDirName if necessary (default dir name = ApplicationName)," + echo " This will create ../TargetDirName if necessary (default dir name = ApplicationName)," echo " and will also put all the files there that are strictly necessary to compile and run" echo " your application." exit @@ -94,7 +94,7 @@ echo "Start building the new project" #cd $TargetDir #aclocal || exit #autoheader || exit -#automake --add-missing --copy --gnu || exit +#automake --add-missing --copy --gnu || exit # !!!!! uncompatible option: --force-missing for the latest version of automake diff --git a/eo/tutorial/Templates/eoMyStruct.tmpl b/eo/tutorial/Templates/eoMyStruct.tmpl index ddf4e008..f68def2a 100644 --- a/eo/tutorial/Templates/eoMyStruct.tmpl +++ b/eo/tutorial/Templates/eoMyStruct.tmpl @@ -14,11 +14,11 @@ Mandatory: However, if you are using dynamic memory, there are 2 places to allocate it: the default constructor (if possible?), or, more in the EO spirit, the eoInit object, that you will need to write anyway -(template file init.tmpl). +(template file init.tmpl). But remember that a COPY CONSTRUCTOR will be used in many places in EO, so make sure that the default copy constructor works, or, even better, -do write your own if in doubt. +do write your own if in doubt. And of course write the corresponding destructor! */ @@ -26,7 +26,7 @@ And of course write the corresponding destructor! #ifndef _eoMyStruct_h #define _eoMyStruct_h -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen @@ -35,7 +35,7 @@ And of course write the corresponding destructor! * like eoVector for instance, if you handle a vector of something.... * If you create a structure from scratch, - * the only thing you need to provide are + * the only thing you need to provide are * a default constructor * IO routines printOn and readFrom * @@ -46,11 +46,11 @@ template< class FitT> class eoMyStruct: public EO { public: /** Ctor: you MUST provide a default ctor. - * though such individuals will generally be processed + * though such individuals will generally be processed * by some eoInit object */ - eoMyStruct() - { + eoMyStruct() + { // START Code of default Ctor of an eoMyStruct object // END Code of default Ctor of an eoMyStruct object } @@ -60,11 +60,11 @@ public: * If this is the case, uncomment and fill the following */ /* - eoMyStruct(const eoMyStruct &) - { + eoMyStruct(const eoMyStruct &) + { // START Code of copy Ctor of an eoMyStruct object // END Code of copy Ctor of an eoMyStruct object - } + } */ @@ -82,7 +82,7 @@ public: // First write the fitness EO::printOn(os); os << ' '; - // START Code of default output + // START Code of default output /** HINTS * in EO we systematically write the sizes of things before the things @@ -92,7 +92,7 @@ public: // END Code of default output } - /** reading... + /** reading... * of course, your readFrom must be able to read what printOn writes!!! */ void readFrom(istream& is) @@ -115,4 +115,3 @@ private: // put all data here }; #endif - diff --git a/eo/tutorial/Templates/evalFunc.tmpl b/eo/tutorial/Templates/evalFunc.tmpl index b8c9f1ed..34eae4c4 100644 --- a/eo/tutorial/Templates/evalFunc.tmpl +++ b/eo/tutorial/Templates/evalFunc.tmpl @@ -1,13 +1,13 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + The above line is usefulin Emacs-like editors */ - + /* Template for evaluator in EO, a functor that computes the fitness of an EO ========================================================================== */ - + #ifndef _eoMyStructEvalFunc_h #define _eoMyStructEvalFunc_h @@ -18,7 +18,7 @@ Template for evaluator in EO, a functor that computes the fitness of an EO // include the base definition of eoEvalFunc #include "eoEvalFunc.h" -/** +/** Always write a comment in this format before class definition if you want the class to be documented by Doxygen */ @@ -29,7 +29,7 @@ public: /// Ctor - no requirement // START eventually add or modify the anyVariable argument eoMyStructEvalFunc() - // eoMyStructEvalFunc( varType _anyVariable) : anyVariable(_anyVariable) + // eoMyStructEvalFunc( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument { // START Code of Ctor of an eoMyStructEvalFunc object @@ -39,7 +39,7 @@ public: /** Actually compute the fitness * * @param EOT & _eo the EO object to evaluate - * it should stay templatized to be usable + * it should stay templatized to be usable * with any fitness type */ void operator()(EOT & _eo) diff --git a/eo/tutorial/Templates/init.tmpl b/eo/tutorial/Templates/init.tmpl index f3c0fbd9..d49e52ef 100644 --- a/eo/tutorial/Templates/init.tmpl +++ b/eo/tutorial/Templates/init.tmpl @@ -14,12 +14,12 @@ Template for EO objects initialization in EO // include the base definition of eoInit #include -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * * There is NO ASSUMPTION on the class GenoypeT. - * In particular, it does not need to derive from EO (e.g. to initialize + * In particular, it does not need to derive from EO (e.g. to initialize * atoms of an eoVector you will need an eoInit) */ template @@ -28,7 +28,7 @@ public: /// Ctor - no requirement // START eventually add or modify the anyVariable argument eoMyStructInit() - // eoMyStructInit( varType _anyVariable) : anyVariable(_anyVariable) + // eoMyStructInit( varType _anyVariable) : anyVariable(_anyVariable) // END eventually add or modify the anyVariable argument { // START Code of Ctor of an eoMyStructInit object @@ -55,4 +55,3 @@ private: }; #endif - diff --git a/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl b/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl index 9a0c3c42..fea5a2a6 100644 --- a/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl +++ b/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl @@ -10,7 +10,7 @@ i.e. that takes any number of parents and generates any number of offspring a GenOp that creates less offspring than there are parents -Second version, get parents using an external eoSelectOne +Second version, get parents using an external eoSelectOne */ #ifndef eoLessOffspringExternalSelectorGenOp_H @@ -18,21 +18,21 @@ Second version, get parents using an external eoSelectOne #include -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * - * ATTENTION, class EOT *must* derive from EO, as method invalidate() + * ATTENTION, class EOT *must* derive from EO, as method invalidate() * must be called if the genotypes of the indis is modified */ -template +template class eoLessOffspringExternalSelectorGenOp: public eoGenOp { public: /** * (Default) Constructor. */ - eoLessOffspringExternalSelectorGenOp(eoSelectOne & _sel, paramType _anyParameter) : + eoLessOffspringExternalSelectorGenOp(eoSelectOne & _sel, paramType _anyParameter) : sel(_sel), anyParameter(_anyParameter) {} /// The class name. Used to display statistics @@ -58,11 +58,11 @@ public: // get extra parents - use private selector // _plop.source() is the eoPop used by _plop to get parents // WARNING: you are not allowed to modify them (mandatory "const") - const EOT& parentN+1 = sel(_plop.source()); - ... - const EOT& parentN+K = sel(_plop.source()); + const EOT& parentN+1 = sel(_plop.source()); + ... + const EOT& parentN+K = sel(_plop.source()); - // modify (in place) the "true" parents + // modify (in place) the "true" parents // (i.e. parent1, ..., parentsN) ... diff --git a/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl b/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl index c0790f93..8fdd8ff6 100644 --- a/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl +++ b/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl @@ -18,21 +18,21 @@ First version, get parents from populator using the imbedded select() method #include -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * - * ATTENTION, class EOT *must* derive from EO, as method invalidate() + * ATTENTION, class EOT *must* derive from EO, as method invalidate() * must be called if the genotypes of the indis is modified */ -template +template class eoLessOffspringSameSelectorGenOp: public eoGenOp { public: /** * (Default) Constructor. */ - eoLessOffspringSameSelectorGenOp(paramType _anyParameter) : + eoLessOffspringSameSelectorGenOp(paramType _anyParameter) : anyParameter(_anyParameter) {} /// The class name. Used to display statistics @@ -42,7 +42,7 @@ public: unsigned max_production(void) { return NbLeftParents; } /** - * eoLesOffspringSameSelectorGenOp operator - + * eoLesOffspringSameSelectorGenOp operator - * gets extra parents from the populator * * @param _pop a POPULATOR (not a simple population) diff --git a/eo/tutorial/Templates/make_MyStruct.cpp b/eo/tutorial/Templates/make_MyStruct.cpp index cf4804ce..aaf183c9 100644 --- a/eo/tutorial/Templates/make_MyStruct.cpp +++ b/eo/tutorial/Templates/make_MyStruct.cpp @@ -126,4 +126,3 @@ void run_ea(eoAlgo >& _ga, eoPop * - * It could be here tempatized only on the fitness, as it can be used + * It could be here tempatized only on the fitness, as it can be used * to evolve structures with any fitness. - * However, for consistency reasons, it was finally chosen, as in - * the rest of EO, to templatize by the full EOT, as this eventually + * However, for consistency reasons, it was finally chosen, as in + * the rest of EO, to templatize by the full EOT, as this eventually * allows to choose the type of genotype at run time (see in es dir) * - * It returns an eoInit that can later be used to initialize + * It returns an eoInit that can later be used to initialize * the population (see make_pop.h). * * It uses a parser (to get user parameters) and a state (to store the memory) * the last argument is to disambiguate the call upon different instanciations. * - * WARNING: that last argument will generally be the result of calling - * the default ctor of EOT, resulting in most cases in an EOT + * WARNING: that last argument will generally be the result of calling + * the default ctor of EOT, resulting in most cases in an EOT * that is ***not properly initialized*** */ template eoInit & do_make_genotype(eoParser& _parser, eoState& _state, EOT) { - // read any useful parameter here from the parser + // read any useful parameter here from the parser // the param itself will belong to the parser (as far as memory is concerned) // paramType & param = _parser.createParam(deafultValue, "Keyword", "Comment to appear in help and status", 'c',"Section of status file").value(); diff --git a/eo/tutorial/Templates/make_op_MyStruct.h b/eo/tutorial/Templates/make_op_MyStruct.h index 8b43d17b..d857e895 100644 --- a/eo/tutorial/Templates/make_op_MyStruct.h +++ b/eo/tutorial/Templates/make_op_MyStruct.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_MyStruct.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 @@ -19,8 +19,8 @@ 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 + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk */ //----------------------------------------------------------------------------- @@ -35,14 +35,14 @@ // combinations of simple eoOps (eoMonOp and eoQuadOp) #include -/** definition of mutation: +/** definition of mutation: * class eoMyStructMonop MUST derive from eoMonOp */ #include "eoMyStructMutation.h" -/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2): +/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2): * class eoMyStructBinCrossover MUST derive from eoBinOp - * OR + * OR * class eoMyStructQuadCrossover MUST derive from eoQuadOp */ // #include "eoMyStructBinOp.h" @@ -61,9 +61,9 @@ * This function builds the operators that will be applied to the eoMyStruct * * It uses a parser (to get user parameters), a state (to store the memory) - * the last parameter is an eoInit: if some operator needs some info + * the last parameter is an eoInit: if some operator needs some info * about the genotypes, the init has it all (e.g. bounds, ...) - * Simply do + * Simply do * EOT myEO; * _init(myEO); * and myEO is then an ACTUAL object @@ -85,7 +85,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit2) only - no time for the eoBinOp case // you can have more than one - combined in a proportional way - + // first, define the crossover objects and read their rates from the parser - - // A first crossover + + // A first crossover eoQuadOp *cross = new eoMyStructQuadCrossover /* (varType _anyVariable) */; // store in the state _state.storeFunctor(cross); @@ -106,21 +106,21 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit *propXover = + eoPropCombinedQuadOp *propXover = new eoPropCombinedQuadOp(*cross, cross1Rate); // and of course stor it in the state _state.storeFunctor(propXover); - // Optional: A second(and third, and ...) crossover + // Optional: A second(and third, and ...) crossover // of course you must create the corresponding classes // and all ***MUST*** derive from eoQuadOp /* Uncomment if necessary - and replicate as many time as you need - cross = new eoMyStructSecondCrossover(varType _anyVariable); + cross = new eoMyStructSecondCrossover(varType _anyVariable); _state.storeFunctor(cross); - double cross2Rate = _parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value(); - propXover.add(*cross, cross2Rate); + double cross2Rate = _parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value(); + propXover.add(*cross, cross2Rate); */ // if you want some gentle output, the last one shoudl be like // propXover.add(*cross, crossXXXRate, true); @@ -130,12 +130,12 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit *mut = new eoMyStructMutation/* (varType _anyVariable) */; _state.storeFunctor(mut); // its relative rate in the combination @@ -151,8 +151,8 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit(varType _anyVariable); _state.storeFunctor(mut); - double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); - propMutation.add(*mut, mut2Rate); + double mut2Rate = _parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); + propMutation.add(*mut, mut2Rate); */ // if you want some gentle output, the last one shoudl be like // propMutation.add(*mut, mutXXXRate, true); @@ -170,7 +170,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit -/** +/** * Always write a comment in this format before class definition * if you want the class to be documented by Doxygen * - * ATTENTION, class EOT *must* derive from EO, as method invalidate() + * ATTENTION, class EOT *must* derive from EO, as method invalidate() * must be called if the genotypes of the indis is modified */ -template +template class eoMoreOffspringGenOp: public eoGenOp { public: /** * (Default) Constructor. */ - eoMoreOffspringGenOp(paramType _anyParameter) : + eoMoreOffspringGenOp(paramType _anyParameter) : anyParameter(_anyParameter) {} /// The class name. Used to display statistics @@ -52,16 +52,16 @@ public: ++_plop; // advance once for each selected parents ... EOT& parentN = *_plop; // select the last parent - // don't advance after the last one: _plop always - // points to the last that has already been treated + // don't advance after the last one: _plop always + // points to the last that has already been treated // apply operator to the parents (modifying them AND generating - // new individuals ofs1, ofs2, ..., ofsN + // new individuals ofs1, ofs2, ..., ofsN ++_plop; // advance before each insertion _plop.insert(ofs1); ... ++_plop; // advance before each insertion - _plop.insert(ofsN); + _plop.insert(ofsN); // oh right, and invalidate fitnesses of modified parents parent1.invalidate(); diff --git a/eo/tutorial/Templates/stat.tmpl b/eo/tutorial/Templates/stat.tmpl index c53602da..9f807d24 100644 --- a/eo/tutorial/Templates/stat.tmpl +++ b/eo/tutorial/Templates/stat.tmpl @@ -46,7 +46,7 @@ public : } void operator()(const eoPop& _pop){ - double tmpStat(0.); + double tmpStat(0.); // START Code for computing the statistics - in tmpStat // tmpStat = blablabla // END Code for computing the statistics @@ -61,4 +61,3 @@ private : }; #endif - diff --git a/website/index.html b/website/index.html index da004b87..e72daad4 100644 --- a/website/index.html +++ b/website/index.html @@ -22,57 +22,57 @@
Evolving Objects logo @@ -140,7 +140,7 @@
We have lost all the mailing-list subscriptions in a crash, please subscribe again on the eodev-main subscription page.
-

Evolutionary algorithms forms a family of algorithms inspired by the theory of evolution, that solve various problems. +

Evolutionary algorithms forms a family of algorithms inspired by the theory of evolution, that solve various problems. They evolve a set of solutions to a given problem, in order to produce the best results. These are stochastic algorithms, because they iteratively use random processes. The vast majority of these methods are used to solve optimization problems, and may be also called "metaheuristics". @@ -179,10 +179,10 @@

Component-based framework

-

Designing an algorithm with EO consists in choosing what components you want to use for your specific needs, just as building a structure with Lego blocks.

-

If you have a classical problem for which available code exists (for example if you have a black-box problem with real-valued variables), you will just choose components to form an algorithm and connect it to your fitness function (which computes the quality of a given solution).

-

If your problem is a bit more exotic, you will have to code a class that represents how your individuals (a solution to your problem) are represented, and perhaps some variations operators, but most of the other operators (selection, replacement, stopping criteria, command-line interface, etc.) are already available in EO.

-

+

Designing an algorithm with EO consists in choosing what components you want to use for your specific needs, just as building a structure with Lego blocks.

+

If you have a classical problem for which available code exists (for example if you have a black-box problem with real-valued variables), you will just choose components to form an algorithm and connect it to your fitness function (which computes the quality of a given solution).

+

If your problem is a bit more exotic, you will have to code a class that represents how your individuals (a solution to your problem) are represented, and perhaps some variations operators, but most of the other operators (selection, replacement, stopping criteria, command-line interface, etc.) are already available in EO.

+

Main Features

@@ -190,134 +190,134 @@ - - - - + + + +
Examples of problems that you can solve with the help of EO:
- -
- -
- -
Examples of problems that you can solve with the help of EO:
+ +
+ +
+ +
    -
  • Flexible design that permits to easily create virtually any algorithm
  • -
  • Solution representation for continuous and combinatorial problems: -
      -
    • binary-strings,
    • -
    • permutations,
    • -
    • vectors,
    • -
    • easily write your own,
    • -
    • …
    • -
    -
  • -
  • Several algorithm paradigms: -
      -
    • evolution strategies,
    • -
    • genetic algorithms,
    • -
    • estimation of distribution,
    • -
    • particle swarm optimization
    • -
    • …
    • -
    -
  • -
  • Many selection and replacement operators: -
      -
    • rank-based,
    • -
    • deterministic or stochastic tournaments,
    • -
    • roulette,
    • -
    • elitism,
    • -
    • …
    • -
    -
  • -
  • Ready-to-use variations operators: -
      -
    • uniform initializer, -
    • gaussian mutation, -
    • subtree crossover, -
    • …
    • -
    -
  • -
  • Easy combination of several operators: -
      -
    • proportional combination,
    • -
    • sequential call,
    • -
    • …
    • -
    -
  • -
  • Portable and human-readable parameter files
  • -
  • Suspend and load population from files
  • -
  • Versatile checkpointing and logging: -
      -
    • graphical display,
    • -
    • file dump,
    • -
    • various statistics,
    • -
    • signal catching,
    • -
    • …
    • -
    -
  • -
  • Mersenne Twister random number generator (and various distributions)
  • -
  • No useless computation (sparing fitness call, functor-based calls)
  • -
  • Fast running speed, thanks to C++
  • -
  • And more!
  • +
  • Flexible design that permits to easily create virtually any algorithm
  • +
  • Solution representation for continuous and combinatorial problems: +
      +
    • binary-strings,
    • +
    • permutations,
    • +
    • vectors,
    • +
    • easily write your own,
    • +
    • …
    • +
    +
  • +
  • Several algorithm paradigms: +
      +
    • evolution strategies,
    • +
    • genetic algorithms,
    • +
    • estimation of distribution,
    • +
    • particle swarm optimization
    • +
    • …
    • +
    +
  • +
  • Many selection and replacement operators: +
      +
    • rank-based,
    • +
    • deterministic or stochastic tournaments,
    • +
    • roulette,
    • +
    • elitism,
    • +
    • …
    • +
    +
  • +
  • Ready-to-use variations operators: +
      +
    • uniform initializer, +
    • gaussian mutation, +
    • subtree crossover, +
    • …
    • +
    +
  • +
  • Easy combination of several operators: +
      +
    • proportional combination,
    • +
    • sequential call,
    • +
    • …
    • +
    +
  • +
  • Portable and human-readable parameter files
  • +
  • Suspend and load population from files
  • +
  • Versatile checkpointing and logging: +
      +
    • graphical display,
    • +
    • file dump,
    • +
    • various statistics,
    • +
    • signal catching,
    • +
    • …
    • +
    +
  • +
  • Mersenne Twister random number generator (and various distributions)
  • +
  • No useless computation (sparing fitness call, functor-based calls)
  • +
  • Fast running speed, thanks to C++
  • +
  • And more!

Portability

-

EO should work on Windows and any Un*x-like operating system with a - standard-conforming C++ development system.

+

EO should work on Windows and any Un*x-like operating system with a + standard-conforming C++ development system.

-

Recent versions of EO have been tested on the following platforms: -

- -
    -
  • Linux x86 with GCC 3.x and 4.x
  • -
  • Linux x86_64 with GCC 3.x and GCC 4.x
  • -
  • MacOS X/Darwin PowerPC with GCC 3.x
  • -
  • MacOS X/Darwin x86 with GCC 4.x
  • -
  • Microsoft Windows using Cygwin's GCC 3.x (cygming special). -
  • Microsoft Windows using Visual Studio 2003/2005; projects files - are provided.
  • -
  • Solaris SPARC with GCC 3.x
  • -
  • Solaris x86 with GCC 3.x
  • -
+

Recent versions of EO have been tested on the following platforms: +

-

Recent versions of EO uses the CMake portable build system, that permits to easily generate a build chain for your environment.

+
    +
  • Linux x86 with GCC 3.x and 4.x
  • +
  • Linux x86_64 with GCC 3.x and GCC 4.x
  • +
  • MacOS X/Darwin PowerPC with GCC 3.x
  • +
  • MacOS X/Darwin x86 with GCC 4.x
  • +
  • Microsoft Windows using Cygwin's GCC 3.x (cygming special). +
  • Microsoft Windows using Visual Studio 2003/2005; projects files + are provided.
  • +
  • Solaris SPARC with GCC 3.x
  • +
  • Solaris x86 with GCC 3.x
  • +
-

If you have tested EO on a system not listed here, please let - us know.

+

Recent versions of EO uses the CMake portable build system, that permits to easily generate a build chain for your environment.

+ +

If you have tested EO on a system not listed here, please let + us know.

+ +

If you are working on a system with an older C++ compiler there + is a good chance that eo-0.9.3z.1 works. It is tested on Linux + with gcc-2.9x and several systems (IRIX, Solaris) with egcs.

-

If you are working on a system with an older C++ compiler there - is a good chance that eo-0.9.3z.1 works. It is tested on Linux - with gcc-2.9x and several systems (IRIX, Solaris) with egcs.

-

Presentations

- -

A functional and "philosophical" overview of EO was presented at EA'01 conference. - You can download the paper - or the - slides, or browse them right here:

- + +

A functional and "philosophical" overview of EO was presented at EA'01 conference. + You can download the paper + or the + slides, or browse them right here:

+ -

You can also read this - PowerPoint presentation, that shows the EO philosophy. - It includes a Visual Basic macro for evolving objects in Visual Basic - for Applications.

+

You can also read this + PowerPoint presentation, that shows the EO philosophy. + It includes a Visual Basic macro for evolving objects in Visual Basic + for Applications.

+ +

EO is described in the following scientific article:
+

M. Keijzer, J.J. Merelo, G. Romero, G., M. Schoenauer, + "Evolving + objects: A general purpose evolutionary computation + library", Artificial Evolution, 2310, 829--888 (2002).
+

-

EO is described in the following scientific article:
-

M. Keijzer, J.J. Merelo, G. Romero, G., M. Schoenauer, - "Evolving - objects: A general purpose evolutionary computation - library", Artificial Evolution, 2310, 829--888 (2002).
-

-

@Article{Keijzer2001,
@@ -340,187 +340,187 @@

- -

Here is a list of some known publications that used EO:

-
From 3786ba8296a09aa0d99faa34ed82ebcad8fcbe84 Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Fri, 6 May 2011 11:14:39 +0200 Subject: [PATCH 80/81] * apply: needed eoLogger header file inclusion --- eo/src/apply.h | 1 + 1 file changed, 1 insertion(+) diff --git a/eo/src/apply.h b/eo/src/apply.h index 33b354fc..4c09e685 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -28,6 +28,7 @@ #include #include +#include #include #include #include From ceeee7c41ecd36d731efeac709185091651e70be Mon Sep 17 00:00:00 2001 From: Caner Candan Date: Fri, 6 May 2011 16:01:28 +0200 Subject: [PATCH 81/81] * pyeo --- eo/src/pyeo/CMakeLists.txt | 10 +++++----- eo/src/pyeo/test/maxone.py | 2 +- eo/src/pyeo/test/run_tests.sh | 2 -- eo/src/pyeo/test/test_transform.py | 2 +- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/eo/src/pyeo/CMakeLists.txt b/eo/src/pyeo/CMakeLists.txt index 626d0201..ab0e0c1e 100644 --- a/eo/src/pyeo/CMakeLists.txt +++ b/eo/src/pyeo/CMakeLists.txt @@ -27,23 +27,23 @@ INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) -# python IF(APPLE) # osx internal FIND_LIBRARY(APPLE_CARBON Carbon) ENDIF(APPLE) - # includes INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) -INCLUDE_DIRECTORIES(../) +#INCLUDE_DIRECTORIES(../) # source FILE(GLOB SOURCES *.cpp) +# EO dependencies SET(EO_SOURCES - ../eoFunctorStore.cpp - ../utils/eoLogger.cpp + ${EO_SOURCE_DIR}/src/eoFunctorStore.cpp + ${EO_SOURCE_DIR}/src/utils/eoLogger.cpp + ${EO_SOURCE_DIR}/src/utils/eoParallel.cpp ) # shared library diff --git a/eo/src/pyeo/test/maxone.py b/eo/src/pyeo/test/maxone.py index 3544d498..0c4bbd01 100644 --- a/eo/src/pyeo/test/maxone.py +++ b/eo/src/pyeo/test/maxone.py @@ -2,7 +2,7 @@ import sys sys.path.append('..') print 'importing pyeo' -from PyEO import * +from libPyEO import * print 'done' from copy import copy diff --git a/eo/src/pyeo/test/run_tests.sh b/eo/src/pyeo/test/run_tests.sh index f3901050..b06c61b0 100755 --- a/eo/src/pyeo/test/run_tests.sh +++ b/eo/src/pyeo/test/run_tests.sh @@ -5,5 +5,3 @@ do python $i > /dev/null done - - diff --git a/eo/src/pyeo/test/test_transform.py b/eo/src/pyeo/test/test_transform.py index fb70de3e..7359342e 100644 --- a/eo/src/pyeo/test/test_transform.py +++ b/eo/src/pyeo/test/test_transform.py @@ -1,7 +1,7 @@ """Test script for the eoSGATranform class""" from copy import deepcopy -from PyEO import * +from libPyEO import * from maxone import * pop = eoPop()