diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..c1a3ba42c --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# ignore html files +*.html + +# ignore all textual files +*.txt + +# ignore object and archive files +*.[oa] + +# ignore auto-saved files +*~ +\#*\# + +# excepted these manually configured files +!CMakeLists.txt +!README.txt +!application/ +!build/ +!doc/ +!lib/ +!src/ +!test/ +!eompi.html +build/ diff --git a/AUTHORS b/AUTHORS index 4b59b102d..604157f80 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,11 +1,41 @@ -Main developers: +Current maintainers +=================== +Arnaud Liefooghe +Clive Canape +Johann Dreo +Sébastien Verel -Sébastien Cahon +Active developpers +================== +Alexandre Quemy +Benjamin Bouvier +Caner Candan +Pierre Savéant + +Past contributors +================= +atantar +fatene +Gustavo Romero Lopez +jboisson +Jeroen Eggermont +Jochen Küpper +Joost +Juan Julian Merelo Guervos Jérémie Humeau -Arnaud Liefooghe -Sebastien Verel -Nourdine Melab - -Team leader: - -El-Ghazali Talbi +Karima Boufaras +legillon +Louis Da Costa +Loïc Jean David Arjanen +Maarten Keijzer +Marc Schoenauer +Marie-Éleonore +Mostepha Khouadjia +Olivier König +Pedro Angel Castillo Valdivieso +Steve Madere +Sébastien Cahon +Thomas Legrand +Victor Manuel Rivas Santos +wcancino +xohm diff --git a/CMakeLists.txt b/CMakeLists.txt index be2f2a516..b5debc4f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,9 +22,13 @@ if("${CMAKE_CXX_COMPILER}" STREQUAL "" OR "${CMAKE_C_COMPILER}" STREQUAL "") endif() ## Versioning -set(VERSION_MAJOR 2) -set(VERSION_MINOR 0) -set(VERSION_PATCH 1) +set(VERSION_MAJOR 2 CACHE STRING "Major version number" ) +set(VERSION_MINOR 1 CACHE STRING "Minor version number" ) +set(VERSION_PATCH 0 CACHE STRING "Patch version number" ) + +SET(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}" CACHE INTERNAL "Package version" FORCE) +SET(VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}${PROJECT_VERSION_MISC}" CACHE INTERNAL "Global version" FORCE) +SET(GLOBAL_VERSION "${VERSION}") ###################################################################################### ### 2) Check dependencies @@ -51,25 +55,36 @@ include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/Target.cmake) ###################################################################################### ## Paths -set(EO_SRC_DIR "${CMAKE_SOURCE_DIR}/eo" CACHE PATH "ParadisEO-EO source directory" FORCE) -set(EO_BIN_DIR "${CMAKE_BINARY_DIR}/eo" CACHE PATH "ParadisEO-EO binary directory" FORCE) - -set(MO_SRC_DIR "${CMAKE_SOURCE_DIR}/mo" CACHE PATH "ParadisEO-MO source directory" FORCE) -set(MO_BIN_DIR "${CMAKE_BINARY_DIR}/mo" CACHE PATH "ParadisEO-MO binary directory" FORCE) +set( EO_SRC_DIR "${CMAKE_SOURCE_DIR}/eo" CACHE INTERNAL "ParadisEO-EO source directory" FORCE) +set( EO_BIN_DIR "${CMAKE_BINARY_DIR}/eo" CACHE INTERNAL "ParadisEO-EO binary directory" FORCE) -set(MOEO_SRC_DIR "${CMAKE_SOURCE_DIR}/moeo" CACHE PATH "ParadisEO-MOEO source directory" FORCE) -set(MOEO_BIN_DIR "${CMAKE_BINARY_DIR}/moeo" CACHE PATH "ParadisEO-MOEO binary directory" FORCE) +set( EDO_SRC_DIR "${CMAKE_SOURCE_DIR}/edo" CACHE INTERNAL "ParadisEO-EDO source directory" FORCE) +set( EDO_BIN_DIR "${CMAKE_BINARY_DIR}/edo" CACHE INTERNAL "ParadisEO-EDO binary directory" FORCE) -set(SMP_SRC_DIR "${CMAKE_SOURCE_DIR}/smp" CACHE PATH "ParadisEO-SMP source directory" FORCE) -set(SMP_BIN_DIR "${CMAKE_BINARY_DIR}/smp" CACHE PATH "ParadisEO-SMP binary directory" FORCE) +set( MO_SRC_DIR "${CMAKE_SOURCE_DIR}/mo" CACHE INTERNAL "ParadisEO-MO source directory" FORCE) +set( MO_BIN_DIR "${CMAKE_BINARY_DIR}/mo" CACHE INTERNAL "ParadisEO-MO binary directory" FORCE) -set(PEO_SRC_DIR "${CMAKE_SOURCE_DIR}/peo" CACHE PATH "ParadisEO-PEO source directory" FORCE) -set(PEO_BIN_DIR "${CMAKE_BINARY_DIR}/peo" CACHE PATH "ParadisEO-PEO binary directory" FORCE) +set(MOEO_SRC_DIR "${CMAKE_SOURCE_DIR}/moeo" CACHE INTERNAL "ParadisEO-MOEO source directory" FORCE) +set(MOEO_BIN_DIR "${CMAKE_BINARY_DIR}/moeo" CACHE INTERNAL "ParadisEO-MOEO binary directory" FORCE) -set(PROBLEMS_SRC_DIR "${CMAKE_SOURCE_DIR}/problems" CACHE PATH "Problems dependant source directory" FORCE) +set( SMP_SRC_DIR "${CMAKE_SOURCE_DIR}/smp" CACHE INTERNAL "ParadisEO-SMP source directory" FORCE) +set( SMP_BIN_DIR "${CMAKE_BINARY_DIR}/smp" CACHE INTERNAL "ParadisEO-SMP binary directory" FORCE) + +#set( PEO_SRC_DIR "${CMAKE_SOURCE_DIR}/peo" CACHE INTERNAL "ParadisEO-PEO source directory" FORCE) +#set( PEO_BIN_DIR "${CMAKE_BINARY_DIR}/peo" CACHE INTERNAL "ParadisEO-PEO binary directory" FORCE) + +set(PROBLEMS_SRC_DIR "${CMAKE_SOURCE_DIR}/problems" CACHE INTERNAL "Problems dependant source directory" FORCE) set(CMAKE_BASE_SOURCE_DIR ${CMAKE_SOURCE_DIR}) +set(EO_ONLY "false" CACHE BOOL "Only build EO and not the other modules") +set(ENABLE_OPENMP "false" CACHE BOOL "Build EO with the OpenMP support (shared-memory parallel evaluators on multi-core)") +set(ENABLE_GNUPLOT "false" CACHE BOOL "Build EO with the GNUplot support (real-time convergence plotting)") +set(EDO "true" CACHE BOOL "Build the EDO module") +set(EDO_USE_LIB "Eigen3" CACHE STRING "Which linear algebra library to use to build EDO ('UBlas' or 'Eigen3', Eigen3 is recommended)") +set(SMP "false" CACHE BOOL "Build the SMP module") +#set(PEO "true" CACHE BOOL "Build the PEO module") + ## EO Module set(EO_MODULE_NAME "Evolving Object") set(CMAKE_SOURCE_DIR ${EO_SRC_DIR}) @@ -77,28 +92,35 @@ add_subdirectory(${CMAKE_SOURCE_DIR}) if(NOT EO_ONLY) ## MO Module - set(MO_MODULE_NAME "ParadisEO-MO") + set(MO_MODULE_NAME "Moving objects") set(CMAKE_SOURCE_DIR ${MO_SRC_DIR}) add_subdirectory(${MO_SRC_DIR}) + ## EDO Module + if(EDO) + set(EDO_MODULE_NAME "Evolving Distribution Objects") + set(CMAKE_SOURCE_DIR ${EDO_SRC_DIR}) + add_subdirectory(${EDO_SRC_DIR}) + endif() + ## MOEO Module - set(MOEO_MODULE_NAME "ParadisEO-MOEO") + set(MOEO_MODULE_NAME "Multi-Objectives EO") set(CMAKE_SOURCE_DIR ${MOEO_SRC_DIR}) add_subdirectory(${MOEO_SRC_DIR}) - + ## SMP Module if(SMP) - set(SMP_MODULE_NAME "ParadisEO-SMP") + set(SMP_MODULE_NAME "Symmetric Multi-Processing") set(CMAKE_SOURCE_DIR ${SMP_SRC_DIR}) add_subdirectory(${SMP_SRC_DIR}) endif() - + ## PEO Module - if(PEO) - set(PEO_MODULE_NAME "ParadisEO-PEO") - set(CMAKE_SOURCE_DIR ${PEO_SRC_DIR}) - add_subdirectory(${PEO_SRC_DIR}) - endif() + # if(PEO) + # set(PEO_MODULE_NAME "Parallel-EO") + # set(CMAKE_SOURCE_DIR ${PEO_SRC_DIR}) + # add_subdirectory(${PEO_SRC_DIR}) + #endif() endif() ###################################################################################### diff --git a/ForRelease b/ForRelease new file mode 100644 index 000000000..870f6cb84 --- /dev/null +++ b/ForRelease @@ -0,0 +1,45 @@ +In order to create a new release from the current repository, perform the +following steps: + +- If necessary, create a branch named "eo_x.y.z" +- Set version number in eo-conf.cmake +- Check/update NEWS file, set release date and version in NEWS. +- use the "archive_current.sh" script to create the source archive +- Put source archive and packages files at SourceForge +- Update the documentation on the website +- Post news on SourceForge project-page +- Send announcement to mailing lists +- Bump version number to next "x.y.z-edge" in eo-conf.cmake + + +When reaching stable versions: +- prepare a message with the following template: + -----8<----- + A new version of the "Evolving Objects" framework is available. + + EO is a template-based, C++ evolutionary computation library which + helps you to write your own stochastic optimization algorithms + insanely fast. + + Learn more about EO on the official website: + http://eodev.sourceforge.net/ + + You will find the release x.y.z at the following address: + https://sourceforge.net/projects/eodev/files/eo/ + + Here is a summary of the change log: + - XXXXX + - and more… + + Do not hesitate to submit the bugs you will face: + https://sourceforge.net/apps/trac/eodev/wiki/WikiStart + + Happy evolutionary hacking. + -----8<----- +- Post the message to: + - EO news https://sourceforge.net/news/?group_id=9775 + - EO mailing list: eodev-main@lists.sourceforge.net + - ParadisEO mailing list: paradiseo-users@lists.gforge.inria.fr + - EC-digest maling list: ec-digest-l@listserv.gmu.edu + - JET mailing list: jet@inria.fr + diff --git a/INSTALL b/INSTALL index 0deb56950..9734fc95a 100644 --- a/INSTALL +++ b/INSTALL @@ -135,6 +135,17 @@ To enable the compilation of the PEO module, just add -DPEO=true to CMake : > cmake .. -DPEO=true +------------------------------------------------------------------------------------------ +2.3 EDO MODULE +------------------------------------------------------------------------------------------ + +WARNING : The EDO module requires either the Boost::ublas or the Eigen3 library. + +To enable the compilation of the EDO module, just add -DEDO=true to CMake : + +> cmake .. -DEDO=true + + ------------------------------------------------------------------------------------------ 3. DOCUMENTATION ------------------------------------------------------------------------------------------ @@ -145,6 +156,7 @@ Targets are : doc for all documentations doc-eo for building EO documentation doc-mo for MO +doc-edo for MO doc-moeo for MOEO doc-smp for SMP diff --git a/archive_current.sh b/archive_current.sh new file mode 100755 index 000000000..ff710c59e --- /dev/null +++ b/archive_current.sh @@ -0,0 +1,3 @@ +today=`date --iso-8601` +git archive --format zip master > EO-${today}.zip + diff --git a/cmake/Config.cmake b/cmake/Config.cmake index ac6553b54..08063040c 100644 --- a/cmake/Config.cmake +++ b/cmake/Config.cmake @@ -51,13 +51,14 @@ endif(SMP) ###################################################################################### if(INSTALL_TYPE STREQUAL full) - set(ENABLE_CMAKE_EXAMPLE "true" CACHE PATH "ParadisEO examples") - set(ENABLE_CMAKE_TESTING "true" CACHE PATH "ParadisEO tests") + set(ENABLE_CMAKE_EXAMPLE "true" CACHE BOOL "ParadisEO examples") + set(ENABLE_CMAKE_TESTING "true" CACHE BOOL "ParadisEO tests") elseif(INSTALL_TYPE STREQUAL min OR NOT DEFINED INSTALL_TYPE) - set(ENABLE_CMAKE_EXAMPLE "false" CACHE PATH "ParadisEO examples") - set(ENABLE_CMAKE_TESTING "false" CACHE PATH "ParadisEO tests") + set(ENABLE_CMAKE_EXAMPLE "false" CACHE BOOL "ParadisEO examples") + set(ENABLE_CMAKE_TESTING "false" CACHE BOOL "ParadisEO tests") endif() + ###################################################################################### ### 2) Define profiling flags ###################################################################################### @@ -65,7 +66,7 @@ endif() if(PROFILING) set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -pg --coverage" CACHE STRING "" FORCE) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "" FORCE) - set(ENABLE_CMAKE_TESTING "true" CACHE STRING "" FORCE) + set(ENABLE_CMAKE_TESTING "true" CACHE BOOL "" FORCE) endif(PROFILING) ###################################################################################### @@ -81,7 +82,7 @@ endif(ENABLE_CMAKE_TESTING) ### 5) Build examples ? ###################################################################################### -set(ENABLE_CMAKE_EXAMPLE "true" CACHE PATH "ParadisEO examples") +set(ENABLE_CMAKE_EXAMPLE "true" CACHE BOOL "ParadisEO examples") ###################################################################################### ### 6) Determine prefix for installation diff --git a/cmake/Package.cmake b/cmake/Package.cmake index 27b7cab49..f989e45d7 100644 --- a/cmake/Package.cmake +++ b/cmake/Package.cmake @@ -52,7 +52,7 @@ set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README") set(CPACK_PACKAGE_DESCRIPTION "ParadisEO is a white-box object-oriented framework dedicated to the flexible design of metaheuristics. This template-based, ANSI-C++ compliant computation library is portable across both Windows system and sequential platforms (Unix, Linux, Mac OS X, etc.). ParadisEO is distributed under the CeCill license and can be used under several environments.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "A Software Framework for Metaheuristics") -set(CPACK_PACKAGE_VENDOR "Inria") +set(CPACK_PACKAGE_VENDOR "Inria/Thales") set(CPACK_PACKAGE_CONTACT "paradiseo-help@lists.gforge.inria.fr") set(CPACK_PACKAGE_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) set(CPACK_STRIP_FILES ${PACKAGE_NAME}) diff --git a/cmake/Target.cmake b/cmake/Target.cmake index 396d4ac13..a2cd0e584 100644 --- a/cmake/Target.cmake +++ b/cmake/Target.cmake @@ -1,9 +1,9 @@ ###################################################################################### -### Mrproper will delete all files and folders in build directory +### cleanall will delete all files and folders in build directory ###################################################################################### if(UNIX) - add_custom_target(mrproper COMMAND cd ${CMAKE_BINARY_DIR} && rm -rf *) + add_custom_target(cleanall COMMAND cd ${CMAKE_BINARY_DIR} && rm -rf *) endif(UNIX) ###################################################################################### @@ -12,16 +12,18 @@ endif(UNIX) if(DOXYGEN_FOUND AND DOXYGEN_EXECUTABLE) if(SMP) - add_custom_target(doc + add_custom_target(doc COMMAND make doc-eo - COMMAND make doc-mo + COMMAND make doc-edo + COMMAND make doc-mo COMMAND make doc-moeo COMMAND make doc-smp ) else() - add_custom_target(doc + add_custom_target(doc COMMAND make doc-eo - COMMAND make doc-mo + COMMAND make doc-edo + COMMAND make doc-mo COMMAND make doc-moeo ) endif() diff --git a/cmake/module/FindParadiseo.cmake b/cmake/module/FindParadiseo.cmake index 1dd1633f7..0f476e092 100644 --- a/cmake/module/FindParadiseo.cmake +++ b/cmake/module/FindParadiseo.cmake @@ -1,9 +1,8 @@ -# File: FindParadiseo.cmake -# Version: 0.0.1 # # The following variables are filled out: # - PARADISEO_INCLUDE_DIR : EO, MO and MOEO source dir # - EO_INCLUDE_DIR : EO source dir +# - EDO_INCLUDE_DIR : EO source dir # - MO_INCLUDE_DIR : MO source dir # - MOEO_INCLUDE_DIR : MOEO source dir. WARNING : You have ton include MO before ! # - PARADISEO_LIBRARIES : the list of all required modules @@ -13,6 +12,7 @@ # # Here are the components: # - eo +# - edo # - PyEO # - es # - ga @@ -38,7 +38,7 @@ endif() # enabled components if ("${Paradiseo_FIND_COMPONENTS}" STREQUAL "") - set(PARADISEO_LIBRARIES_TO_FIND eo eoutils cma es flowshop ga moeo) + set(PARADISEO_LIBRARIES_TO_FIND eo eoutils edoutils cma es flowshop ga moeo) else() set(PARADISEO_LIBRARIES_TO_FIND ${Paradiseo_FIND_COMPONENTS}) endif() @@ -63,7 +63,11 @@ set(PARADISEO_SRC_PATHS find_path(EO_INCLUDE_DIR eo PATH_SUFFIXES include${INSTALL_SUB_DIR}/eo eo/src PATHS ${PARADISEO_SRC_PATHS}) - + +find_path(EDO_INCLUDE_DIR edo + PATH_SUFFIXES include${INSTALL_SUB_DIR}/edo edo/src + PATHS ${PARADISEO_SRC_PATHS}) + find_path(MO_INCLUDE_DIR mo PATH_SUFFIXES include${INSTALL_SUB_DIR}/mo mo/src PATHS ${PARADISEO_SRC_PATHS}) @@ -71,7 +75,7 @@ find_path(MO_INCLUDE_DIR mo find_path(MOEO_INCLUDE_DIR moeo PATH_SUFFIXES include${INSTALL_SUB_DIR}/moeo moeo/src PATHS ${PARADISEO_SRC_PATHS}) - + # Specific for SMP and PEO foreach(COMP ${PARADISEO_LIBRARIES_TO_FIND}) if(${COMP} STREQUAL "smp") @@ -87,7 +91,7 @@ foreach(COMP ${PARADISEO_LIBRARIES_TO_FIND}) endif() endforeach() -set(PARADISEO_INCLUDE_DIR ${EO_INCLUDE_DIR} ${MO_INCLUDE_DIR} ${MOEO_INCLUDE_DIR}) +set(PARADISEO_INCLUDE_DIR ${EO_INCLUDE_DIR} ${EDO_INCLUDE_DIR} ${MO_INCLUDE_DIR} ${MOEO_INCLUDE_DIR}) if(SMP_FOUND) set(PARADISEO_INCLUDE_DIR ${PARADISEO_INCLUDE_DIR} ${SMP_INCLUDE_DIR}) @@ -116,6 +120,7 @@ set(FIND_PARADISEO_LIB_PATHS #Suffixes set(PARADISEO_LIB_PATHS_SUFFIXES eo/lib + edo/lib mo/lib moeo/lib moeo/tutorial/examples/flowshop/lib #For flowshop library @@ -125,7 +130,7 @@ set(PARADISEO_LIB_PATHS_SUFFIXES lib32 lib64 ) - + foreach(FIND_PARADISEO_COMPONENT ${PARADISEO_LIBRARIES_TO_FIND}) string(TOUPPER ${FIND_PARADISEO_COMPONENT} FIND_PARADISEO_COMPONENT_UPPER) # release library @@ -149,6 +154,7 @@ endforeach() if(PARADISEO_FOUND) message(STATUS "Found ParadisEO includes :") message(${EO_INCLUDE_DIR}) + message(${EDO_INCLUDE_DIR}) message(${MO_INCLUDE_DIR}) message(${MOEO_INCLUDE_DIR}) if(SMP_FOUND) diff --git a/eo/AUTHORS b/deprecated/eo/AUTHORS similarity index 100% rename from eo/AUTHORS rename to deprecated/eo/AUTHORS diff --git a/deprecated/eo/BuildConfig.cmake b/deprecated/eo/BuildConfig.cmake new file mode 100644 index 000000000..bb1af9652 --- /dev/null +++ b/deprecated/eo/BuildConfig.cmake @@ -0,0 +1,44 @@ +# the user should choose the build type on windows environments,excepted under cygwin (default=none) + +#SET(CMAKE_DEFAULT_BUILD_TYPE "Release" CACHE STRING "Variable that stores the default CMake build type" FORCE) + +#SET(CMAKE_BUILD_TYPE Debug) # allows to enable assert calls and -g flag + +FIND_PROGRAM(MEMORYCHECK_COMMAND + NAMES purify valgrind + PATHS + "/usr/local/bin /usr/bin [HKEY_LOCAL_MACHINE\\SOFTWARE\\Rational Software\\Purify\\Setup;InstallFolder]" + DOC "Path to the memory checking command, used for memory error detection.") + +IF(NOT CMAKE_BUILD_TYPE) + SET( CMAKE_BUILD_TYPE + ${CMAKE_DEFAULT_BUILD_TYPE} CACHE STRING + "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel." + FORCE) +ENDIF(NOT CMAKE_BUILD_TYPE) + +IF(WIN32 AND NOT CYGWIN) + IF(CMAKE_CXX_COMPILER MATCHES cl) + IF(NOT WITH_SHARED_LIBS) + IF(CMAKE_GENERATOR STREQUAL "Visual Studio 8 2005" OR CMAKE_GENERATOR STREQUAL "Visual Studio 9 2008") + SET(CMAKE_CXX_FLAGS "/nologo /Gy") + SET(CMAKE_CXX_FLAGS_DEBUG "/W3 /MTd /Z7 /Od") + SET(CMAKE_CXX_FLAGS_RELEASE "/w /MT /O2 /wd4530") + SET(CMAKE_CXX_FLAGS_MINSIZEREL "/MT /O2") + SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "/MTd /Z7 /Od") + SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:CONSOLE") + ENDIF(CMAKE_GENERATOR STREQUAL "Visual Studio 8 2005" OR CMAKE_GENERATOR STREQUAL "Visual Studio 9 2008") + ENDIF(NOT WITH_SHARED_LIBS) + ENDIF(CMAKE_CXX_COMPILER MATCHES cl) +ELSE(WIN32 AND NOT CYGWIN) + IF(CMAKE_COMPILER_IS_GNUCXX) + # SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g -fprofile-arcs -ftest-coverage -Wall -Wextra -Wno-unused-parameter") + SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g -Wall -Wextra -Wno-unused-parameter -Wunknown-pragmas") + SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -Wunknown-pragmas") + SET(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} -O6 -Wunknown-pragmas") + ENDIF(CMAKE_COMPILER_IS_GNUCXX) +ENDIF(WIN32 AND NOT CYGWIN) + +IF(CMAKE_BUILD_TYPE MATCHES Debug) + ADD_DEFINITIONS(-DCMAKE_VERBOSE_MAKEFILE=ON) +ENDIF(CMAKE_BUILD_TYPE MATCHES Debug) diff --git a/deprecated/eo/CHANGELOG b/deprecated/eo/CHANGELOG new file mode 100644 index 000000000..8a518c2f8 --- /dev/null +++ b/deprecated/eo/CHANGELOG @@ -0,0 +1,9882 @@ +Author: Caner Candan +Date: Tue May 10 15:33:42 2011 +0200 + + * NEWS + +Author: Caner Candan +Date: Tue May 10 11:45:37 2011 +0200 + + - old eclipse files + +Author: Caner Candan +Date: Tue May 10 11:44:53 2011 +0200 + + * ConfigureChecks.cmake: issue fixed + +Author: Caner Candan +Date: Tue May 10 10:34:35 2011 +0200 + + - removed useless .cvsignore files since we are using git now + +Author: nojhan +Date: Tue May 10 00:31:18 2011 +0200 + + updated build instructions + +Author: Caner Candan +Date: Mon May 9 17:21:18 2011 +0200 + + + build_gcc_linux_pyeo + +Author: Caner Candan +Date: Mon May 9 17:21:16 2011 +0200 + + * build_gcc_linux_unittest + +Author: Caner Candan +Date: Mon May 9 17:20:33 2011 +0200 + + + build_gcc_linux_stl_parallel + +Author: Caner Candan +Date: Fri May 6 16:01:28 2011 +0200 + + * pyeo + +Author: Caner Candan +Date: Fri May 6 11:14:39 2011 +0200 + + * apply: needed eoLogger header file inclusion + +Author: Caner Candan +Date: Thu May 5 17:15:10 2011 +0200 + + * whitespace cleanup + +Author: Caner Candan +Date: Thu May 5 16:54:00 2011 +0200 + + * indentations + whitespace cleanup + +Author: Caner Candan +Date: Thu May 5 16:53:31 2011 +0200 + + * pyeo/PyEO.cpp: renamed module name + +Author: Caner Candan +Date: Thu May 5 16:53:02 2011 +0200 + + * pyeo/CMakeLists.txt: auto find cpp files + +Author: Caner Candan +Date: Thu May 5 11:47:30 2011 +0200 + + * pyeo cmake config file + +Merge: 7dcc7b6 f984839 +Author: Caner Candan +Date: Wed May 4 17:57:54 2011 +0200 + + Merge branch 'openmp' + +Author: Caner Candan +Date: Tue Mar 15 18:05:45 2011 +0100 + + * edoSampler: sampler method protected + +Author: Caner Candan +Date: Tue Mar 15 16:39:46 2011 +0100 + + * eoLogger: forgot to close opened file + +Author: Caner Candan +Date: Wed May 4 17:29:45 2011 +0200 + + * pyeo: updated pyeo in order to make it works + +Author: Caner Candan +Date: Wed May 4 17:28:46 2011 +0200 + + * eoReduceSplit.h: bad syntax in using eo::log + +Author: Caner Candan +Date: Wed Mar 30 15:52:23 2011 +0200 + + * eoOpContainer: call to eoGenOp::apply instead of operator() to avoid calling reserve + +Author: Caner Candan +Date: Wed Mar 30 15:50:19 2011 +0200 + + * eoEasyEA: pop reserve at each call to algo + +Author: Caner Candan +Date: Thu Mar 24 12:52:27 2011 +0100 + + * switched eoGenOp::apply method from protected to public in order to be visible from eoSequentialOp + +Author: Caner Candan +Date: Wed Mar 23 17:34:35 2011 +0100 + + * eoEasyEA: moved offspring into attributes space in order to avoid memory reallocation when we restart + +Merge: 007aae6 bc30b2c +Author: Caner Candan +Date: Fri Mar 18 11:20:09 2011 +0100 + + Merge branch 'master' into openmp + +Merge: aa23cec 8f6e4b2 +Author: Caner Candan +Date: Fri Mar 18 11:10:59 2011 +0100 + + Merge branch 'master' of ssh://localhost:9001/gitroot/eodev/eodev + +Merge: e7b6b17 16c2e9d +Author: Caner Candan +Date: Fri Mar 18 11:10:14 2011 +0100 + + Merge branch 'openmp' of ssh://localhost:9001/gitroot/eodev/eodev into openmp + +Merge: 9597010 8f6e4b2 +Author: Caner Candan +Date: Mon Mar 14 17:30:46 2011 +0100 + + Merge branch 'master' into openmp + +Author: Caner Candan +Date: Mon Mar 14 17:29:20 2011 +0100 + + * pipecom: added an argument to printf generating a warning + +Merge: cbc44d4 9e95eef +Author: Caner Candan +Date: Tue Mar 8 00:20:37 2011 +0100 + + Merge branch 'openmp' of ssh://eodev.git.sourceforge.net/gitroot/eodev/eodev into openmp + +Merge: 2044d92 90863fd +Author: Caner Candan +Date: Tue Mar 8 00:19:46 2011 +0100 + + Merge branch 'master' into openmp + +Author: Caner Candan +Date: Tue Mar 8 00:08:18 2011 +0100 + + * disabled app/gprop temporary because of the incompatibility with gcc version higher than 4.5.1 + +Merge: 9e95eef aa23cec +Author: Caner Candan +Date: Thu Feb 24 14:29:29 2011 +0100 + + Merge branch 'master' into openmp + +Author: Caner Candan +Date: Thu Feb 24 11:10:47 2011 +0100 + + + added install.cmake to configure dependancies paths + +Author: Caner Candan +Date: Thu Feb 24 11:09:51 2011 +0100 + + * fixed issues on the code to be compatible with last version of boost + +Author: Caner Candan +Date: Thu Feb 24 10:32:13 2011 +0100 + + * application/common/cmakelists.txt: fixed issues with copy of files + +Author: Caner Candan +Date: Tue Feb 8 10:59:00 2011 +0100 + + * eoParallel: added the both parameters enable_results and do_measure + +Author: Caner Candan +Date: Fri Feb 4 16:29:27 2011 +0100 + + * t-openmpy.*: added a header + +Author: Caner Candan +Date: Fri Feb 4 16:28:24 2011 +0100 + + * eoParallel: added the parameter enableResults + +Merge: a733983 2044d92 +Author: Caner Candan +Date: Fri Feb 4 14:10:10 2011 +0100 + + Merge branch 'openmp' of ssh://localhost:9001/gitroot/eodev/eodev into openmp + +Merge: 77a92ff 61faa63 +Author: Caner Candan +Date: Fri Feb 4 14:09:12 2011 +0100 + + Merge branch 'master' into openmp + +Author: Caner Candan +Date: Wed Feb 2 23:50:58 2011 +0100 + + * eoParallel: added the call to omp_set_num_threads to define the number of threads with parameters + +Merge: 54e2a8b 61faa63 +Author: Caner Candan +Date: Fri Jan 28 15:27:24 2011 +0100 + + Merge branch 'master' into openmp + +Author: Caner Candan +Date: Fri Jan 28 14:38:50 2011 +0100 + + * apply.h: size variable missing without openmp + +Author: Caner Candan +Date: Fri Jan 28 11:11:20 2011 +0100 + + * a little update in building script files + +Merge: 4c561f9 36fe44b +Author: Caner Candan +Date: Fri Jan 28 10:43:23 2011 +0100 + + Merge branch 'master' of ssh://eodev.git.sourceforge.net/gitroot/eodev/eodev + +Author: Caner Candan +Date: Thu Jan 27 17:50:11 2011 +0100 + + * removed some warnings + +Merge: db4eda2 9635901 +Author: Caner Candan +Date: Thu Jan 27 14:41:42 2011 +0100 + + Merge branch 'openmp' of ssh://localhost:9001/gitroot/eodev/eodev into openmp + +Author: Caner Candan +Date: Thu Jan 27 14:41:17 2011 +0100 + + * eoParallel: added a missing attribute + +Merge: 4c561f9 32a183e +Author: Caner Candan +Date: Thu Jan 27 13:53:42 2011 +0100 + + Merge branch 'openmp' of ssh://eodev.git.sourceforge.net/gitroot/eodev/eodev into openmp + + Conflicts: + eo/test/CMakeLists.txt + +Author: Johann Dreo +Date: Thu Jan 27 11:59:14 2011 +0100 + + a very simple script to create snapshot of the current head + +Author: Johann Dreo +Date: Thu Jan 27 11:58:21 2011 +0100 + + move edo stuff, that was in the wriong place after the merge, in the edo directory + +Merge: e6ee096 d618ab0 +Author: Johann Dreo +Date: Thu Jan 27 11:36:55 2011 +0100 + + Merge branch 'edo' + +Merge: 12f4f24 8c4b160 +Author: Johann Dreo +Date: Thu Jan 27 11:32:21 2011 +0100 + + Merge branch 'master' of ssh://eodev/gitroot/eodev/eodev + +Author: Johann Dreo +Date: Thu Jan 27 11:23:23 2011 +0100 + + rename everything from 'do' to 'edo' + +Merge: 6e2041d 5fe07ab +Author: Caner Candan +Date: Thu Jan 27 10:49:41 2011 +0100 + + Merge branch 'master' into symlink + +Merge: 3d06d4a 5fe07ab +Author: Caner Candan +Date: Thu Jan 27 10:45:07 2011 +0100 + + Merge branch 'master' into openmp + + Conflicts: + eo/src/eo + +Author: Caner Candan +Date: Thu Jan 27 10:43:13 2011 +0100 + + + eoParallel: nthreads option * apply.h: mangled the openmp code with pre-processing conditions + +Author: Caner Candan +Date: Thu Jan 27 10:39:15 2011 +0100 + + fixed an issue in eoParallel class + + Conflicts: + + eo/src/utils/eoParallel.cpp + +Author: Caner Candan +Date: Tue Dec 28 16:42:53 2010 +0100 + + * updated eoParallel class in order to define the result filename according to the parallelization mode + +Author: Caner Candan +Date: Thu Jan 27 10:35:49 2011 +0100 + + - removed old parallelization parameters from the old-style from eoParser class + + Conflicts: + + eo/src/utils/eoParser.h + +Author: Caner Candan +Date: Thu Jan 27 10:31:28 2011 +0100 + + * changed apply.h to use new parallelization s parameters + + Conflicts: + + eo/src/apply.h + +Author: Caner Candan +Date: Thu Jan 27 10:30:40 2011 +0100 + + added measure into apply function + + Conflicts: + + eo/src/apply.h + +Author: Caner Candan +Date: Thu Jan 27 10:29:09 2011 +0100 + + + 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 + +Author: Caner Candan +Date: Thu Jan 27 10:25:22 2011 +0100 + + add the parser/logger to the general header + + Conflicts: + + eo/src/eo + +Author: Caner Candan +Date: Wed Jan 26 18:10:34 2011 +0100 + + - removed t-eoDualFitness from test/CMakeLists.txt because it fails + + Conflicts: + + eo/test/CMakeLists.txt + +Author: Caner Candan +Date: Thu Dec 23 12:22:29 2010 +0100 + + + add the value() method in eoParam used by dae + +Author: Caner Candan +Date: Wed Dec 22 13:40:49 2010 +0100 + + * package dependancies changed + +Author: Caner Candan +Date: Wed Jan 26 18:09:37 2011 +0100 + + * doc: solved some mistakes + + Conflicts: + + eo/doc/index.h + +Author: Caner Candan +Date: Thu Jan 6 09:16:01 2011 +0100 + + * a little update tu be compatible with gnuplot + +Author: Caner Candan +Date: Wed Jan 5 16:07:08 2011 +0100 + + * --parallelize-prefix parameter description + +Author: Caner Candan +Date: Tue Dec 28 22:54:10 2010 +0100 + + fixed an issue in eoParallel class + +Author: Caner Candan +Date: Tue Dec 28 16:43:44 2010 +0100 + + + added a test file for eoParallel class + +Author: Caner Candan +Date: Tue Dec 28 16:42:53 2010 +0100 + + * updated eoParallel class in order to define the result filename according to the parallelization mode + +Author: Caner Candan +Date: Tue Dec 28 16:41:14 2010 +0100 + + * apply.h: now results stored to a filename defined with parallelization parameters + +Author: Caner Candan +Date: Sun Dec 26 19:19:20 2010 +0100 + + * added eoParallel header inclusion to eo + +Author: Caner Candan +Date: Sun Dec 26 19:13:43 2010 +0100 + + - removed old parallelization parameters from the old-style from eoParser class + +Author: Caner Candan +Date: Sun Dec 26 19:12:20 2010 +0100 + + * updated cmakelists.txt to compile new eoParallel class + +Author: Caner Candan +Date: Sun Dec 26 19:11:00 2010 +0100 + + + created new eoParallel class with a global variable eo::parallel in order to store all parameters tied to parallelization and to access from anywhere + +Author: Caner Candan +Date: Sun Dec 26 19:09:08 2010 +0100 + + * changed apply.h to use new parallelization s parameters + +Author: Caner Candan +Date: Thu Dec 23 23:03:02 2010 +0100 + + added measure into apply function + +Author: Caner Candan +Date: Thu Dec 23 18:09:25 2010 +0100 + + + now you are able to enable or not parallelization with the option --parallelize-loops=1|0 + +Author: Johann Dreo +Date: Thu Dec 16 15:51:28 2010 +0100 + + set the version to 1.1.1-edge + +Author: Johann Dreo +Date: Thu Dec 16 15:50:26 2010 +0100 + + evaluator that throw an exception if a maximum CPU user time has been reached, for POSIX systems + +Author: Johann Dreo +Date: Tue Dec 14 15:27:26 2010 +0100 + + add the parser/logger to the general header + +Merge: df57a10 5fe07ab +Author: Johann Dreo +Date: Wed Jan 26 16:31:55 2011 +0100 + + Merge branch 'master' of ssh://eodev/gitroot/eodev/eodev + +Author: Caner Candan +Date: Thu Jan 20 19:07:41 2011 +0100 + + - removed t-eoDualFitness from test/CMakeLists.txt because it fails + +Merge: 9e93f52 1e177e1 +Author: Johann Dreo +Date: Tue Jan 4 10:42:20 2011 +0100 + + Merge branch 'master' of ssh://eodev/gitroot/eodev/eodev + +Author: Caner Candan +Date: Thu Dec 23 14:31:34 2010 +0100 + + fixed a mistake in cflags setting about openmp flags + +Author: Caner Candan +Date: Thu Dec 23 12:22:29 2010 +0100 + + + add the value() method in eoParam used by dae + +Author: Johann Dreo +Date: Wed Dec 22 18:29:30 2010 +0100 + + const parameter + intermediate reused variable + +Author: Johann Dreo +Date: Wed Dec 22 18:25:44 2010 +0100 + + missing include of the eoLogger header + +Author: Caner Candan +Date: Wed Dec 22 18:23:45 2010 +0100 + + * now symlink script more generic + +Author: Caner Candan +Date: Wed Dec 22 17:25:40 2010 +0100 + + changed cmakelists.txt to generate install symlink script + +Author: Caner Candan +Date: Wed Dec 22 17:24:34 2010 +0100 + + added install_symlink script + +Author: Caner Candan +Date: Wed Dec 22 13:40:49 2010 +0100 + + * package dependancies changed + +Author: Caner Candan +Date: Wed Dec 22 10:25:13 2010 +0100 + + * doc: solved some mistakes + +Author: Johann Dreo +Date: Fri Dec 17 11:25:58 2010 +0100 + + Add a value(ValueType) method for ValueParam, to directly change the value using the templatized type. Use two intermediate streamstring conversions. + +Author: Johann Dreo +Date: Fri Dec 17 10:39:42 2010 +0100 + + eoMaxTimeException is not used only for wallclock time, set a more general message + +Author: Johann Dreo +Date: Thu Dec 16 15:51:28 2010 +0100 + + set the version to 1.1.1-edge + +Author: Johann Dreo +Date: Thu Dec 16 15:50:26 2010 +0100 + + evaluator that throw an exception if a maximum CPU user time has been reached, for POSIX systems + +Author: Johann Dreo +Date: Tue Dec 14 15:27:26 2010 +0100 + + add the parser/logger to the general header + +Author: Caner Candan +Date: Sun Nov 28 14:21:26 2010 +0100 + + now we can select which measures we want + +Author: Caner Candan +Date: Sun Nov 28 13:36:25 2010 +0100 + + using rdtsc for rng seed with mersenne twister + +Author: Caner Candan +Date: Sun Nov 28 03:41:09 2010 +0100 + + update + +Author: Caner Candan +Date: Sun Nov 28 03:35:21 2010 +0100 + + added variable time measure + +Author: Caner Candan +Date: Sun Nov 28 03:32:53 2010 +0100 + + added variable time measure + +Author: Caner Candan +Date: Sun Nov 28 03:24:02 2010 +0100 + + added variable time measure + +Author: Caner Candan +Date: Sun Nov 28 00:19:46 2010 +0100 + + added n processus and fixed bound parameters + +Author: Caner Candan +Date: Sun Nov 28 00:12:08 2010 +0100 + + added n processus and fixed bound parameters + +Author: Caner Candan +Date: Sat Nov 27 23:26:16 2010 +0100 + + onlyexec and onlyprint parameters added on openmp script + +Author: Caner Candan +Date: Sat Nov 27 23:22:54 2010 +0100 + + onlyexec and onlyprint parameters added on openmp script + +Author: Caner Candan +Date: Sat Nov 27 23:07:11 2010 +0100 + + t-openmp.py released + +Author: Caner Candan +Date: Sat Nov 27 21:27:41 2010 +0100 + + changed output results name + +Author: Caner Candan +Date: Sat Nov 27 21:24:07 2010 +0100 + + added t-openmp.py + +Author: Caner Candan +Date: Sat Nov 27 16:19:51 2010 +0100 + + added prefix parameter on t-openmp + +Author: Caner Candan +Date: Mon Nov 22 19:16:09 2010 +0100 + + updated Dp = Tp / TDp + +Author: Caner Candan +Date: Mon Nov 22 18:20:38 2010 +0100 + + remode two - on results filename + +Author: Caner Candan +Date: Mon Nov 22 18:08:58 2010 +0100 + + updated to D_p = T_Dp / T_p and avoid all D_p higher than the number of tasks used + +Author: Caner Candan +Date: Mon Nov 22 17:43:52 2010 +0100 + + popStep and dimStep replaced by pS and dS on the results filename + +Author: Caner Candan +Date: Mon Nov 22 17:37:44 2010 +0100 + + added popStep and dimStep value on the result filename + +Author: Caner Candan +Date: Mon Nov 22 17:35:06 2010 +0100 + + created two boxplot script files one to generate image the other to display with matplotlab + +Author: Caner Candan +Date: Mon Nov 22 17:33:11 2010 +0100 + + removed omp_apply.h and added to apply.h, added dynamicity computation + +Author: Caner Candan +Date: Mon Nov 22 14:47:55 2010 +0100 + + remove threshold parameter and move from static schedule to dynamic + +Author: Caner Candan +Date: Mon Nov 22 14:07:47 2010 +0100 + + added efficienty computation + +Author: Caner Candan +Date: Sat Nov 20 01:57:30 2010 +0100 + + added stepping parameters + +Merge: dab81d1 6625cd2 +Author: Caner Candan +Date: Sat Nov 20 01:08:22 2010 +0100 + + uptodate + +Author: Caner Candan +Date: Sat Nov 20 01:01:45 2010 +0100 + + openmp testing up-to-date + +Author: nojhan +Date: Fri Nov 19 21:08:18 2010 +0100 + + test binary for dual fitness + +Merge: e8a083f 651ba9f +Author: nojhan +Date: Fri Nov 19 21:07:05 2010 +0100 + + Merge branch 'master' of ssh://eodev.git.sourceforge.net/gitroot/eodev/eodev + + Conflicts: + eo/test/CMakeLists.txt + +Author: nojhan +Date: Fri Nov 19 21:03:07 2010 +0100 + + add t-eoDualFitness to CMake + +Author: nojhan +Date: Fri Nov 19 21:02:35 2010 +0100 + + added a method to get the value of a dual fitness + +Author: Caner Candan +Date: Fri Nov 19 11:54:45 2010 +0100 + + new pkg-config file + +Author: Caner Candan +Date: Fri Nov 19 11:50:51 2010 +0100 + + changed pkg-config file creation process + +Author: Caner Candan +Date: Fri Nov 19 11:48:42 2010 +0100 + + openmp test updated + +Author: Caner Candan +Date: Thu Nov 18 10:49:24 2010 +0100 + + added some new scripts to specialize building and a build script for visual studio 2008 + +Author: Caner Candan +Date: Thu Nov 18 10:47:29 2010 +0100 + + forgot to add t-eoParser in test/CMakeLists.txt + +Author: Caner Candan +Date: Wed Nov 17 17:27:55 2010 +0100 + + added a apply.h variant for parallel execution + +Author: Caner Candan +Date: Wed Nov 17 14:43:18 2010 +0100 + + functor operator applying to population in parallel + +Merge: 979a186 8ecef39 +Author: Caner Candan +Date: Wed Nov 17 11:54:07 2010 +0100 + + Merge branch 'master' of ssh://eodev.git.sourceforge.net/gitroot/eodev/eodev + +Author: Caner Candan +Date: Wed Nov 17 11:47:49 2010 +0100 + + unit test for eoParser added + +Author: Caner Candan +Date: Wed Nov 17 11:41:43 2010 +0100 + + fixed unistd.h portability issue + +Author: Johann Dreo +Date: Mon Nov 15 09:30:37 2010 +0100 + + eoDualStatSwitch, a wrapper for computing stats on feasible and unfeasible individuals, separately + +Merge: fb8a8d7 04f12b7 +Author: Johann Dreo +Date: Mon Nov 15 09:14:00 2010 +0100 + + Merge branch 'master' of ssh://eodev/gitroot/eodev/eodev + +Author: Johann Dreo +Date: Mon Nov 15 09:13:39 2010 +0100 + + verify that pop is not empty before attempting to compute the IQR + +Author: Johann Dreo +Date: Mon Nov 15 09:12:10 2010 +0100 + + @todo: add an init method for continuators? + +Author: nojhan +Date: Sun Nov 14 15:24:35 2010 +0100 + + supress some doxygen warnings about \classes + +Author: nojhan +Date: Sun Nov 14 15:11:46 2010 +0100 + + eoInterquartileRangeStat example link to t-eoIQRStat + +Author: nojhan +Date: Sun Nov 14 15:07:50 2010 +0100 + + a test binary for eoInterquartileRangeStat + +Author: Caner Candan +Date: Wed Nov 10 11:18:57 2010 +0100 + + there was a warning from compiler related to a comment syntax in eoInvalidateOps.h + +Author: Johann Dreo +Date: Tue Nov 9 11:44:28 2010 +0100 + + fix most of the doxygen warnings + +Author: Johann Dreo +Date: Mon Nov 8 22:58:37 2010 +0100 + + default log output to debug for the ostream monitor ; better documentation + +Author: Johann Dreo +Date: Mon Nov 8 18:29:25 2010 +0100 + + new eoAerageSizeStat class + +Author: Johann Dreo +Date: Mon Nov 8 18:27:58 2010 +0100 + + check for self assignement in copy operator of eoDualFitness + +Author: Johann Dreo +Date: Mon Nov 8 18:27:19 2010 +0100 + + deactivate gpsymreg that uses the now unsuported multi-objective feature + +Author: Johann Dreo +Date: Sun Nov 7 23:43:58 2010 +0100 + + fix some doxygen warnings + +Author: Johann Dreo +Date: Sun Nov 7 23:16:45 2010 +0100 + + remove multi-objective stuff, deprecated by ParadisEO-PEO + +Author: Johann Dreo +Date: Sun Nov 7 23:12:28 2010 +0100 + + add tests interfaces as examples in the doc ; remove unused test binaries ; some code formating + +Author: Johann Dreo +Date: Sun Nov 7 23:09:35 2010 +0100 + + remove unused test binaries, some code formating + +Author: Johann Dreo +Date: Sun Nov 7 11:19:33 2010 +0100 + + in the doc's main page: brief section first with a link to the modules list + +Author: Johann Dreo +Date: Sat Nov 6 17:31:39 2010 +0100 + + do not documentify: test, tutorial, contrib and app, that are not part of the framework by itself + +Author: Johann Dreo +Date: Sat Nov 6 17:24:00 2010 +0100 + + removing obsolete win directory, we now se CMake that can generate VC++ project files by itself + +Author: nojhan +Date: Sat Nov 6 09:19:17 2010 +0100 + + small fixes in the doc + +Author: Johann Dreo +Date: Fri Nov 5 22:46:15 2010 +0100 + + and finally... still more grouping in documentation. + +Author: Johann Dreo +Date: Fri Nov 5 15:59:35 2010 +0100 + + grouping classes in documentation + +Author: Johann Dreo +Date: Fri Nov 5 14:28:28 2010 +0100 + + name of variables in english ; use the eo::log instead of cerr ; doc grouping + +Author: Johann Dreo +Date: Fri Nov 5 11:26:04 2010 +0100 + + grouping classes in documentation + +Author: Johann Dreo +Date: Tue Nov 2 17:23:27 2010 +0100 + + readable size for the evolutionry algorithm diagram + +Author: Johann Dreo +Date: Tue Nov 2 16:57:13 2010 +0100 + + evolutionary algorithm diagram with lego blocks, fancier + +Author: Johann Dreo +Date: Mon Nov 1 23:08:58 2010 +0100 + + more doc groups, cleaner modules hierarchy + +Author: Johann Dreo +Date: Mon Nov 1 22:09:40 2010 +0100 + + replace TODO comments by @ŧodo doxygen command + +Author: Johann Dreo +Date: Mon Nov 1 22:08:37 2010 +0100 + + more explanations in doc main page, remove HTML markup, remove deprecated link pages + +Author: Johann Dreo +Date: Mon Nov 1 18:20:56 2010 +0100 + + Create more doxygen groups for base classes, clean some doc + +Author: Johann Dreo +Date: Mon Nov 1 18:19:37 2010 +0100 + + delete the obsolete directory (still versionned in the repository if necessary) + +Author: Johann Dreo +Date: Mon Nov 1 15:34:27 2010 +0100 + + grouping algorithms in a module of the doc + +Author: Johann Dreo +Date: Mon Nov 1 13:37:24 2010 +0100 + + added Johann and Caner as authors on the web page + +Author: Johann Dreo +Date: Mon Nov 1 13:32:37 2010 +0100 + + more shortcut links on the webpage, toward the chat and the trac + +Author: Johann Dreo +Date: Sun Oct 31 23:01:16 2010 +0100 + + fix #10: removed MOO binaries + +Author: Johann Dreo +Date: Sun Oct 31 22:57:05 2010 +0100 + + fix #10: removed the moo/ directory and eoMO* classes, deprecated by the Paradiseo-MOEO project + +Author: Johann Dreo +Date: Sun Oct 31 21:57:06 2010 +0100 + + indicate cudacc branch in the changelog + +Merge: fc21827 66b4dfd +Author: Johann Dreo +Date: Sun Oct 31 21:50:15 2010 +0100 + + Merge branch 'cudacc' + +Author: Johann Dreo +Date: Sun Oct 31 21:36:53 2010 +0100 + + remove default values for verbose parameters, so as to make deprecated wrappers unused by default + +Author: Johann Dreo +Date: Sun Oct 31 21:19:34 2010 +0100 + + alternate function prototypes without verbose parameter + +Author: Johann Dreo +Date: Sun Oct 31 07:47:12 2010 +0100 + + changelog summary for the next 1.1 release + +Author: Johann Dreo +Date: Sat Oct 30 23:30:40 2010 +0200 + + fix #13: remove the use of the verbose members, replaced by the eo::log system ; functions prototypes keep their verbose parameters, but display a warning until next version + +Author: Johann Dreo +Date: Tue Oct 26 13:48:47 2010 +0200 + + file not at the right place + +Author: Johann Dreo +Date: Tue Oct 26 13:37:15 2010 +0200 + + replace the changelog with the (cleaned) git log, more up-to-date + +Author: Johann Dreo +Date: Tue Oct 26 13:35:08 2010 +0200 + + renamed in CHANGELOG + +Author: Johann Dreo +Date: Tue Oct 26 13:34:19 2010 +0200 + + warning: not up-to-date + +Author: Johann Dreo +Date: Tue Oct 26 13:32:55 2010 +0200 + + added Johann and Caner as authors + +Author: Johann Dreo +Date: Tue Oct 26 13:32:43 2010 +0200 + + replace the changelog with the (cleaned) git log, more up-to-date + +Author: Johann Dreo +Date: Tue Oct 26 10:51:48 2010 +0200 + + create a more generic class for monitoring to any ostream (useful for output to clog or cerr, for example), the stdout monitor now inherits from it + +Author: Johann Dreo +Date: Mon Oct 25 09:50:50 2010 +0200 + + Stat object to compute ratio of feasible indviduals in a pop using eoDualFitness + +Author: Johann Dreo +Date: Fri Oct 22 10:08:57 2010 +0200 + + a stat object for computing interquartile range (a robust measure of dispersion) + +Author: Johann Dreo +Date: Fri Oct 22 10:07:09 2010 +0200 + + Arithmetic operators (note: priority to unfeasibility) + +Author: Caner Candan +Date: Tue Oct 12 10:09:56 2010 +0200 + + I have fixed some bugs and added some tests for doDistrib classes + +Author: Johann Dreo +Date: Wed Sep 29 22:52:30 2010 +0200 + + using eo::log instead of std::cout + +Author: Caner Candan +Date: Tue Sep 28 10:38:38 2010 +0200 + + there was an issue on doBounderNo class tied to the default values of the ctor of mother class doBounder: fixed + +Author: Caner Candan +Date: Wed Sep 22 19:25:37 2010 +0200 + + * eda n eda_sa: bug fixed, while we were using -h the result folder was removed + +Author: Caner Candan +Date: Wed Sep 22 14:38:15 2010 +0200 + + + eda algo: same algo than eda-sa without sa, + plotting scripts and problem functions moved to application/common + +Author: Johann Dreo +Date: Tue Sep 21 17:53:48 2010 +0200 + + do not explicitely specify build type, use O3 instead of O2 for release + +Author: Johann Dreo +Date: Tue Sep 21 17:52:59 2010 +0200 + + typo variable name + +Author: Caner Candan +Date: Tue Sep 21 15:12:19 2010 +0200 + + + boxplot.py: script to generate graphic with boxplot to illustrate distances between theorical and visual means for each population value + +Author: Caner Candan +Date: Tue Sep 21 15:08:38 2010 +0200 + + + t-mean-distance: program to generate distance value between the theorical and visual means + +Author: Johann Dreo +Date: Mon Sep 20 13:35:51 2010 +0200 + + typofix declaration types in macro + +Author: Johann Dreo +Date: Mon Sep 20 11:32:55 2010 +0200 + + deactivate -fprofile-arcs -ftest-coverage that necessitate gcov + +Author: Johann Dreo +Date: Thu Sep 16 14:16:24 2010 +0200 + + accessors to levels ; typofix on _contextLevel + +Author: Johann Dreo +Date: Thu Sep 16 11:29:32 2010 +0200 + + important note: we are using wallclock time + +Author: Johann Dreo +Date: Thu Sep 16 11:16:55 2010 +0200 + + bugfix operator() signature + +Author: Johann Dreo +Date: Thu Sep 16 11:06:04 2010 +0200 + + evals that can throw exceptions + +Merge: ccd5b01 88b2ec3 +Author: Johann Dreo +Date: Thu Sep 16 09:41:26 2010 +0200 + + Merge branch 'master' of ssh://eodev/gitroot/eodev/eodev + +Author: Johann Dreo +Date: Thu Sep 16 09:33:55 2010 +0200 + + more comments ; header + +Author: Johann Dreo +Date: Thu Sep 16 09:29:51 2010 +0200 + + typo bugfix + +Author: Johann Dreo +Date: Thu Sep 16 09:28:55 2010 +0200 + + use std::endl ; error message format ; more comments + +Author: Johann Dreo +Date: Wed Sep 15 22:53:15 2010 +0200 + + bugfix _keep_existing name ; added an overwriting option to use ios_base::trunc instead of ios_base::app + +Author: Johann Dreo +Date: Wed Sep 15 22:28:58 2010 +0200 + + use eo::log + +Author: Johann Dreo +Date: Wed Sep 15 22:28:29 2010 +0200 + + doc comments + +Merge: 26ac5ca 86b7538 +Author: Caner Candan +Date: Tue Sep 14 14:18:14 2010 +0200 + + Merge branch 'master' of 188.165.44.48:do + +Author: Caner Candan +Date: Tue Sep 14 13:19:43 2010 +0200 + + bugfixed from ublas::vector assignement ctor for old version of boost + +Author: Caner Candan +Date: Mon Sep 13 06:17:44 2010 +0200 + + - screenshots + +Merge: 0f4e43c 6a613bc +Author: Caner Candan +Date: Sat Sep 11 00:21:02 2010 +0200 + + Merge branch 'mo-1.3' of candan.fr:do into mo-1.3 + +Author: Caner Candan +Date: Fri Sep 10 23:21:31 2010 +0200 + + t-doEstimatorNormalMulti: display means and distance + +Author: Caner Candan +Date: Fri Sep 10 17:04:02 2010 +0200 + + * bugfixed on test_cov_parameters + +Author: Caner Candan +Date: Fri Sep 10 15:52:54 2010 +0200 + + replaced generated prefix name in result folder + +Author: Caner Candan +Date: Fri Sep 10 15:48:16 2010 +0200 + + + test_cov_parameters.py: script to execute the estimator testor (t-EstimatorNormalMulti) in using all combinaison parameters values for 2-D cov-matrix + +Author: Caner Candan +Date: Fri Sep 10 01:09:16 2010 +0200 + + + test/t-doEstimatorNormalMulti + +Author: nojhan +Date: Thu Sep 9 22:37:50 2010 +0200 + + update related softwares: + EASEA, GUIDE + +Merge: 15ae721 86b0828 +Author: Caner Candan +Date: Thu Sep 9 13:55:59 2010 +0200 + + Merge branch 'mo-1.3' of git:do into mo-1.3 + +Author: Caner Candan +Date: Thu Sep 9 13:55:18 2010 +0200 + + * added some comments + +Author: Caner Candan +Date: Thu Sep 9 11:53:14 2010 +0200 + + + new screenshot with parameters -P=10000 -d=10 + +Author: Caner Candan +Date: Thu Sep 9 11:24:35 2010 +0200 + + * some updates on gplot.py to have a better display + screenshots from gnuplot + +Author: Caner Candan +Date: Thu Sep 9 08:03:01 2010 +0200 + + * README + +Author: Caner Candan +Date: Thu Sep 9 07:59:50 2010 +0200 + + buxfixed on CMakeLists.txt regarding copying failures + +Author: Caner Candan +Date: Thu Sep 9 07:58:05 2010 +0200 + + renamed scripts filenames + +Author: Caner Candan +Date: Thu Sep 9 07:56:15 2010 +0200 + + * added some features in plot.py plotting script + +Merge: 2e43f47 56680e8 +Author: Johann Dreo +Date: Wed Sep 8 12:15:08 2010 +0200 + + Merge branch 'mo-1.3' of git:do into mo-1.3 + +Author: Johann Dreo +Date: Wed Sep 8 12:14:15 2010 +0200 + + bounder on uniform distribution that can handle different bounds on several dimensions + +Author: Caner CANDAN +Date: Tue Sep 7 15:36:16 2010 +0200 + + * fixed bad using of method moNeighbor< EOT >::init( EOT& ) + +Author: Johann Dreo +Date: Mon Sep 6 12:05:13 2010 +0200 + + bugfix xdebug level + +Author: Johann Dreo +Date: Mon Sep 6 11:20:00 2010 +0200 + + use eo::log instead of cout + +Author: Johann Dreo +Date: Mon Sep 6 10:43:34 2010 +0200 + + no more dummy bounder + +Author: Johann Dreo +Date: Mon Sep 6 10:43:07 2010 +0200 + + constructors for passing the bounder to super class + +Author: Johann Dreo +Date: Mon Sep 6 00:04:37 2010 +0200 + + indent clean, more comments + +Author: Johann Dreo +Date: Sun Sep 5 23:56:17 2010 +0200 + + replace \n with endl + +Author: Johann Dreo +Date: Sun Sep 5 23:42:58 2010 +0200 + + use eo::log instead of cout + +Author: Johann Dreo +Date: Sat Sep 4 23:07:37 2010 +0200 + + some MO types replacement + +Author: Johann Dreo +Date: Fri Sep 3 18:32:27 2010 +0200 + + switch to new MO 1.3 classes and interface + +Author: Johann Dreo +Date: Fri Sep 3 15:55:28 2010 +0200 + + Patch from Karima.Boufaras@inria.fr: compilation wth CUDACC + +Author: nojhan +Date: Fri Sep 3 09:19:23 2010 +0200 + + official xmpp chat room + +Author: Caner Candan +Date: Wed Sep 1 19:15:26 2010 +0200 + + * t-eoLogger: missed some code lines to display correctly the help + +Author: Caner Candan +Date: Wed Sep 1 17:30:50 2010 +0200 + + * packaging: now the test and tutorial binaries are installed in share directory + +Author: Caner Candan +Date: Wed Sep 1 14:51:09 2010 +0200 + + ticket #1: Remove the autotools files done + +Merge: 5bd0baa 7159f8e +Author: Caner Candan +Date: Wed Sep 1 12:07:23 2010 +0200 + + Merge branch 'packaging' of ssh://localhost:9001/gitroot/eodev/eodev + +Author: Caner Candan +Date: Wed Sep 1 12:01:42 2010 +0200 + + eo::log: added the parameter -o in order to define a log file + removed some warning messages at compile time + +Merge: 25bb766 13b9b62 +Author: Caner Candan +Date: Wed Sep 1 10:33:42 2010 +0200 + + Merge branch 'master' of ssh://localhost:8007/do + +Author: Caner Candan +Date: Tue Aug 31 19:29:05 2010 +0200 + + added temporary population sorting + +Author: Caner Candan +Date: Tue Aug 31 19:26:51 2010 +0200 + + * added some useful comments in eoLogger class + +Author: Caner Candan +Date: Tue Aug 31 17:16:48 2010 +0200 + + * main.cpp: removed useless comments * src/do: added some lines to make detectable language file * doEDASA.h: added some comments + +Author: Caner Candan +Date: Tue Aug 31 16:39:21 2010 +0200 + + fixed some warning messages while compiling + +Author: Caner Candan +Date: Tue Aug 31 16:35:50 2010 +0200 + + + eoEvalFuncCounterBounder.h: inherits of eoEvalFuncCounter in adding an exception throwing when a threshold of evaluation has been reached + +Author: Caner Candan +Date: Tue Aug 31 16:34:03 2010 +0200 + + + eoEvalFuncCounterBounder.h: inherits of eoEvalFuncCounter in adding an exception throwing when a threshold of evaluation has been reached + +Author: Caner Candan +Date: Tue Aug 31 16:32:19 2010 +0200 + + + eoEvalFuncCounterBounder.h: inherits of eoEvalFuncCounter in adding an exception throwing when a threshold of evaluation has been reached + +Author: Caner Candan +Date: Tue Aug 31 16:31:39 2010 +0200 + + + eoEvalFuncCounterBounder.h: inherits of eoEvalFuncCounter in adding an exception throwing when a threshold of evaluation has been reached + +Author: Caner Candan +Date: Tue Aug 31 15:53:32 2010 +0200 + + * eoRNG.h: added double uniform(double min, double max) + +Author: Caner Candan +Date: Tue Aug 31 14:56:11 2010 +0200 + + * eoFitContinue: using of _pop.best_element().fitness() instead of pop.nth_element_fitness(0) + +Author: Caner Candan +Date: Tue Aug 31 14:54:42 2010 +0200 + + removed a wrong logging message from eoEvalContinue.h + +Author: Caner Candan +Date: Tue Aug 31 14:52:08 2010 +0200 + + repared some compile warning messages + +Author: Caner Candan +Date: Tue Aug 31 14:15:54 2010 +0200 + + updated doxygen config file to the version 1.6.x + +Author: Caner Candan +Date: Tue Aug 31 14:10:13 2010 +0200 + + * fixed some warning issues during compilation + +Author: Caner Candan +Date: Tue Aug 31 14:06:34 2010 +0200 + + updated doc/CMakeLists.txt in order to add docs in packages + +Author: Caner Candan +Date: Tue Aug 31 14:04:25 2010 +0200 + + removed useless eo.cfg, this is generated automaticaly by cmake with the file eo.cfg.cmake + +Merge: 248d12d 2fdc24a +Author: Johann Dreo +Date: Tue Aug 31 10:22:46 2010 +0200 + + Merge branch 'master' of ssh://eodev/gitroot/eodev/eodev + +Author: Johann Dreo +Date: Mon Aug 30 22:50:59 2010 +0200 + + add eoDualFitness.h to the list of headers + +Author: Johann Dreo +Date: Mon Aug 30 22:50:34 2010 +0200 + + bugfix: typo on _this_ + +Author: Johann Dreo +Date: Mon Aug 30 22:46:55 2010 +0200 + + update of the license headers, LGPL version 2 only for those new files + +Author: Johann Dreo +Date: Mon Aug 30 22:46:37 2010 +0200 + + add a xdebug level & update of the license headers, LGPL version 2 only for this new file + +Author: Johann Dreo +Date: Mon Aug 30 22:44:18 2010 +0200 + + no ; at the end of the line + +Author: Johann Dreo +Date: Mon Aug 30 22:43:50 2010 +0200 + + New class: A fitness class that permits to compare feasible and unfeasible individuals. It guaranties that a feasible individual will always be better than an unfeasible one. + +Author: Johann Dreo +Date: Mon Aug 30 22:42:42 2010 +0200 + + no ; at the end of the line + +Author: Caner Candan +Date: Mon Aug 30 16:20:55 2010 +0200 + + fixed a bug with using of replacor, it didnt reduce the fitness + +Author: nojhan +Date: Sat Aug 28 12:30:37 2010 +0200 + + openhatch button, supposed to facilitate the involvement of new contributors + +Merge: 74b23dd 799a8f0 +Author: Caner Candan +Date: Thu Aug 26 19:54:05 2010 +0200 + + Merge branch 'master' of candan.fr:do + +Author: Caner Candan +Date: Thu Aug 26 19:31:30 2010 +0200 + + ... + +Author: Caner Candan +Date: Wed Aug 25 19:15:32 2010 +0200 + + * removed rho parameter and replaced it by popsize + +Author: Caner Candan +Date: Tue Aug 24 18:40:49 2010 +0200 + + + script to plot on ggobi + +Author: Caner Candan +Date: Tue Aug 24 11:23:55 2010 +0200 + + * LICENSE + +Author: Caner Candan +Date: Tue Aug 24 11:22:06 2010 +0200 + + * fixed remove command issue + +Author: Caner Candan +Date: Tue Aug 24 11:19:31 2010 +0200 + + * pkg-config updated + cmake file + +Author: Caner Candan +Date: Tue Aug 24 10:26:36 2010 +0200 + + + lib utils + +Author: Caner Candan +Date: Mon Aug 23 18:03:44 2010 +0200 + + + multiplot with gnuplot + +Author: Caner Candan +Date: Mon Aug 23 16:14:02 2010 +0200 + + a C header include missed + +Author: Caner Candan +Date: Mon Aug 23 15:56:58 2010 +0200 + + + plot populations by generation - removed dump from doEDASA + +Author: nojhan +Date: Thu Aug 19 22:04:01 2010 +0200 + + more sections to jump to + +Author: nojhan +Date: Thu Aug 19 21:45:19 2010 +0200 + + correct links to sourceforge features + +Author: nojhan +Date: Thu Aug 19 20:38:19 2010 +0200 + + bugfix #2054922: using base_const_iterator::node; + +Author: Caner Candan +Date: Wed Aug 18 19:13:38 2010 +0200 + + added a FIXME + +Author: Caner Candan +Date: Wed Aug 18 18:39:58 2010 +0200 + + * cma-sa name has been replace by eda-sa in the project + +Author: Caner Candan +Date: Wed Aug 18 18:24:16 2010 +0200 + + - useless comments and files removed + +Author: Caner Candan +Date: Wed Aug 18 18:23:01 2010 +0200 + + - useless comments and files removed + +Author: Caner Candan +Date: Wed Aug 18 18:22:28 2010 +0200 + + - useless comments and files removed + +Author: Caner CANDAN +Date: Wed Aug 18 17:30:11 2010 +0200 + + * eoDetSelect: when the call of howmany() returns 0 it is replaced by 1 + +Author: Caner CANDAN +Date: Wed Aug 18 17:18:36 2010 +0200 + + fixed a warning issue at the file eoRealBounds.cpp + +Author: Caner CANDAN +Date: Wed Aug 18 17:06:16 2010 +0200 + + + cpack configuration in order to generate packaging files, to make it easier use the script package_deb and package_rpm + +Author: Caner Candan +Date: Wed Aug 18 13:37:17 2010 +0200 + + - some useless comments + authors in files header + +Merge: 0a37f66 6ec3fc5 +Author: Caner CANDAN +Date: Wed Aug 18 12:16:13 2010 +0200 + + Merge branch 'master' of ssh://localhost:9001/gitroot/eodev/eodev + +Author: Caner Candan +Date: Tue Aug 17 17:44:53 2010 +0200 + + bug fixed + +Author: Johann Dreo +Date: Tue Aug 17 15:11:18 2010 +0200 + + correct headers ; class comment + +Author: Johann Dreo +Date: Tue Aug 17 15:07:17 2010 +0200 + + improved explanations + +Author: Johann Dreo +Date: Tue Aug 17 15:02:39 2010 +0200 + + missing header ; correct copyright ; correct emails + +Author: Johann Dreo +Date: Tue Aug 17 14:59:24 2010 +0200 + + translate variable from french to english + +Author: Johann Dreo +Date: Tue Aug 17 14:56:33 2010 +0200 + + use eo::log ; warning when returns 0 + +Author: Caner Candan +Date: Mon Aug 16 15:38:39 2010 +0200 + + issue to fix + +Author: Caner Candan +Date: Mon Aug 16 11:45:43 2010 +0200 + + added L(i,i) = sqrt( abs(V(i,i) - sum) ) but the issue still exists + +Author: Caner Candan +Date: Mon Aug 16 11:30:06 2010 +0200 + + * added the eo features Continue/CheckOut/Stat to DO in order to dump distribution parameters and to have compatibility with eoMonitor/eoUpdater classes + +Author: Caner Candan +Date: Mon Aug 16 07:52:30 2010 +0200 + + +Author: Caner Candan +Date: Fri Aug 6 10:24:45 2010 +0200 + + added doNormalMono + +Author: Caner Candan +Date: Fri Aug 6 10:19:50 2010 +0200 + + replace doNormal by doNormalMulti + +Merge: f66efcb 36ec42d +Author: Caner Candan +Date: Fri Aug 6 09:50:58 2010 +0200 + + merge + +Merge: 9f4c073 68a03aa +Author: Caner CANDAN +Date: Wed Aug 4 14:10:57 2010 +0200 + + Merge branch 'yaml_load_and_save' of ssh://localhost:9001/gitroot/eodev/eodev + +Author: Caner Candan +Date: Wed Aug 4 14:05:42 2010 +0200 + + * changed some comments sentences + +Author: Caner CANDAN +Date: Wed Aug 4 13:47:51 2010 +0200 + + + feature eoSIGContinue: Continuator can catch user signals + feature eoLogger: flexible logging system for eo + +Author: Caner Candan +Date: Wed Aug 4 13:05:28 2010 +0200 + + +Author: Caner Candan +Date: Tue Aug 3 18:54:41 2010 +0200 + + * cholesky + +Author: Caner Candan +Date: Tue Aug 3 10:35:25 2010 +0200 + + - doDistribParams + +Author: Caner Candan +Date: Tue Aug 3 10:26:15 2010 +0200 + + + some useful files added + +Author: Johann Dreo +Date: Mon Aug 2 17:07:32 2010 +0200 + + code to display only once the message about the help parameter + some indent fix + some more comments + +Author: nojhan +Date: Sun Aug 1 22:27:31 2010 +0200 + + list of some publications + +Author: nojhan +Date: Sun Aug 1 10:55:38 2010 +0200 + + example diagrams now close to features list, with a better legend + +Author: nojhan +Date: Sat Jul 31 23:00:10 2010 +0200 + + better layout for the menu + +Author: nojhan +Date: Sat Jul 31 22:48:49 2010 +0200 + + correct layout in 1024, better spacing for greater resolutions + +Author: nojhan +Date: Sat Jul 31 22:40:04 2010 +0200 + + 'jump to section' links and back links + +Author: nojhan +Date: Sat Jul 31 22:14:09 2010 +0200 + + logo icon for sourceforge, without text, 48px + +Author: nojhan +Date: Sat Jul 31 22:06:27 2010 +0200 + + slides via slideshare, better section order, small design changes + +Author: nojhan +Date: Sat Jul 31 18:59:12 2010 +0200 + + website sources + +Author: nojhan +Date: Thu Jul 29 14:28:05 2010 +0200 + + no more CVSROOT + +Author: Caner Candan +Date: Thu Jul 29 11:22:10 2010 +0200 + + * doc installable + +Author: Caner Candan +Date: Fri Jul 23 13:34:42 2010 +0200 + + + added some useful files + +Author: Caner Candan +Date: Fri Jul 23 13:24:09 2010 +0200 + + + TODO + doStats.cpp + +Author: Caner Candan +Date: Fri Jul 23 13:18:30 2010 +0200 + + * some cleaner updates + +Author: Caner Candan +Date: Tue Jul 13 13:20:07 2010 +0200 + + * doStats * doEstimatorNormal: replaced use of Variance by CoMatrix + +Author: Caner Candan +Date: Tue Jul 6 15:43:15 2010 +0200 + + ... + +Author: Caner Candan +Date: Tue Jul 6 11:25:02 2010 +0200 + + + do.pc + +Author: Caner Candan +Date: Tue Jul 6 10:15:47 2010 +0200 + + * fixed some packaging issues + +Author: Caner Candan +Date: Tue Jul 6 01:31:44 2010 +0200 + + cpack works + +Author: Caner Candan +Date: Tue Jul 6 01:27:14 2010 +0200 + + config cmake + +Author: Caner Candan +Date: Mon Jul 5 20:39:41 2010 +0200 + + + test + +Author: Caner Candan +Date: Mon Jul 5 20:31:30 2010 +0200 + + ... + +Author: Caner Candan +Date: Mon Jul 5 19:42:34 2010 +0200 + + + packaging + cmake files + +Author: Caner Candan +Date: Mon Jul 5 19:06:34 2010 +0200 + + + cma_sa application + +Author: Caner Candan +Date: Mon Jul 5 19:04:35 2010 +0200 + + + do files + +Author: Caner Candan +Date: Mon Jul 5 18:54:55 2010 +0200 + + ... + +Author: paradiseo +Date: Tue Jun 22 09:31:58 2010 +0000 + + Store a result in a variable to have no warning + +Author: paradiseo +Date: Thu Jun 10 10:03:26 2010 +0000 + + Add "Visual Studio 10" in config file for CMake + +Author: stevemadere +Date: Fri May 7 03:17:44 2010 +0000 + + changed YAML saving technique to YAML::Serializable + +Author: stevemadere +Date: Thu May 6 22:46:10 2010 +0000 + + added support to save app/gprop/mlp as YAML + +Author: stevemadere +Date: Tue May 4 17:18:12 2010 +0000 + + configure changes to prepare for use of libyaml-cpp + +Author: (EO team) <(EO team)> +Date: Tue May 4 13:00:51 2010 +0000 + + 'yaml_load_and_save'. + +Author: stevemadere +Date: Tue May 4 13:00:50 2010 +0000 + + Reflecting build process changes in doc and source tree (now using autogen.sh;./configure) + +Author: stevemadere +Date: Tue May 4 12:56:54 2010 +0000 + + Added includes necessary to compile using gcc 4.4 + +Author: stevemadere +Date: Tue May 4 12:54:36 2010 +0000 + + Removed references to eliminated headers eoDummyFlight.h, eoLSPSO.h, eoSSPSO.h + +Author: stevemadere +Date: Tue May 4 12:50:29 2010 +0000 + + Removed reference to Lesson6 until its makefile is fixed + +Author: paradiseo +Date: Thu Mar 18 12:44:45 2010 +0000 + + add an include + +Author: paradiseo +Date: Wed Dec 9 15:49:30 2009 +0000 + + +Author: paradiseo +Date: Thu Jun 25 14:49:53 2009 +0000 + + Accept long time + +Author: paradiseo +Date: Tue Jan 27 16:30:18 2009 +0000 + + little change to delete warnings + +Author: paradiseo +Date: Tue Jan 27 16:28:55 2009 +0000 + + little modif to delete warning + +Author: paradiseo +Date: Tue Jan 27 16:26:44 2009 +0000 + + little change to delete warning + +Author: paradiseo +Date: Tue Jan 27 16:21:53 2009 +0000 + + little modif to delete warning + +Author: paradiseo +Date: Mon Jan 26 14:39:37 2009 +0000 + + Change Compiler flags + +Author: paradiseo +Date: Mon Jan 26 13:43:40 2009 +0000 + + disable warning C4530 (Visual Studio) + +Author: paradiseo +Date: Mon Jan 26 13:38:01 2009 +0000 + + option added to disable warning (mode release with Visual Studio) + +Author: paradiseo +Date: Mon Jan 26 09:07:59 2009 +0000 + + cmake < 2.6 authorized + +Author: paradiseo +Date: Thu Jan 22 10:18:10 2009 +0000 + + test on PSO changed. + +Author: paradiseo +Date: Fri Jan 16 14:29:42 2009 +0000 + + modif cmake + +Author: paradiseo +Date: Wed Jan 14 14:50:46 2009 +0000 + + Cmake configuration modified + +Author: paradiseo +Date: Mon Jan 12 09:14:02 2009 +0000 + + Update to cmake2.6 + modif to support compatibility with icc + +Author: evomarc +Date: Thu Dec 25 16:01:57 2008 +0000 + + Fixing a small glitch that was giving wrong clues to newcomers ... + Thanks to Christophe-Marie Duquesne for the post + +Author: paradiseo +Date: Fri Dec 5 13:55:41 2008 +0000 + + add "=0;" at the end of two virtual method + +Author: paradiseo +Date: Thu Nov 20 16:35:47 2008 +0000 + + remove DartConfig + +Author: paradiseo +Date: Mon Nov 17 10:27:55 2008 +0000 + + Switch from Dart to Dash. + +Author: jeggermo +Date: Tue Nov 11 09:51:17 2008 +0000 + + fixed some very old and stupid problems + +Author: jeggermo +Date: Tue Nov 11 09:50:52 2008 +0000 + + fixed some stupid problems + +Author: maartenkeijzer +Date: Mon May 5 12:33:26 2008 +0000 + + updated configure.in to generate moo files + +Author: tlegrand +Date: Fri Apr 18 12:00:15 2008 +0000 + + deleted "win" directory in the autotools config + +Author: tlegrand +Date: Fri Apr 18 08:59:02 2008 +0000 + + added eoExtendedvelocity (+doc + test) that takes both the local best and the global of a PSO topology into account. Also updated the doc tags for the other topologies and velocities + +Author: tlegrand +Date: Fri Apr 18 08:58:42 2008 +0000 + + imrproved PSO topology/velocity tests + +Author: tlegrand +Date: Fri Apr 18 08:51:38 2008 +0000 + + updated the doc tags + +Author: tlegrand +Date: Fri Apr 18 08:50:22 2008 +0000 + + added eoExtendedvelocity (+doc + test) that takes both the local best and the global of a PSO topology into account. Also updated the doc tags for the other topologies and velocities + +Author: tlegrand +Date: Fri Apr 18 08:19:22 2008 +0000 + + updated a few things about paradiseo (links, docs) + +Author: tlegrand +Date: Fri Apr 18 07:58:17 2008 +0000 + + deleted old and obsolete paradiseo's pdf slides + +Author: paradiseo +Date: Thu Apr 17 14:31:11 2008 +0000 + + new implementation of the test + +Author: paradiseo +Date: Thu Apr 17 14:29:57 2008 +0000 + + Add t-eoOrderXover in the test list + +Author: paradiseo +Date: Thu Apr 17 14:29:10 2008 +0000 + + test of eoOrderXover + +Author: paradiseo +Date: Thu Apr 17 14:26:59 2008 +0000 + + new crossover dedicated to permutation-based representation + +Author: kuepper +Date: Mon Mar 31 19:12:12 2008 +0000 + + start preparation for 1.1 release + +Author: kuepper +Date: Mon Mar 31 19:11:13 2008 +0000 + + Update for gcc-4.3 compatibility + +Author: kuepper +Date: Mon Mar 31 13:35:41 2008 +0000 + + Add climits header as required for gcc-4.3 when using UINT_MAX + +Author: ldacosta +Date: Mon Mar 31 12:53:51 2008 +0000 + + make_continue... just a little formatting + +Author: ldacosta +Date: Fri Mar 28 16:24:17 2008 +0000 + + Output functor is needed if there is screen output OR FILE OUTPUT - until now, it was only created and stored in the screen output was activated. Line 120 of make_checkpoint.h + +Author: ldacosta +Date: Fri Mar 28 16:09:40 2008 +0000 + + Change in do_make_checkpoint: it receives not just a parameter from the evaluation function, not the function itself!! + +Author: ldacosta +Date: Fri Mar 28 15:57:55 2008 +0000 + + Adjusting configuration for Eclipse + +Author: ldacosta +Date: Fri Mar 28 15:51:48 2008 +0000 + + do_make_algo_scalar is extended: now it accepts also an evaluation of the fitness of the population as parameter. + +Author: ldacosta +Date: Fri Mar 28 13:49:14 2008 +0000 + + "Tutorial" conflicts with "tutorial" (in Eclipse), so I try to change names + +Author: ldacosta +Date: Fri Mar 28 13:49:13 2008 +0000 + + "Tutorial" conflicts with "tutorial" (in Eclipse), so I try to change names + +Author: tlegrand +Date: Thu Mar 20 15:48:31 2008 +0000 + + come back to dart.irisa.fr ! + +Author: tlegrand +Date: Thu Mar 20 08:43:44 2008 +0000 + + added minimal test config + +Author: ldacosta +Date: Thu Mar 13 16:28:34 2008 +0000 + + "Tutorial" (with capital T) was interfering with the checkout of eo on Eclipse (because there is already one "tutorial", with "t"). This is just a renaming of "Tutorial". + +Author: tlegrand +Date: Wed Mar 12 15:36:58 2008 +0000 + + replaced ParadisEO links + +Author: tlegrand +Date: Wed Mar 12 15:29:29 2008 +0000 + + replaced ParadisEO links + +Author: tlegrand +Date: Wed Mar 12 15:23:35 2008 +0000 + + added lesson6 + +Author: tlegrand +Date: Wed Mar 12 14:59:03 2008 +0000 + + added lesson 6 subdir + +Author: tlegrand +Date: Tue Mar 11 13:16:35 2008 +0000 + + changed dart server + +Author: tlegrand +Date: Mon Mar 10 14:27:19 2008 +0000 + + added coverage flags + visual studio 9 specific flags + +Author: tlegrand +Date: Thu Mar 6 17:05:16 2008 +0000 + + deleted CMAKE_BUILD_TYPE tags and management + +Author: tlegrand +Date: Wed Mar 5 09:41:24 2008 +0000 + + deleted old customized LL/SS PSO algorithms + +Author: tlegrand +Date: Wed Mar 5 09:06:50 2008 +0000 + + added lesson6 subdir + +Author: tlegrand +Date: Tue Mar 4 14:01:29 2008 +0000 + + Added new lesson (6) dedicated to the PSO. Also changed a few things into the PSO-dedicated components (constructors) + +Author: tlegrand +Date: Tue Feb 26 14:53:32 2008 +0000 + + corrected bad index error when uniform()=0 in roulette_wheel. The error was: if fortune=0, we first have "int i=0", then "return --i" . + +Author: tlegrand +Date: Wed Feb 20 10:07:49 2008 +0000 + + changed nightly start time : EDT -> WEST + +Author: kuepper +Date: Mon Feb 18 20:14:47 2008 +0000 + + fix SF doc-generation, + remove absolute paths + +Author: tlegrand +Date: Mon Feb 18 15:08:08 2008 +0000 + + added nighlty start date for Dart config + +Author: tlegrand +Date: Mon Feb 18 14:43:09 2008 +0000 + + set new gcc warning flags -Wall & -Wextra (deleted the others) + +Author: tlegrand +Date: Fri Feb 15 13:10:06 2008 +0000 + + Replaced "_isOneIndexed" boolean by an unsigned "_startFrom" + +Author: tlegrand +Date: Fri Feb 15 12:50:58 2008 +0000 + + Completed eoInitPermutation: CTor now has a "isOneIndexed" parameter to assign 1..Indi_size as genotype values instead of 0..Indi_size + +Author: tlegrand +Date: Thu Feb 14 09:08:42 2008 +0000 + + added "IF(ENABLE_CMAKE_TESTING)" to add test only if they have been enabled + +Author: tlegrand +Date: Thu Feb 14 08:39:41 2008 +0000 + + Added DartConfig for Dart reporting. By default CTest will submit to dart.irisa.fr (project ParadisEO). + +Author: tlegrand +Date: Thu Feb 14 08:28:47 2008 +0000 + + Added cl compiler flags + new DartConfig + +Author: tlegrand +Date: Thu Feb 14 08:23:48 2008 +0000 + + set warning flags to OFF + +Author: tlegrand +Date: Thu Feb 14 08:23:16 2008 +0000 + + deleted cxx flags for cl compiler. They have been moved to the CMakeLists.txt at the top level + +Author: paradiseo +Date: Thu Jan 24 08:35:11 2008 +0000 + + Addition of a method sort for PSO + +Author: paradiseo +Date: Fri Jan 18 09:49:16 2008 +0000 + + Modification of cotinuator.h + +Author: tlegrand +Date: Thu Jan 17 13:08:21 2008 +0000 + + added generic continuator for tests. just an "continuator" class extended by eoContinue. No impact for the rest. + +Author: tlegrand +Date: Wed Jan 16 08:30:38 2008 +0000 + + removed bad semicolon at the end of a "{}" bloc which is not a class/template/struct. + Debugged using g++ flags + +Author: tlegrand +Date: Wed Jan 16 08:14:18 2008 +0000 + + corrected contructor parameter names. All tests OK + +Author: tlegrand +Date: Tue Jan 15 13:57:32 2008 +0000 + + renamed "globalBest" parameter in "globalBest" function ... + +Author: tlegrand +Date: Tue Jan 15 13:53:18 2008 +0000 + + removed bad semicolon at the end of a "{}" bloc which is not a class/template. + Debugged using g++ flags (see CMakeLists.txt at the root) + +Author: tlegrand +Date: Tue Jan 8 15:34:43 2008 +0000 + + corrected weight factor and updated doc + +Author: tlegrand +Date: Tue Jan 8 15:13:32 2008 +0000 + + corrected PSO dummy errors and completed documentation + +Author: tlegrand +Date: Tue Jan 8 14:50:13 2008 +0000 + + corrected PSO dummy errors and completed documentation + +Author: evomarc +Date: Sat Dec 8 15:05:51 2007 +0000 + + Added the GDB trick to visualize the components of a vector + (but it still doesn't work with EO objects, though???) + +Author: evomarc +Date: Sat Dec 8 14:49:52 2007 +0000 + + 3 identical typos in 3 different files :-) + +Author: tlegrand +Date: Mon Nov 26 08:00:25 2007 +0000 + + Warning: A '_WINDOWS' definition is added to compile four Unix-dedicated files (eoCtrlCContinue.h,eoCtrlCContinue.cpp, pipecom.h, pipecom.cpp). The same definition should be added in the automake configuration file to ensure the compatibility. + +Author: tlegrand +Date: Mon Nov 26 07:56:08 2007 +0000 + + added definition _WINDOWS for (mingw and others) compatibility + +Author: maartenkeijzer +Date: Mon Nov 12 16:23:57 2007 +0000 + + Updated makefiles, updated the moo stuff and cleaned up some stuff that refused to compile + +Author: tlegrand +Date: Mon Nov 12 15:48:56 2007 +0000 + + indented file + +Author: tlegrand +Date: Mon Nov 12 15:46:42 2007 +0000 + + completed with pso new components + +Author: tlegrand +Date: Mon Nov 12 15:45:27 2007 +0000 + + completed pso topologies+velocities + +Author: tlegrand +Date: Mon Nov 12 15:43:43 2007 +0000 + + added pso initializer+ integerVelocity + +Author: tlegrand +Date: Mon Nov 12 15:41:46 2007 +0000 + + added permutation init + +Author: tlegrand +Date: Mon Nov 12 15:41:09 2007 +0000 + + added permut components + +Author: tlegrand +Date: Thu Oct 11 14:14:10 2007 +0000 + + added test for permutation components + +Author: tlegrand +Date: Thu Oct 11 14:10:27 2007 +0000 + + added generic parameter for sigmoid function + +Author: tlegrand +Date: Thu Oct 11 14:08:41 2007 +0000 + + added new tests + +Author: tlegrand +Date: Thu Oct 11 14:08:06 2007 +0000 + + added PSO ring topology test + +Author: tlegrand +Date: Thu Oct 11 14:03:18 2007 +0000 + + added PSO ring topology + +Author: tlegrand +Date: Mon Oct 8 15:33:46 2007 +0000 + + *** empty log message *** + +Author: tlegrand +Date: Mon Oct 8 15:22:25 2007 +0000 + + added best position updating + printOn + +Author: tlegrand +Date: Thu Oct 4 15:10:11 2007 +0000 + + added autoconf > 2.6 compatibility + +Author: kuepper +Date: Tue Sep 25 21:29:31 2007 +0000 + + add coding cookies for Emacs and vim + +Author: maartenkeijzer +Date: Sun Sep 23 08:37:09 2007 +0000 + + added patched tcc source tree + +Author: maartenkeijzer +Date: Sun Sep 23 08:35:51 2007 +0000 + + updated include dependencies + +Author: tlegrand +Date: Wed Sep 19 11:45:19 2007 +0000 + + Added #ifdef HAVE_GNUPLOT for Windows compatibility + +Author: tlegrand +Date: Wed Sep 19 11:44:39 2007 +0000 + + Added eoNSGA_II classes in eomoo lib + +Author: tlegrand +Date: Wed Sep 19 11:41:08 2007 +0000 + + Forget gprop application under Visual Studio + +Author: tlegrand +Date: Wed Sep 19 11:40:31 2007 +0000 + + Several fixes + +Author: tlegrand +Date: Wed Sep 19 11:32:47 2007 +0000 + + Added basic CMake file + +Author: tlegrand +Date: Tue Sep 18 15:40:31 2007 +0000 + + Avoid EONSGA in the lib (errors with Windows/MVS) + +Author: tlegrand +Date: Tue Sep 18 15:12:22 2007 +0000 + + Completed CMake config + +Author: tlegrand +Date: Fri Sep 14 14:47:15 2007 +0000 + + Corrected missing eo.doxytag + +Author: tlegrand +Date: Thu Sep 13 15:13:15 2007 +0000 + + removed --force-missing option for Automake: incompatible with the latest versions + +Author: tlegrand +Date: Thu Sep 13 13:36:13 2007 +0000 + + Added cmake support, deleted Autoconf/Automake stuff and made an easy-to-use process + +Author: tlegrand +Date: Tue Sep 11 14:20:16 2007 +0000 + + Changed file format (to avoid Visual Studio errors): MAC --> DOS + +Author: tlegrand +Date: Tue Sep 11 13:59:49 2007 +0000 + + Added HAVE_GNUPLOT checking + +Author: maartenkeijzer +Date: Mon Sep 10 10:30:53 2007 +0000 + + Various changes and optimizations + +Author: maartenkeijzer +Date: Thu Sep 6 08:15:22 2007 +0000 + + Woops, used the wrong sort here + +Author: maartenkeijzer +Date: Wed Sep 5 13:52:17 2007 +0000 + + added eoFuncPtrStat, and appended various addTo member functions for more elegant definition of monitors, stats, checkpoints, etc + +Author: maartenkeijzer +Date: Wed Sep 5 11:36:44 2007 +0000 + + added eoFuncPtrStat, and appended various addTo member functions for more elegant definition of monitors, stats, checkpoints, etc + +Author: maartenkeijzer +Date: Tue Sep 4 15:30:42 2007 +0000 + + added eoEpsMOEA support + +Author: maartenkeijzer +Date: Tue Sep 4 15:26:45 2007 +0000 + + added epsilon moea + +Author: maartenkeijzer +Date: Tue Sep 4 13:44:41 2007 +0000 + + made fitness() query return const reference + +Author: maartenkeijzer +Date: Tue Sep 4 13:44:02 2007 +0000 + + removed const qualifier from choice() member + +Author: maartenkeijzer +Date: Tue Sep 4 07:50:31 2007 +0000 + + Added member to get to the embedded fitness object + +Author: maartenkeijzer +Date: Tue Sep 4 07:47:46 2007 +0000 + + Added reinitialization of fitness when fitness is invalidated. Needed this to clear worths in multi-objective case + +Author: maartenkeijzer +Date: Mon Sep 3 14:37:27 2007 +0000 + + several fixes + +Author: maartenkeijzer +Date: Fri Aug 31 14:12:54 2007 +0000 + + more bugfixes + +Author: maartenkeijzer +Date: Fri Aug 31 14:03:35 2007 +0000 + + changed eoTruncate to use sort. nth_element leads to weird results in moo case + +Author: maartenkeijzer +Date: Fri Aug 31 13:45:46 2007 +0000 + + made stuff virtual + +Author: maartenkeijzer +Date: Fri Aug 31 13:27:40 2007 +0000 + + Refactoring + +Author: maartenkeijzer +Date: Fri Aug 31 13:26:41 2007 +0000 + + updated nsga + +Author: maartenkeijzer +Date: Fri Aug 31 12:59:18 2007 +0000 + + refactoring + +Author: maartenkeijzer +Date: Fri Aug 31 11:19:26 2007 +0000 + + hmm not a good idea to replace with dummy + +Author: maartenkeijzer +Date: Fri Aug 31 11:08:25 2007 +0000 + + update needed for multi-objective approach + +Author: maartenkeijzer +Date: Fri Aug 31 11:05:59 2007 +0000 + + updated comments + +Author: maartenkeijzer +Date: Fri Aug 31 10:57:05 2007 +0000 + + added new multi-objective support + +Author: maartenkeijzer +Date: Fri Aug 31 06:47:39 2007 +0000 + + fixed bug in NSGA-II, only niching on last objective + +Author: maartenkeijzer +Date: Thu Aug 30 22:30:52 2007 +0000 + + fixed bug in NSGA-II, only niching on last objective + +Author: kuepper +Date: Wed Aug 22 07:30:47 2007 +0000 + + eoRNG.h (eoRng::random): Add comment on truncation as standard way of + floating point to integer conversion. + +Author: kuepper +Date: Tue Aug 21 14:52:50 2007 +0000 + + Fix according to + [ 1663606 ] eoBitOp vector access + +Author: kuepper +Date: Tue Aug 21 14:50:55 2007 +0000 + + Fix wrong removalr of necessary include statement + +Author: kuepper +Date: Tue Aug 21 14:47:14 2007 +0000 + + Correctly round towards zero in random(uint32_t) + +Author: kuepper +Date: Tue Aug 21 14:44:41 2007 +0000 + + Minor cleanup + +Author: kuepper +Date: Tue Aug 21 13:58:53 2007 +0000 + + Fix typos + +Author: maartenkeijzer +Date: Sat Aug 11 20:48:07 2007 +0000 + + brought gprop into 21st century + +Author: tlegrand +Date: Fri Aug 10 14:31:04 2007 +0000 + + added #ifdef SIGQUIT for windows compatibility + +Author: tlegrand +Date: Fri Aug 10 14:30:26 2007 +0000 + + added #define _MSC_VER_ for windows compatibility + +Author: tlegrand +Date: Fri Aug 10 14:29:12 2007 +0000 + + added CMake configuration files + +Author: tlegrand +Date: Fri Aug 10 14:27:12 2007 +0000 + + added CMake configuration file + +Author: xohm +Date: Thu Aug 2 10:48:20 2007 +0000 + + Add extra functionwrapper to member 'size' + +Author: xohm +Date: Thu Aug 2 10:47:15 2007 +0000 + + Excluded 'config.h' from windows build + +Author: xohm +Date: Thu Aug 2 10:46:07 2007 +0000 + + Add static var-declaration + +Author: xohm +Date: Thu Aug 2 10:45:12 2007 +0000 + + Cmake multiplattform buildfile + +Author: xohm +Date: Thu Aug 2 10:15:13 2007 +0000 + + *** empty log message *** + +Author: maartenkeijzer +Date: Tue Jul 17 13:03:29 2007 +0000 + + comments removed + +Author: maartenkeijzer +Date: Tue Jul 17 13:01:00 2007 +0000 + + Adding timed continuator + +Author: tlegrand +Date: Tue Jul 3 09:13:07 2007 +0000 + + added doc details to recognize particle swarm optimization + +Author: tlegrand +Date: Mon Jul 2 13:05:14 2007 +0000 + + added t-eoEasyPSO test + +Author: tlegrand +Date: Mon Jul 2 13:02:26 2007 +0000 + + added myself in the author list :-)) + +Author: tlegrand +Date: Mon Jul 2 13:01:49 2007 +0000 + + particle-swarm-optimization includes added + +Author: tlegrand +Date: Mon Jul 2 13:00:48 2007 +0000 + + removed unconsitent reference in "eoWeakElitistReplacement" (const EOT oldChamp) + +Author: tlegrand +Date: Mon Jul 2 12:59:49 2007 +0000 + + "dMatrix distMatrix(pSize*(pSize-1)/2)" replaced by "distMatrix(pSize) " + +Author: tlegrand +Date: Mon Jul 2 12:58:13 2007 +0000 + + particle-swarm-optimization main templates added + +Author: tlegrand +Date: Mon Jun 25 09:38:44 2007 +0000 + + PSO package - contains src+doc+examples and build process files - should be removed before integrating sources + +Author: maartenkeijzer +Date: Tue Jun 19 17:48:16 2007 +0000 + + Re-enabled declone flag (seemed to be commented out for some reason) + +Author: jeggermo +Date: Thu May 3 14:00:50 2007 +0000 + + All debug (dll and non-dll libs) and release libs are placed in either debug or release + +Author: jeggermo +Date: Thu May 3 13:54:27 2007 +0000 + + Added Multi-Threaded DLL projects settings for both deebug and release + +Author: kuepper +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. + +Author: kuepper +Date: Tue Jan 23 22:25:57 2007 +0000 + + bump versions to 1.0.2-cvs + +Author: kuepper +Date: Tue Jan 23 22:23:31 2007 +0000 + + *** empty log message *** + +Author: kuepper +Date: Tue Jan 23 22:09:17 2007 +0000 + + updates for 1.0.1 release + +Author: evomarc +Date: Wed Jan 17 05:31:05 2007 +0000 + + Slightly modified the README.tmpl for more help to first-timers + +Author: kuepper +Date: Tue Jan 16 08:28:24 2007 +0000 + + Add instructions for bash. + +Author: kuepper +Date: Sun Jan 14 18:56:31 2007 +0000 + + * createEOproject.sh: Set TargetDir to /tmp/. This is a workaround + 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. + +Author: kuepper +Date: Sun Jan 14 18:13:40 2007 +0000 + + State more explicitly what a "complete installation" means. + +Author: kuepper +Date: Fri Dec 29 14:16:01 2006 +0000 + + Update after release + +Author: kuepper +Date: Mon Dec 18 18:56:05 2006 +0000 + + (EXTRA_DIST): Add README's + +Author: kuepper +Date: Mon Dec 18 18:51:12 2006 +0000 + + Update for release. + +Author: jeggermo +Date: Mon Dec 18 16:21:38 2006 +0000 + + Small changes to 2 readme files to stress that the release version are in + eo\win\lib\release and the debug versions in eo\win\lib\debug + +Author: kuepper +Date: Mon Dec 18 12:18:32 2006 +0000 + + * index.h: Add old ToDos + +Author: kuepper +Date: Mon Dec 18 11:19:53 2006 +0000 + + *** empty log message *** + +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 +Date: Sun Dec 17 23:18:33 2006 +0000 + + update + +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 +Date: Sun Dec 17 22:56:03 2006 +0000 + + Remove these, potentially confusing files + +Author: kuepper +Date: Sun Dec 17 22:50:26 2006 +0000 + + Added new README. + Removed old unnecesary files + +Author: kuepper +Date: Sat Dec 16 22:05:17 2006 +0000 + + * Makefile.am (EXTRA_DIST): Distribute exactly the necessary files + +Author: kuepper +Date: Sat Dec 16 22:01:46 2006 +0000 + + * Makefile.am (EXTRA_DIST): Distribute exactly the necessary files + +Author: kuepper +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. + +Author: uid24343 +Date: Thu Dec 7 21:54:48 2006 +0000 + + clean up + +Author: kuepper +Date: Thu Dec 7 21:36:33 2006 +0000 + + cleanup for release + +Author: kuepper +Date: Tue Dec 5 08:42:39 2006 +0000 + + set version to 1.0-cvs again + +Author: kuepper +Date: Tue Dec 5 08:41:24 2006 +0000 + + (EXTRA_DIST): Add new MSVC project files to distribution. + +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 +Date: Mon Dec 4 21:55:31 2006 +0000 + + (eoRng::normal(stdev)): Revert erroneous change. + +Author: kuepper +Date: Sun Dec 3 11:57:34 2006 +0000 + + Fixupper/lowercase issues + +Author: kuepper +Date: Sun Dec 3 11:44:38 2006 +0000 + + fix html errors + +Author: kuepper +Date: Sun Dec 3 11:40:25 2006 +0000 + + update + +Author: kuepper +Date: Sun Dec 3 11:24:41 2006 +0000 + + update, add link to Niko Hansen's comparison + +Author: kuepper +Date: Sun Dec 3 10:53:29 2006 +0000 + + update version number of next release + +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. + +Author: evomarc +Date: Sun Dec 3 07:21:44 2006 +0000 + + Added a note to avoid that some dishonest researchers use teh code + in this tutorial as a basis for comparing their algorithms with "EAs" + as was done for the LEM3 algorithm in GECCO 2006. + +Author: kuepper +Date: Sat Dec 2 12:15:29 2006 +0000 + + update + +Author: kuepper +Date: Sat Dec 2 11:46:34 2006 +0000 + + cleanup, docs + +Author: kuepper +Date: Sat Dec 2 11:36:29 2006 +0000 + + (VirusShiftMutation::operator()): Fix test for i>1. + This makes t-MGE1bit pass on x86_64 using GCC. + +Author: kuepper +Date: Sat Dec 2 11:32:00 2006 +0000 + + Change float to double. + +Author: kuepper +Date: Sat Dec 2 11:02:13 2006 +0000 + + Remove unnecessary tests. + +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. + +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 +Date: Fri Dec 1 21:07:55 2006 +0000 + + minor typos + +Author: kuepper +Date: Fri Dec 1 20:40:54 2006 +0000 + + Use C++ style cast. + +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 +Date: Fri Dec 1 10:49:47 2006 +0000 + + minor cleanup of code and docs, + resolve some compiler warnings + +Author: okoenig +Date: Fri Dec 1 08:42:54 2006 +0000 + + Replaced float vars with double to avoid conversion warnings on VS 8.0 + +Author: kuepper +Date: Wed Nov 29 23:47:40 2006 +0000 + + update for release + +Author: kuepper +Date: Wed Nov 29 23:37:29 2006 +0000 + + Generally include + +Author: okoenig +Date: Tue Nov 28 17:14:05 2006 +0000 + + Removing MAC line endings, because Windows VS 8.0 does not accept them. + +Author: okoenig +Date: Tue Nov 28 17:12:21 2006 +0000 + + Added additonal definition for operator< between fitness and ScalarType. Needed for compilation with VS 8.0. + +Author: jeggermo +Date: Mon Nov 20 13:34:28 2006 +0000 + + Added Solution and Project files for MSVC 2003 + +Author: jeggermo +Date: Mon Nov 20 13:25:46 2006 +0000 + + Changed some files for compatibility with MSVC 2003 and 2005 + +Author: kuepper +Date: Thu Nov 16 13:21:41 2006 +0000 + + include + +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. + +Author: kuepper +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 + eoParser::readFrom. + +Author: kuepper +Date: Tue Jun 13 13:35:26 2006 +0000 + + update + +Author: kuepper +Date: Mon Mar 27 18:55:20 2006 +0000 + + Fix using directives for gcc-4.1 + +Author: maartenkeijzer +Date: Sun Mar 26 13:33:25 2006 +0000 + + fixed t-eoCMAES.cpp test + +Author: kuepper +Date: Sun Mar 26 10:04:01 2006 +0000 + + Update docs, some cleanup + +Author: kuepper +Date: Sat Mar 25 13:03:45 2006 +0000 + + Start list of publications + +Author: kuepper +Date: Thu Mar 23 18:06:10 2006 +0000 + + Fix spelling + +Author: kuepper +Date: Thu Mar 23 10:15:17 2006 +0000 + + update Makefile.am foe eoPeriodicContiunue addition + +Author: maartenkeijzer +Date: Mon Mar 6 20:47:28 2006 +0000 + + making dimensionality requirement optional + +Author: maartenkeijzer +Date: Mon Mar 6 20:31:03 2006 +0000 + + making dimensionality requirement optional + +Author: cahon +Date: Tue Feb 28 14:40:37 2006 +0000 + + Adding a continuator + +Author: cahon +Date: Tue Feb 28 14:39:45 2006 +0000 + + New continuation strategy + +Author: evomarc +Date: Wed Feb 22 04:53:20 2006 +0000 + + Corrected a few typos, and acknowledged the fact that all Lessons are now + compiled within the installation procedure... + +Author: maartenkeijzer +Date: Mon Jan 23 15:12:49 2006 +0000 + + updated makefile to boost-python3.3 and python2.4 + +Author: evomarc +Date: Mon Jan 2 14:09:22 2006 +0000 + + Changed some bug in never-used-except-in-make_algo_easea.h file + (probably some change in the compiler made this stop working ???) + +Author: cahon +Date: Fri Dec 9 17:49:43 2005 +0000 + + eoGenContinue is now persistent + +Author: cahon +Date: Fri Dec 9 17:45:56 2005 +0000 + + eoContinue is now persistent + +Author: kuepper +Date: Wed Dec 7 15:51:32 2005 +0000 + + fix build for our FC4 systems + +Author: kuepper +Date: Wed Dec 7 15:40:23 2005 +0000 + + fixes for gcc-4 compilation -- still have a linker problem + +Author: maartenkeijzer +Date: Thu Nov 24 09:38:05 2005 +0000 + + kd + +Author: maartenkeijzer +Date: Thu Nov 24 09:35:34 2005 +0000 + + Various bugfixes and additions + +Author: evomarc +Date: Tue Nov 8 11:34:12 2005 +0000 + + Removed the "using eoMonitor::vec from eoGnuplot1DMonitor.h because it generated + an internal compiler error with gcc4.0.0. + Repalced all occurences of "vec" by "this->vec" in eoGnuplot1DMonitor.cpp + so it is understood by the compiler :-( + +Author: evomarc +Date: Tue Nov 8 11:31:01 2005 +0000 + + Removed extra colon (;) at end of class definitions. + They didn't hurt until gcc 3.4.1 but then they generated an error! + +Author: maartenkeijzer +Date: Mon Oct 17 12:46:53 2005 +0000 + + Woops, forgot to clear a static string for compile + +Author: maartenkeijzer +Date: Sun Oct 16 15:38:38 2005 +0000 + + Added lambda expression (user/automatically defined functions + +Author: maartenkeijzer +Date: Sat Oct 15 21:27:47 2005 +0000 + + Solved some issues and prepared the library for using unordered_map instead of hash_map (C++ TR1). Can only use this when g++-4.0.3 is out + +Author: maartenkeijzer +Date: Sat Oct 15 09:05:57 2005 +0000 + + Made eoGencontinue a ValueParam, so that it can be attached to a monitor + +Author: maartenkeijzer +Date: Fri Oct 14 16:14:37 2005 +0000 + + forgot to invalidate + +Author: maartenkeijzer +Date: Fri Oct 14 15:34:45 2005 +0000 + + Tester for CMA + +Author: maartenkeijzer +Date: Fri Oct 14 15:33:32 2005 +0000 + + Added CMA + +Author: maartenkeijzer +Date: Fri Oct 14 15:33:16 2005 +0000 + + added timed monitor + +Author: maartenkeijzer +Date: Wed Oct 12 18:35:13 2005 +0000 + + oops, stats.h was missing + +Author: maartenkeijzer +Date: Tue Oct 11 08:15:29 2005 +0000 + + Added simplify and differentiation tests + +Author: kuepper +Date: Mon Oct 10 21:59:57 2005 +0000 + + prepare vecInitSize + +Author: kuepper +Date: Mon Oct 10 21:42:31 2005 +0000 + + cleanup, prepare vecSigmaInit change + +Author: kuepper +Date: Mon Oct 10 21:13:27 2005 +0000 + + cleanup + +Author: evomarc +Date: Mon Oct 10 13:34:21 2005 +0000 + + Added an accessor to the pointsize in eoeoGnuplot1DSnapshot.h + +Author: evomarc +Date: Mon Oct 10 13:33:13 2005 +0000 + + Added an accessor to the pointsize, for do_make_checkpoint_pareto + +Author: maartenkeijzer +Date: Sun Oct 9 07:03:35 2005 +0000 + + Added symbolic differentiation + +Author: maartenkeijzer +Date: Fri Oct 7 13:31:20 2005 +0000 + + Faster scaled evaluation, etc. + +Author: maartenkeijzer +Date: Fri Oct 7 11:31:01 2005 +0000 + + Constant mutation + simplification added + +Author: evomarc +Date: Fri Oct 7 08:27:59 2005 +0000 + + A colon had mystriously dissappeared !!! + +Author: maartenkeijzer +Date: Thu Oct 6 22:26:59 2005 +0000 + + more ramblings in readme + +Author: maartenkeijzer +Date: Thu Oct 6 22:14:48 2005 +0000 + + Added constant getting and setting + +Author: maartenkeijzer +Date: Thu Oct 6 18:10:13 2005 +0000 + + fix + +Author: kuepper +Date: Thu Oct 6 17:22:40 2005 +0000 + + Handle including from contrib/MGE nicely. + +Author: maartenkeijzer +Date: Thu Oct 6 14:31:09 2005 +0000 + + removed stray object files + +Author: maartenkeijzer +Date: Thu Oct 6 12:25:00 2005 +0000 + + first fix in makefile + +Author: maartenkeijzer +Date: Thu Oct 6 12:13:53 2005 +0000 + + Added mathsym+tcc and boost against all advice + +Author: maartenkeijzer +Date: Thu Oct 6 10:06:25 2005 +0000 + + Replaced GPL with LGPL license here. EO has always been LGPL + +Author: kuepper +Date: Wed Oct 5 22:22:25 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Wed Oct 5 22:08:29 2005 +0000 + + typos + +Author: kuepper +Date: Wed Oct 5 21:48:01 2005 +0000 + + cleanup + +Author: kuepper +Date: Wed Oct 5 21:40:53 2005 +0000 + + comments + +Author: kuepper +Date: Wed Oct 5 21:34:19 2005 +0000 + + finish the handling of gnuplot completely at build-time. + No gnuplot-ifs in headers anymore. + +Author: kuepper +Date: Wed Oct 5 21:25:51 2005 +0000 + + some first external links + +Author: kuepper +Date: Mon Oct 3 21:48:15 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Mon Oct 3 12:54:45 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Mon Oct 3 10:58:01 2005 +0000 + + cleanup + +Author: kuepper +Date: Mon Oct 3 10:53:35 2005 +0000 + + clean up + +Author: kuepper +Date: Mon Oct 3 10:32:56 2005 +0000 + + some nifty details, + passes W3 validator. + +Author: kuepper +Date: Mon Oct 3 10:26:30 2005 +0000 + + clean up html + +Author: kuepper +Date: Mon Oct 3 10:10:09 2005 +0000 + + move logo to cvs + +Author: kuepper +Date: Mon Oct 3 10:06:26 2005 +0000 + + updates for release + +Author: kuepper +Date: Mon Oct 3 09:56:02 2005 +0000 + + Make clear that the docs are for the cvs code. + +Author: kuepper +Date: Mon Oct 3 09:51:27 2005 +0000 + + update for release. + +Author: kuepper +Date: Mon Oct 3 09:47:06 2005 +0000 + + Initialize booleans to get rid of compiler-warnings. + +Author: kuepper +Date: Sun Oct 2 21:57:43 2005 +0000 + + fix foe gnuplot configuration-switch usage + +Author: kuepper +Date: Sun Oct 2 21:42:08 2005 +0000 + + Clean up configure/build-process. + - assume C++ standard-conforming environment + - 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 +Date: Sat Oct 1 17:07:59 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Sat Oct 1 16:05:01 2005 +0000 + + add zip to dist, + update release-plan. + +Author: kuepper +Date: Sat Oct 1 15:35:45 2005 +0000 + + Search for ar as necessary on Solaris-x86. + Make DOXYGEN and AR precious variables. + +Author: kuepper +Date: Sat Oct 1 14:25:29 2005 +0000 + + update for solaris-x86 + +Author: kuepper +Date: Sat Oct 1 14:00:42 2005 +0000 + + Include inttypes.h if available but stdint.h is not. + Add powerpc success. + +Author: kuepper +Date: Sat Oct 1 13:27:25 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Sat Oct 1 13:26:29 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Sat Oct 1 13:07:01 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Sat Oct 1 13:00:59 2005 +0000 + + update and clean up + +Author: kuepper +Date: Sat Oct 1 12:18:21 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Sat Oct 1 12:13:00 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Sat Oct 1 11:59:14 2005 +0000 + + update docs + clean Tutorial + bump version-number for cvs + +Author: kuepper +Date: Fri Sep 30 21:16:24 2005 +0000 + + typo + +Author: kuepper +Date: Fri Sep 30 11:47:26 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Thu Sep 29 22:08:19 2005 +0000 + + *** empty log message *** + +Author: kuepper +Date: Thu Sep 29 22:01:52 2005 +0000 + + add main web-page + +Author: kuepper +Date: Thu Sep 29 16:53:06 2005 +0000 + + Use install to copy generated documentation. + +Author: kuepper +Date: Wed Sep 28 21:57:40 2005 +0000 + + remove forgotten config.h + +Author: kuepper +Date: Wed Sep 28 21:49:26 2005 +0000 + + Simplify configuration. + Remove support for (outdated) , require . + Require uint32_t for now, defined in stdint.h according to C99. + Some general cleanup and more documentation. + +Author: kuepper +Date: Wed Sep 28 18:25:38 2005 +0000 + + +Author: kuepper +Date: Wed Sep 28 17:59:59 2005 +0000 + + +Author: kuepper +Date: Wed Sep 28 16:32:35 2005 +0000 + + Switch on documentation generation for private and static members. + +Author: kuepper +Date: Wed Sep 28 14:32:12 2005 +0000 + + Some more documentation + +Author: kuepper +Date: Wed Sep 28 10:00:16 2005 +0000 + + Add ignore-files to quiten cvs + +Author: kuepper +Date: Wed Sep 28 08:36:00 2005 +0000 + + documente for stdev_eps + +Author: kuepper +Date: Tue Sep 27 22:06:08 2005 +0000 + + cleanup + +Author: kuepper +Date: Tue Sep 27 21:54:05 2005 +0000 + + documentation, whitespace + +Author: maartenkeijzer +Date: Mon Sep 26 11:22:47 2005 +0000 + + Removed wrong reference to rng from choice members (what was I thinking?) + +Author: kuepper +Date: Mon Sep 26 10:18:15 2005 +0000 + + Make sure uint32_t is defined correctly in eoRNG.h and use it where + appropriate. + +Author: maartenkeijzer +Date: Sun Sep 25 19:32:10 2005 +0000 + + Added few convenience functions + +Author: maartenkeijzer +Date: Sun Sep 25 19:09:38 2005 +0000 + + Added choice functions, plus rolled back inadvertant chance to eoRNG + +Author: kuepper +Date: Tue Sep 13 10:24:50 2005 +0000 + + setORcreate returns it parameter. + +Author: kuepper +Date: Mon Sep 12 17:53:25 2005 +0000 + + Use getORcreateParam instead of createParam when getting values from + the eoParser. + Update setORcreateParam. + +Author: maartenkeijzer +Date: Wed Sep 7 17:09:19 2005 +0000 + + eoRNG.h + +Author: kuepper +Date: Mon Sep 5 17:04:13 2005 +0000 + + Remove paradiseo configuration switch + +Author: kuepper +Date: Mon Sep 5 16:47:53 2005 +0000 + + Provide virtual destructors as gcc-4 barks heavily otherwise + +Author: kuepper +Date: Mon Sep 5 16:11:00 2005 +0000 + + ParadiesEO cleanup + +Author: kuepper +Date: Mon Sep 5 16:09:43 2005 +0000 + + Remove useless PAradisEO files + +Author: kuepper +Date: Mon Sep 5 16:08:14 2005 +0000 + + Remove useless files from paradiseo directories + +Author: cahon +Date: Fri Sep 2 13:36:21 2005 +0000 + + Removing ParadisEO + +Author: cahon +Date: Fri Sep 2 07:12:27 2005 +0000 + + Removing ParadisEO + +Author: cahon +Date: Fri Sep 2 07:00:45 2005 +0000 + + Removing ParadisEO + +Author: kuepper +Date: Mon Aug 29 07:50:50 2005 +0000 + + Provide eoParser::setORcreateParam to set a paramter in the parser to + a specific value. + +Author: kuepper +Date: Mon Aug 29 07:32:13 2005 +0000 + + Install eoPropGAGenOp.h + Add #include in eoEsChromInit.h in order to make gcc-4.0 happy. + +Author: evomarc +Date: Sat May 7 15:43:29 2005 +0000 + + Added eoPropGAGenOp, the sequential application of crossover and mutation + +Author: evomarc +Date: Mon Apr 4 20:41:06 2005 +0000 + + Small upgrade for gcc 3.3 (I guess no-one is using those files, right?) + +Author: evomarc +Date: Mon Mar 14 21:00:00 2005 +0000 + + Updated the src:: everywhere in eoVariableLengthCrossover.h eoFlOrMonOp.h + (that nobody seems to actually use btw :-) + +Author: cahon +Date: Wed Feb 23 13:31:20 2005 +0000 + + Removing ParadisEO + +Author: cahon +Date: Tue Feb 22 14:12:19 2005 +0000 + + Removing ParadisEO + +Author: evomarc +Date: Thu Feb 10 09:57:28 2005 +0000 + + Added the complete reference to the base class in call for value() + because g++3.4 otherwise complains + +Author: kuepper +Date: Mon Jan 3 09:35:39 2005 +0000 + + include config.h + +Author: kuepper +Date: Mon Jan 3 09:35:17 2005 +0000 + + fix for gcc-3.4 + +Author: evomarc +Date: Mon Dec 27 09:08:44 2004 +0000 + + Mainly made it obvious that Lesson4 contains "ready-to-use" EAs + +Author: evomarc +Date: Mon Dec 27 08:01:29 2004 +0000 + + Modified the way to set the initial values of the sigmas (and stdevs) + so that they can be scaled to the range of each variable (by adding + a "%" after the value in the parameter file) + See also the examples in tutorial/Lesson4 + +Author: evomarc +Date: Mon Dec 27 07:59:58 2004 +0000 + + Added the 2 parameter files ESEA.param amd RealEA.param + so both programs go to 0 nicely instead of staying anywhere but close + +Author: evomarc +Date: Mon Dec 27 07:33:03 2004 +0000 + + Added the explicit calls to the base class ctors in eoXXXGeneralBounds copy Ctors + +Author: evomarc +Date: Mon Dec 27 07:31:59 2004 +0000 + + Fixed some int - unsigned int problem for the case "combien < 0" + +Author: kuepper +Date: Thu Dec 23 17:33:08 2004 +0000 + + reshuffle libraries to resolve all dependencies + +Author: kuepper +Date: Thu Dec 23 17:26:39 2004 +0000 + + minor updates, + create doxytag-file when running doxygen + +Author: kuepper +Date: Thu Dec 23 17:22:52 2004 +0000 + + more adjustments for gcc-3.4 (now using optimization, go figure...) + +Author: kuepper +Date: Thu Dec 23 16:06:37 2004 +0000 + + small fix for gcc-3.3.3 + +Author: maartenkeijzer +Date: Thu Dec 23 15:40:44 2004 +0000 + + Some small changes concerning flags and warnings + +Author: kuepper +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. + +Author: maartenkeijzer +Date: Thu Dec 23 10:14:42 2004 +0000 + + Added using declarations to avoid g++-3.4 errors + +Author: evomarc +Date: Wed Dec 1 09:27:31 2004 +0000 + + Added comments so that the new classes eoGeneralXXXBounds are taken into account + by Doxygen. + +Author: evomarc +Date: Wed Dec 1 09:23:53 2004 +0000 + + ... some comments ... + +Author: evomarc +Date: Wed Dec 1 09:22:48 2004 +0000 + + ... some comments for Doxygen ... + +Author: evomarc +Date: Wed Dec 1 09:19:47 2004 +0000 + + ... a comment ... + +Author: evomarc +Date: Wed Dec 1 08:49:40 2004 +0000 + + Added a few words about Lesson5, and the change in the Makefiles. + Also, looking alive is probably important ! + +Author: evomarc +Date: Mon Nov 29 20:49:34 2004 +0000 + + Corrected some bugs in eoGeneralXXXBounds (e.g. no const in copy Ctor arguments) + Added a default value for the intialization (-infty, +infty) + Needs to allow uniform() on unbounded - still pondering + +Author: evomarc +Date: Fri Nov 5 08:57:34 2004 +0000 + + Added classes to hendle bounds: + - eoGeneralRealBound that can be initialized using a string (and hence can be + 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 + +Author: evomarc +Date: Fri Nov 5 08:55:12 2004 +0000 + + Added classes to hendle bounds: + - eoGeneralRealBound that can be initialized using a string (and hence can be + 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 + +Author: kuepper +Date: Thu Oct 7 14:32:54 2004 +0000 + + fix install dir + +Author: kuepper +Date: Thu Oct 7 13:36:43 2004 +0000 + + were these lost? + +Author: kuepper +Date: Thu Oct 7 13:34:08 2004 +0000 + + wrong directory + +Author: kuepper +Date: Wed Sep 29 18:37:20 2004 +0000 + + update for sstream + +Author: kuepper +Date: Tue Sep 28 17:13:34 2004 +0000 + + +Author: evomarc +Date: Mon Sep 27 15:19:53 2004 +0000 + + Added include eoDistance.h + +Author: evomarc +Date: Mon Sep 27 13:34:34 2004 +0000 + + Replaced the eoNormalMutation (mutating ALL variables of a real-valued vector) + with eiNormalVecMutation that has a proba. to mutation each variable + +Author: evomarc +Date: Mon Sep 27 13:31:40 2004 +0000 + + Added the class eoNormalVecMutation (yes, should have made another file :-( + +Author: okoenig +Date: Sun Sep 26 09:47:06 2004 +0000 + + Replaced top_builddir with top_srcdir + +Author: okoenig +Date: Sun Sep 26 09:45:59 2004 +0000 + + Removing a "/" at the end of a comment + +Author: kuepper +Date: Fri Sep 24 15:00:48 2004 +0000 + + Fix doc-target. + Fix inclusion of documentation in dist. + +Author: kuepper +Date: Fri Sep 24 11:55:09 2004 +0000 + + minor fixes + +Author: kuepper +Date: Wed Sep 22 18:38:12 2004 +0000 + + Removed clean-local due to problems with "make distcheck" + +Author: kuepper +Date: Wed Sep 22 18:18:31 2004 +0000 + + fix installation, dist-preparation + +Author: kuepper +Date: Wed Sep 22 17:30:11 2004 +0000 + + updates for distributing/installing ParadisEO. + +Author: kuepper +Date: Wed Sep 22 13:20:15 2004 +0000 + + update for new build-process + +Author: kuepper +Date: Wed Sep 22 12:38:28 2004 +0000 + + update build process to include paradiseo tutorial, + fix paradiseo headers for sstream + +Author: kuepper +Date: Wed Sep 22 08:18:29 2004 +0000 + + Update configure with switches for app, ParadisEO, and tutorial. + Add ParadisEO/Lesson1 tutorial in build-process. + minor fixes. + +Author: maartenkeijzer +Date: Tue Sep 21 19:49:48 2004 +0000 + + Made couple of functions virtual + +Author: kuepper +Date: Tue Sep 21 17:01:14 2004 +0000 + + updates, + start supoorting ParadisEO + +Author: kuepper +Date: Tue Sep 21 10:30:45 2004 +0000 + + fix dist-header + +Author: kuepper +Date: Tue Sep 21 10:23:33 2004 +0000 + + fix 'make dist', works now (besides ParadisEO). + +Author: kuepper +Date: Mon Sep 20 21:47:15 2004 +0000 + + updates + +Author: kuepper +Date: Mon Sep 20 17:14:11 2004 +0000 + + fix + +Author: kuepper +Date: Mon Sep 20 17:12:12 2004 +0000 + + better distribution support (not finished) + +Author: kuepper +Date: Mon Sep 20 17:06:25 2004 +0000 + + conditional compilation fixes + +Author: kuepper +Date: Mon Sep 20 16:05:25 2004 +0000 + + don't use user-variables + +Author: kuepper +Date: Mon Sep 20 15:51:53 2004 +0000 + + update user commentary + +Author: kuepper +Date: Mon Sep 20 15:50:00 2004 +0000 + + *** empty log message *** + +Author: kuepper +Date: Mon Sep 20 14:11:24 2004 +0000 + + updates for build-process + +Author: kuepper +Date: Mon Sep 20 09:56:10 2004 +0000 + + *** empty log message *** + +Author: kuepper +Date: Mon Sep 20 09:52:19 2004 +0000 + + Remove support files, they are automatically created by autotools + +Author: kuepper +Date: Mon Sep 20 09:50:47 2004 +0000 + + update + +Author: kuepper +Date: Mon Sep 20 09:47:19 2004 +0000 + + remove + +Author: kuepper +Date: Mon Sep 20 09:46:48 2004 +0000 + + remove Makefiles from cvs + +Author: kuepper +Date: Fri Sep 17 17:05:28 2004 +0000 + + add conditional includes for sstream + +Author: kuepper +Date: Fri Sep 17 17:00:04 2004 +0000 + + cleanup + +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 +Date: Fri Sep 17 15:20:19 2004 +0000 + + Save copies of old simple Makefiles + +Author: maartenkeijzer +Date: Mon Aug 30 19:44:48 2004 +0000 + + added verbose flag that can be used to turn off annoying message to cout + +Author: evomarc +Date: Sat Aug 28 16:26:03 2004 +0000 + + CLeaned up the comments in files related to Sharing (added t-eoSharing in test) + +Author: evomarc +Date: Sat Aug 28 16:25:12 2004 +0000 + + Committing at last the long awaited test for Sharing + +Author: evomarc +Date: Sat Aug 28 14:03:34 2004 +0000 + + Cleaned up the comments + +Author: jmerelo +Date: Tue Aug 10 17:19:46 2004 +0000 + + Changes in docs and added stuff to eoEvalSteadyFitness to reset after using it + +Author: jmerelo +Date: Tue Aug 10 07:39:10 2004 +0000 + + Updating doxygen configuration + +Author: okoenig +Date: Sun Jul 25 13:26:02 2004 +0000 + + added a string msg to eoScalarFitnessAssembled, in order to store all sorts of messages for an individual + +Author: evomarc +Date: Fri Jul 16 08:45:02 2004 +0000 + + Added className (mysteriously missint) mandatory for eoCombinedInit + +Author: evomarc +Date: Fri Jul 16 08:44:14 2004 +0000 + + Allows proportional combinations of eoInit objects + Similar to eoPropostionalCombinedXXXOp + +Author: cahon +Date: Mon Jul 12 09:16:41 2004 +0000 + + Adding typedef EOT EOType ; + +Author: cahon +Date: Mon Jul 12 08:57:38 2004 +0000 + + Adding typedef EOT EOType ; + +Author: evomarc +Date: Wed Jun 23 23:19:17 2004 +0000 + + Added the Ctor using the Parser + +Author: evomarc +Date: Tue Jun 15 07:28:54 2004 +0000 + + Added the className method everywhere + +Author: evomarc +Date: Tue Jun 15 07:09:57 2004 +0000 + + Added the className methods everywhere + +Author: evomarc +Date: Tue Jun 15 07:06:27 2004 +0000 + + Added newline at end of stat + +Author: evomarc +Date: Tue Jun 15 07:04:12 2004 +0000 + + Added the allClassName method to print the name of all + classes that have been added to the checkpoint + +Author: okoenig +Date: Mon Jun 14 17:07:25 2004 +0000 + + Added a failed boolean to the fitness, for statistics... Average stat values are now computed from succesful fitness evaluations only + +Author: okoenig +Date: Mon Jun 14 17:05:07 2004 +0000 + + Added a failed boolean to indicate if fitness evaluation succeeded ( useful if programs are involved, where fitness evaluation can fail for some indis) + Avg Stats are now only evaluated of individuals if this bool is false! + +Author: okoenig +Date: Mon Jun 14 11:59:39 2004 +0000 + + Replaced #include with #include to get rid of "deprecated" warnings in gcc 3.3 + +Author: okoenig +Date: Mon Jun 14 11:24:37 2004 +0000 + + Added a failed boolean to indicate if fitness evaluation succeeded ( useful if programs are involved, where fitness evaluation can fail for some indis) + Avg Stats are now only evaluated of individuals if this bool is false! + +Author: okoenig +Date: Mon Jun 14 11:23:48 2004 +0000 + + Added a failed boolean to indicate if fitness evaluation succeeded ( useful if programs are involved, where fitness evaluation can fail for some indis) + +Author: evomarc +Date: Wed May 26 10:23:07 2004 +0000 + + Adding Sharing (though eoSharingSelect - a roulette selection on shared fitnesses + +Author: evomarc +Date: Wed May 26 09:00:26 2004 +0000 + + Temporary modification of the tutorial to account for the new features + - stat.tmpl allowing easy creation of own stat + - sharing as a new possible selector in make_algo_scalar - requires a distance + No detail given, though ... + +Author: evomarc +Date: Tue May 25 08:03:30 2004 +0000 + + Adding sharing - needed to modify quite a few files, like eoDistance.h + make_algo_scalar.h and all related files, and the like + +Author: evomarc +Date: Tue May 25 07:57:52 2004 +0000 + + Adding the statistics in createSimple (create.sh is becoming obsolete) + +Author: stevemadere +Date: Fri May 21 01:44:32 2004 +0000 + + Fixed a bug in mlp::net::load() that prevented loading of multiple nets + from the same stream. + +Author: stevemadere +Date: Fri Apr 23 16:20:12 2004 +0000 + + Added weight perturbation operators to enable implementation of + exact GPROP-III algorithm. + +Author: evomarc +Date: Thu Apr 8 07:55:40 2004 +0000 + + Added the setLongName method to handle the prefix trick in eoParser + +Author: evomarc +Date: Mon Apr 5 15:28:12 2004 +0000 + + Added a prefix data in eoParser - and the setPrefix method - + for multi-population parameter input. Now you can call the make_xxx + functions from teh src/do directory several times for different populations + provided you do different calls to setPrefix inbetween + +Author: evomarc +Date: Tue Mar 30 16:51:06 2004 +0000 + + Corrected errors in the "memory management" section. + Thanks to ZhangQian for pointing them out + +Author: okoenig +Date: Sun Mar 28 22:18:03 2004 +0000 + + Bugfix regarding the feasible flag + +Author: maartenkeijzer +Date: Fri Mar 26 09:56:56 2004 +0000 + + Fixed bug in rng::roulette_wheel: use of float had too little precision in change/fortune var + +Author: maartenkeijzer +Date: Fri Mar 26 09:36:07 2004 +0000 + + Fixed rng::uniform to not provide the wrong result (1.0) once in every 2^32 times + +Author: stevemadere +Date: Wed Feb 11 23:03:23 2004 +0000 + + Made mlp::net::operator() a virtual function to allow for subclassing + with networks that transform their input or output. + +Author: stevemadere +Date: Tue Feb 10 22:33:30 2004 +0000 + + Fixed some signed/unsigned conversion bugs + +Author: jeggermo +Date: Mon Feb 2 08:54:10 2004 +0000 + + *** empty log message *** + +Author: maartenkeijzer +Date: Wed Jan 21 19:57:19 2004 +0000 + + Added define NO_GNUPLOT to disable gnuplot extensions + Needed for win32 (well, at least for me) + +Author: stevemadere +Date: Tue Jan 13 20:28:33 2004 +0000 + + Fixed the string serialization operators (>>, <<) for neuron, layer, + and net so they actually work and added or fixed stream-source + constructors where appropriate. + +Author: stevemadere +Date: Tue Jan 13 20:21:52 2004 +0000 + + Made it compile under gcc 3.2.2 by adding explicit definitions + of normally derived comparison operators >, >=, and == for the + structure phenotype. ( adding #include was not sufficient + to solve the problem) + Also added function gprop_use_datasets() to give more flexibility + in subclassing the datasets used to train the nets. + +Author: evomarc +Date: Tue Jan 13 03:35:27 2004 +0000 + + Added the standard header - just a test of CVS in fact! + +Author: evomarc +Date: Wed Dec 24 16:38:02 2003 +0000 + + Corrected a but in eoUniformMutation (only the first component ever got modified! + Thanks to Jeroen's student ... + +Author: evomarc +Date: Fri Dec 5 05:39:40 2003 +0000 + + There was an infinite loop in case of a file without section header on first line! + +Author: evomarc +Date: Fri Dec 5 05:38:02 2003 +0000 + + Added a few user-friendly comments in case sizes don't match between + load file and required popsize + +Author: evomarc +Date: Wed Nov 26 14:20:26 2003 +0000 + + A minor typo ... + +Author: evomarc +Date: Wed Nov 26 11:15:59 2003 +0000 + + THe call to randomize was forgotten after the choice of a terminal + at max_depth. + This was only visible if + - you implemented the randomize method + - you reached the maximum depth (or used ramped half-and-half). + +Author: okoenig +Date: Wed Nov 19 13:29:15 2003 +0000 + + Added possibility to print header to first line of output file; control through last bool in constructor - default = false... + +Author: jeggermo +Date: Tue Nov 4 15:32:24 2003 +0000 + + parse_tree.h now uses standard memory allocation + for MacOSX + +Author: jeggermo +Date: Tue Nov 4 15:29:24 2003 +0000 + + eoData has been changed slightly for MacOSX + +Author: maartenkeijzer +Date: Sun Oct 12 23:49:23 2003 +0000 + + oops, forgot std:: + +Author: maartenkeijzer +Date: Sun Oct 12 20:53:28 2003 +0000 + + Sort dissappeared in one-objective + +Author: evomarc +Date: Sat Sep 20 05:42:23 2003 +0000 + + Updated lists of headers in some Makefile.am (thanks to Claude Dion for pointing this out) + While there, changed the presentations of source and headers (1 per line with \) + +Author: evomarc +Date: Thu Sep 18 15:09:34 2003 +0000 + + Modified a wrong link + +Author: evomarc +Date: Tue Sep 2 05:49:37 2003 +0000 + + Slightly modified the formula: the worst individual had "fitness" 0 in hte case of linear scaling with pressure=2. Now it has fitness 1/[P(P-1)/2] + Thanks to Gilles BAUDRILLARD (EADS) + +Author: evomarc +Date: Mon Sep 1 12:56:29 2003 +0000 + + Added 2 missing headers (and broke the long lines). + Thanks to Jochen Küpper for pointing this out. + +Author: evomarc +Date: Tue Aug 26 18:07:06 2003 +0000 + + Corrected a HUGE bug in eoRealUXover !!! + Thanks to Gilles BAUDRILLARD - EADS + +Author: okoenig +Date: Thu Aug 21 13:02:53 2003 +0000 + + added parameters to the constructors to start generation counting !=0 + the parameters are optional and appended in the end + +Author: evomarc +Date: Sat Aug 2 06:55:47 2003 +0000 + + CLean-up + +Author: evomarc +Date: Sat Aug 2 06:42:33 2003 +0000 + + Adding the generic operators for FIXED-LENGTH ORDERED genotypes eoFlOrXxxOp.h + +Author: okoenig +Date: Wed Jul 30 14:48:13 2003 +0000 + + Inserted a missing std:: + +Author: evomarc +Date: Tue Jul 29 05:33:58 2003 +0000 + + Forgot the dir when adding eoSBXcross.h :-((( + +Author: evomarc +Date: Mon Jul 28 09:48:58 2003 +0000 + + Adding SBX crossover operator in es dir + +Author: evomarc +Date: Mon Jul 28 09:47:15 2003 +0000 + + Adding the SBX operator in es dir + +Author: evomarc +Date: Sat Jun 21 06:34:00 2003 +0000 + + More precise comment + +Author: jmerelo +Date: Wed Jun 18 09:07:19 2003 +0000 + + Eliminated using namespace std + +Author: jmerelo +Date: Tue Jun 17 12:03:42 2003 +0000 + + better eoString + +Author: jmerelo +Date: Tue Jun 17 06:24:15 2003 +0000 + + Changes to obsolete things + +Author: okoenig +Date: Mon Jun 16 21:41:30 2003 +0000 + + added a public bool feasible, used to identify feasible individuals in initialization processes + +Author: maartenkeijzer +Date: Mon Jun 9 06:25:11 2003 +0000 + + Exported operator() for eoSGATransform in abstract1.cpp + +Author: evomarc +Date: Mon Jun 9 06:17:26 2003 +0000 + + Change in terminology: EDA (Estimation of Distribution Algorithms) replaces + DEA (Distribution Evolution Algorithms), as it seems more widely used today. + +Author: evomarc +Date: Mon Jun 9 06:06:13 2003 +0000 + + Change in terminology: EDA (Estimation of Distribution Algorithms) replaces + DEA (Distribution Evolution Algorithms), as it seems more widely used today. + +Author: maartenkeijzer +Date: Fri Jun 6 10:29:13 2003 +0000 + + Improved the check for changed. Now it will only set the changed flag when the elements that are flipped are actually different + +Author: maartenkeijzer +Date: Wed Jun 4 11:50:48 2003 +0000 + + added shuffle + +Author: maartenkeijzer +Date: Wed Jun 4 09:34:26 2003 +0000 + + Added tests for roulette wheel selection + +Author: maartenkeijzer +Date: Wed Jun 4 09:33:27 2003 +0000 + + optimized eoProportional and added universalselect + +Author: jeggermo +Date: Fri May 16 14:28:52 2003 +0000 + + GCC 3.3 + +Author: evomarc +Date: Sun Apr 27 06:08:11 2003 +0000 + + Added keywords "Sequential" and "Random" as synonyms of resp. "Deterministic" + and "Uniform" - for EASEA + +Author: maartenkeijzer +Date: Sun Apr 20 12:57:59 2003 +0000 + + Removed HAVE_SSTREAM for redhat 2.96 + +Author: cahon +Date: Fri Apr 18 13:32:39 2003 +0000 + + missing include eoParetoFitness.h + +Author: okoenig +Date: Sat Apr 5 13:42:44 2003 +0000 + + minor changes + +Author: okoenig +Date: Sat Apr 5 13:42:01 2003 +0000 + + added eoAssembledFitnessStat.h to implement Best and Avg Stat for eoScalarFitnessAssembled + +Author: okoenig +Date: Sat Apr 5 13:40:57 2003 +0000 + + Removed function template specializations for eoScalarFitnessAssembled from classes in this file, since they do not work under Visual Studio! Reimplemented these stat classes for this new fitness class in eoAssembledFitnessStat.h + +Author: okoenig +Date: Thu Apr 3 16:51:47 2003 +0000 + + Included new fitness class eoScalarFitnessAssembled, that stores different fitness terms in a std::vector, but still acts as a scalar fitness. A new checkpoint uses these values for statistics. + +Author: okoenig +Date: Thu Apr 3 16:47:47 2003 +0000 + + Minor changes to make it run under Visual Studio 6.0 + +Author: okoenig +Date: Thu Apr 3 16:25:55 2003 +0000 + + Minor changes to make it run under Visual Studio 6.0 + +Author: okoenig +Date: Thu Apr 3 10:44:35 2003 +0000 + + Minor changes to make it run under Visual Studio 6.0 + +Author: okoenig +Date: Thu Apr 3 09:23:52 2003 +0000 + + Minor changes to make it run under Visual Studio 6.0 + +Author: okoenig +Date: Thu Apr 3 09:11:17 2003 +0000 + + Minor changes to make it run under Visual Studio 6.0 + +Author: okoenig +Date: Wed Apr 2 21:10:53 2003 +0000 + + included new fitness class eoScalarFitnessAssembled, that stores different fitness terms in a std::vector, but still acts as a scalar fitness. A new checkpoint uses these values for statistics. + +Author: evomarc +Date: Tue Apr 1 12:09:37 2003 +0000 + + Removed a dummy line containing reference to lesson3! + +Author: maartenkeijzer +Date: Tue Mar 25 10:46:08 2003 +0000 + + Deleted political statement as I changed my mind about this + +Author: evomarc +Date: Sat Mar 22 06:39:21 2003 +0000 + + ADded comments and hook for copy constructor + +Author: maartenkeijzer +Date: Fri Mar 21 09:17:38 2003 +0000 + + bumped up the version number + +Author: maartenkeijzer +Date: Fri Mar 21 02:44:05 2003 +0000 + + now added an std::ends for plotting strstream + +Author: maartenkeijzer +Date: Fri Mar 21 02:41:54 2003 +0000 + + again: std::ends and stringstream + +Author: maartenkeijzer +Date: Fri Mar 21 02:39:09 2003 +0000 + + fixed (?) some problems with stringstreams and std::ends + +Author: maartenkeijzer +Date: Thu Mar 20 20:00:38 2003 +0000 + + eliminated gprop from the build until someone makes sure it builds under gcc-3.2 + +Author: maartenkeijzer +Date: Thu Mar 20 19:49:32 2003 +0000 + + replace \0 with std::ends + +Author: maartenkeijzer +Date: Wed Mar 19 10:47:08 2003 +0000 + + finished pickling support for valueParam + +Author: maartenkeijzer +Date: Wed Mar 19 10:16:56 2003 +0000 + + Added pickling support for ValueParams + +Author: maartenkeijzer +Date: Wed Mar 19 08:53:59 2003 +0000 + + removed comment in PyEO.cpp + +Author: maartenkeijzer +Date: Tue Mar 18 16:57:17 2003 +0000 + + added operator> + +Author: maartenkeijzer +Date: Tue Mar 18 16:52:31 2003 +0000 + + fixed a bug reported on sourceforge + +Author: maartenkeijzer +Date: Tue Mar 18 16:35:27 2003 +0000 + + *** empty log message *** + +Author: maartenkeijzer +Date: Tue Mar 18 09:40:36 2003 +0000 + + excluded gcc>3 from check + +Author: maartenkeijzer +Date: Tue Mar 18 09:35:46 2003 +0000 + + hi + +Author: maartenkeijzer +Date: Sun Mar 2 11:35:43 2003 +0000 + + decorated sort and max with std:: specifier + +Author: maartenkeijzer +Date: Sun Mar 2 11:29:01 2003 +0000 + + decorated copy with std:: specifier + +Author: maartenkeijzer +Date: Sun Mar 2 11:26:45 2003 +0000 + + added typenames for pop::iterator + +Author: maartenkeijzer +Date: Sun Mar 2 11:16:33 2003 +0000 + + added include file + +Author: okoenig +Date: Fri Feb 28 17:47:24 2003 +0000 + + This Makefile.am was missing; all it does is adding the *.h and Readme files to distribution + +Author: maartenkeijzer +Date: Fri Feb 28 16:56:59 2003 +0000 + + oops, forgot thisone + +Author: maartenkeijzer +Date: Fri Feb 28 16:49:19 2003 +0000 + + changed to using sstream + +Author: okoenig +Date: Thu Feb 27 19:28:07 2003 +0000 + + Removed "using namespace std" statements from header files in EO -- "std::" identifier were added where necessary. + +Author: okoenig +Date: Thu Feb 27 19:18:53 2003 +0000 + + removed "using namespace std" statements from header files in EO -- "std::" identifier were added where necessary + +Author: okoenig +Date: Thu Feb 27 19:18:07 2003 +0000 + + removed "using namespace std" statements from header files in EO -- "std::" identifier were added where necessary. + +Author: okoenig +Date: Thu Feb 20 19:13:33 2003 +0000 + + added an #ifdef _MSC_VER statement to hide "typename" identifier for Visual Studio + +Author: maartenkeijzer +Date: Mon Feb 17 10:42:03 2003 +0000 + + added std:: + +Author: maartenkeijzer +Date: Mon Feb 17 10:19:25 2003 +0000 + + Updated to use gcc-3.2 + +Author: maartenkeijzer +Date: Mon Feb 17 09:52:36 2003 +0000 + + rolled back unfortunate change in eoAverageStat + +Author: evomarc +Date: Sat Feb 8 05:36:01 2003 +0000 + + Added a mthod to remove one of the combined things (from Ramón Casero Cañas) + +Author: evomarc +Date: Sat Feb 8 05:24:51 2003 +0000 + + Removed debugging printouts + +Author: maartenkeijzer +Date: Tue Jan 14 10:09:28 2003 +0000 + + added missing valueparm.h" + +Author: maartenkeijzer +Date: Tue Jan 14 09:37:45 2003 +0000 + + next iteration + +Author: maartenkeijzer +Date: Fri Jan 10 15:42:45 2003 +0000 + + found a bug in eoProportionalOp, hope this helps... + +Author: maartenkeijzer +Date: Fri Jan 10 15:41:17 2003 +0000 + + Added monitors and statistics, also made a module with some + specific python stuff in __init__.py + +Author: okoenig +Date: Wed Jan 8 12:43:31 2003 +0000 + + bugfix: since there are no Makefiles in the directory ~eo/src/do anymore, I removed this directory from the subdirs list in this Makefile.am + +Author: maartenkeijzer +Date: Tue Jan 7 14:24:56 2003 +0000 + + some bugfixes + +Author: maartenkeijzer +Date: Tue Jan 7 10:50:23 2003 +0000 + + df + +Author: maartenkeijzer +Date: Tue Jan 7 10:49:55 2003 +0000 + + added a small cookbook + +Author: maartenkeijzer +Date: Mon Jan 6 21:56:40 2003 +0000 + + needed for redhat + +Author: maartenkeijzer +Date: Mon Jan 6 16:11:05 2003 +0000 + + added + +Author: maartenkeijzer +Date: Mon Jan 6 16:10:38 2003 +0000 + + Added multi-objective support to PyEO (and changed its name to that) + +Author: maartenkeijzer +Date: Mon Jan 6 14:25:40 2003 +0000 + + Changed a few things so that the python library can + be used with the multi-objective library (it basically + boils down to removing the assumption that fitness() has a + size() member function and changing eoPop to vector) + +Author: maartenkeijzer +Date: Sun Jan 5 16:45:48 2003 +0000 + + updated build info + +Author: maartenkeijzer +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 +Date: Sun Dec 29 22:48:01 2002 +0000 + + oops, error in line 47 + +Author: music_dev +Date: Sat Dec 14 02:51:53 2002 +0000 + + Added compatibility for MSVC.NET + +Author: cahon +Date: Fri Dec 13 10:03:47 2002 +0000 + + Fixing bug [preserve order of the pop. to evaluate] + +Author: evomarc +Date: Mon Dec 9 21:04:47 2002 +0000 + + There was a bug in teh Ctor (fortunately, only with the last + parameter, that was generally used with the default value). + Thanks to Ramón Casero Cañas + +Author: evomarc +Date: Mon Dec 9 06:57:33 2002 +0000 + + Corrected wrong links in the 1st paragraph + +Author: evomarc +Date: Mon Dec 9 06:19:56 2002 +0000 + + Corrected an error in name of statusParam parameter + +Author: evomarc +Date: Mon Dec 9 06:17:25 2002 +0000 + + Corrected a typo + +Author: okoenig +Date: Sun Nov 3 13:17:48 2002 +0000 + + reordered initialization list to match declaration order + +Author: okoenig +Date: Sun Nov 3 13:07:43 2002 +0000 + + added some typename statements to make it compile without warnings under gcc3.2 + +Author: okoenig +Date: Wed Oct 23 10:23:03 2002 +0000 + + small bugfix, to make this example run under Solaris/g++ 2.95.3 + +Author: evomarc +Date: Wed Oct 23 04:43:10 2002 +0000 + + Adding depcom so that it compile smoothly on Solaris. + Thanks to Oliver Koenig + +Author: evomarc +Date: Wed Oct 23 04:42:07 2002 +0000 + + Modification of all Makefiles so that it compiles smoothly on Solaris. + Thanks to Oliver Koenig + +Author: evomarc +Date: Mon Oct 21 04:28:11 2002 +0000 + + Added the .SUFFIXES lien (for Solaris) and the use of $(CXX) instead of c++ + plus a few comments :-) + +Author: jeggermo +Date: Fri Oct 18 11:39:09 2002 +0000 + + *** empty log message *** + +Author: music_dev +Date: Mon Oct 14 16:16:01 2002 +0000 + + Better install for libraries. + +Author: evomarc +Date: Wed Oct 2 14:07:58 2002 +0000 + + Removed the stringstream (sstream not in all compilers distributions) + +Author: evomarc +Date: Wed Sep 18 15:36:41 2002 +0000 + + Added accessors to private parameter stopOnUnknownParam + +Author: jeggermo +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 +Date: Tue Sep 17 07:08:51 2002 +0000 + + Allowing a first eval. of the pop. to be performed by the E.A. + +Author: cahon +Date: Mon Sep 16 12:53:08 2002 +0000 + + Invalidating flags ... + +Author: evomarc +Date: Thu Aug 29 16:44:30 2002 +0000 + + Added a missing test in the weak elitism + +Author: evomarc +Date: Thu Aug 29 16:31:50 2002 +0000 + + Added an error message in case of unknown reducer + (was the source of a segmentation fault with old parameter files) + +Author: evomarc +Date: Fri Aug 23 16:06:06 2002 +0000 + + Removed non-tested code (forthcoming)... + +Author: evomarc +Date: Fri Aug 23 16:02:02 2002 +0000 + + It was about time to enter the template file for EASEA here, as createSimple + and EASEA are doing approximately the same job ...` + +Author: evomarc +Date: Fri Aug 23 15:58:15 2002 +0000 + + Adding a simpler way of generating files for new genotypes (see EO.tpl + in EASEA). + +Author: evomarc +Date: Fri Aug 23 15:56:09 2002 +0000 + + Adding more repalcements utilities (see do/make_easea_algo.h) + +Author: evomarc +Date: Fri Aug 23 15:54:30 2002 +0000 + + Adding replacement strategies: teh ReduceMergeReduce for EASEA and the + MGG and G2 replacements from Deb's PCX paper + +Author: evomarc +Date: Fri Aug 23 15:52:40 2002 +0000 + + Adding make_xxx files for EASEA + +Author: evomarc +Date: Fri Aug 23 15:50:57 2002 +0000 + + Adding eoSGAGenOp.h - mimicking eoSGATransform into an eoGenOp + +Author: evomarc +Date: Fri Aug 23 15:49:29 2002 +0000 + + Added the invalidate method + +Author: evomarc +Date: Fri Aug 23 15:44:27 2002 +0000 + + Tiny details + +Author: evomarc +Date: Fri Aug 23 15:41:00 2002 +0000 + + Added bounds to FitnessStat and Gnuplot monitor + +Author: evomarc +Date: Fri Aug 2 07:40:47 2002 +0000 + + Removed some multiple declaraions inside for loops that MSVC++ doesn't like + +Author: evomarc +Date: Tue Jul 30 03:21:59 2002 +0000 + + Removed a typo that made gnuplot file not be in the RESULT directory + +Author: evomarc +Date: Sun Jul 28 05:40:25 2002 +0000 + + Added eoReduceMergeReduce and elitism (+ corrected small bug in eoHowMany) + +Author: evomarc +Date: Wed Jul 24 18:08:30 2002 +0000 + + A radical change in eoCheckPoint - though invisible from the outside: + eoCheckpoint now alos contains a vector - and not only + IS A eoContinue. So you can ADD another eoContinue to an eoCheckpoint... + +Author: evomarc +Date: Wed Jul 24 18:05:18 2002 +0000 + + There was a problem with the activation of the Ctrl C + +Author: maartenkeijzer +Date: Tue Jul 23 09:34:46 2002 +0000 + + added EO.h to include list + +Author: maartenkeijzer +Date: Tue Jul 23 09:17:59 2002 +0000 + + Run it for 50 generations, it's too fast otherwise :) + +Author: maartenkeijzer +Date: Mon Jul 22 13:35:11 2002 +0000 + + +Author: maartenkeijzer +Date: Mon Jul 22 13:31:55 2002 +0000 + + added a 'nasty_declone_flag' to be able to declone a population + +Author: maartenkeijzer +Date: Mon Jul 22 13:20:04 2002 +0000 + + Added 'sweepline' optimization for eoNDSorting.h + +Author: evomarc +Date: Sat Jul 6 05:24:51 2002 +0000 + + Added eoSequentialSelect.h in the includes + +Author: evomarc +Date: Sat Jul 6 05:23:18 2002 +0000 + + I had left a flaw in teh Ctor (did not accept rates >1) + +Author: evomarc +Date: Fri Jun 21 13:50:39 2002 +0000 + + Changd a const_iterator to iterator in method it_best_element + God (or Maarten :-) knows why this was there + +Author: evomarc +Date: Fri Jun 21 13:30:17 2002 +0000 + + Added the negative rate (-> 1-rate) and the unary operator- (useful + in eoG3Replacement) + +Author: jeggermo +Date: Thu Jun 20 12:38:47 2002 +0000 + + small typo + +Author: evomarc +Date: Wed Jun 19 03:42:54 2002 +0000 + + Replaced ../../src with the DIR_EO macro! + +Author: evomarc +Date: Mon Jun 17 09:19:17 2002 +0000 + + Added include file eoHowMany for self-consistency + +Author: evomarc +Date: Mon Jun 17 09:18:37 2002 +0000 + + Removed eoSequentialSelect + +Author: evomarc +Date: Mon Jun 17 09:13:47 2002 +0000 + + Added the Truncation embedders, and the separate eoSequentialSelect file + +Author: evomarc +Date: Mon Jun 17 09:12:08 2002 +0000 + + Separated eoSequentialSelect from eoRandomSelect.h file + Added eoEliteSequentialSelect, where best is always selected first, useful for + G3 engine + +Author: evomarc +Date: Mon Jun 17 04:51:34 2002 +0000 + + Reshaped the whole code + Added the SequentialSelect selectors + THe generated files are now "hidden" in ResSelect dir (hardcoded!) + +Author: evomarc +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) + +Author: jeggermo +Date: Mon Jun 10 14:10:35 2002 +0000 + + all .dsp files converted from unix to dos format + +Author: evomarc +Date: Wed May 22 02:13:06 2002 +0000 + + I had forgotten the real_value.h - SecondRealEA did not compile! + +Author: jeggermo +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 +Date: Thu May 9 15:43:01 2002 +0000 + + ramped half and half initialization has been added to eoParseTreeDepthInit + +Author: evomarc +Date: Thu May 9 06:35:34 2002 +0000 + + Still introducing ParadisEO + +Author: evomarc +Date: Thu May 9 06:28:34 2002 +0000 + + Added references to ParadisEO and Lesson5 + +Author: evomarc +Date: Wed May 8 06:55:21 2002 +0000 + + Added Lesson5 + +Author: evomarc +Date: Wed May 8 06:52:37 2002 +0000 + + Updated version number + +Author: evomarc +Date: Wed May 8 06:50:58 2002 +0000 + + Adding the Lesson5 - how to create your own genotype + +Author: evomarc +Date: Wed May 8 06:47:50 2002 +0000 + + Added the MyStructLibEA.cpp+make_MyStruct.cpp that allow separate + compilation of representation-indenepent stuff. Modified create.sh script + and Makefile accordingly. See Lesson5 of the tutorial + +Author: evomarc +Date: Wed May 8 06:44:04 2002 +0000 + + an example of how to make a new genotype within EO - see HTML doc + +Author: evomarc +Date: Wed May 8 06:31:18 2002 +0000 + + Replacing Paradiseo(jet7).pdf with paradiseoJet7.pdf because of Unix problems + with names containing commas + +Author: evomarc +Date: Wed May 8 06:14:23 2002 +0000 + + Removed the template_depth argument (since we are finally NOT going for + the fitness_trait stuff). + +Author: evomarc +Date: Fri May 3 05:12:32 2002 +0000 + + Replaced the eoParameterLoader parameter by an eoParser (used everywhere now) + +Author: evomarc +Date: Wed May 1 04:04:15 2002 +0000 + + eoParameterLoader -> eoParser + +Author: evomarc +Date: Wed May 1 02:44:54 2002 +0000 + + THe code for the 1/5th mutation was completely wrong! + +Author: evomarc +Date: Tue Apr 30 05:10:49 2002 +0000 + + Turned the power function to sum - was untractable with long bitstrings + +Author: evomarc +Date: Tue Apr 30 05:07:52 2002 +0000 + + Added the calls to EO::printOn and EO::readFrom in the corresponding methods + so th euser does not forget to use these before writing/reading the actual eo + +Author: evomarc +Date: Tue Apr 30 04:56:39 2002 +0000 + + Added utils/eoUniformInit.h + +Author: evomarc +Date: Tue Apr 30 04:54:25 2002 +0000 + + Copied from eoRndGenerators here is eoUniformInit, same thing but in the eoInit + hierarchy. + Useful to embed into higher levels eoInit + +Author: evomarc +Date: Sun Apr 28 05:04:24 2002 +0000 + + Adding SecondRealEA + +Author: evomarc +Date: Sun Apr 28 04:38:38 2002 +0000 + + Adding SecongRealEA - mainly to prepare Lesson5 about adaptive parameters + +Author: evomarc +Date: Fri Apr 26 03:17:37 2002 +0000 + + Added explanation and examples of getORcreateParam usage + +Author: evomarc +Date: Fri Apr 26 02:39:10 2002 +0000 + + Turned the code that was testing for the existence of the size parameter + in to the call to getORcreateParam (actually, this was where this code + has been tested the first time) + +Author: evomarc +Date: Fri Apr 26 02:37:40 2002 +0000 + + Added the negative argument in Ctor to say that you want number + popSize - some fixed number + +Author: evomarc +Date: Fri Apr 26 02:28:19 2002 +0000 + + Turned the createParam into getORcreateParam so that you can more easily + define them before (e.g. from the problem at hand). + This is useful specially for vecSize as some problems have predefined values + +Author: cahon +Date: Thu Apr 25 14:26:02 2002 +0000 + + *** empty log message *** + +Author: cahon +Date: Thu Apr 25 14:10:22 2002 +0000 + + Adding cellular E.A. + +Author: cahon +Date: Thu Apr 25 14:08:26 2002 +0000 + + A toric topology for cellular E.A. + +Author: cahon +Date: Thu Apr 25 14:06:43 2002 +0000 + + Cellular parallel easy algorithm + +Author: evomarc +Date: Tue Apr 23 09:56:49 2002 +0000 + + Updated the documentation (comments) + +Author: cahon +Date: Tue Apr 23 09:16:51 2002 +0000 + + Slides from Jet7, March 2002, ENSTA Paris + +Author: cahon +Date: Tue Apr 23 09:11:58 2002 +0000 + + *** empty log message *** + +Author: jeggermo +Date: Fri Apr 19 22:13:15 2002 +0000 + + A faulty constructor in eoParseTree caused some problems + +Author: cahon +Date: Fri Apr 19 15:24:07 2002 +0000 + + Slides from Jet7, ENSTA Paris (April 2002) + +Author: music_dev +Date: Fri Apr 19 14:42:47 2002 +0000 + + Multithreaded version. Changed name of lib to eo_lib[d].lib + +Author: evomarc +Date: Fri Apr 19 14:06:50 2002 +0000 + + Templatized apply + added a return statement + +Author: evomarc +Date: Fri Apr 19 14:04:25 2002 +0000 + + Replaced floats by doubles + +Author: jeggermo +Date: Thu Apr 18 13:56:36 2002 +0000 + + new printOn and readFrom functions + (they look more like the eoBit ones) + +Author: evomarc +Date: Thu Apr 18 03:23:24 2002 +0000 + + Ome explanations on how to launch the examples + +Author: evomarc +Date: Thu Apr 18 03:22:47 2002 +0000 + + Added the README, and modified the config files to remove the 127.0.0.1 + that was misleading + +Author: jeggermo +Date: Mon Apr 15 14:12:19 2002 +0000 + + *** empty log message *** + +Author: jeggermo +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 +Date: Fri Apr 12 16:17:02 2002 +0000 + + Changed name of target in all_lib.dsp + Added eoParetoFitness.cpp in sources of eo.dsp + +Author: evomarc +Date: Fri Apr 12 15:13:45 2002 +0000 + + A few changes for MSVC++ compatibility + +Author: evomarc +Date: Fri Apr 12 14:41:52 2002 +0000 + + Turned the specific compiler order mpiCC into a Macro + so it's easier to modify + We shall need to put this into the automatic configure one day ... + +Author: evomarc +Date: Fri Apr 12 14:39:58 2002 +0000 + + Changing the include file that contain all include from + eoparadiseo to eoparadiseo.h + because teh CVS tool in Microsoft Windaube doesn't make the difference + with the directory ParadisEO + +Author: evomarc +Date: Fri Apr 12 14:13:08 2002 +0000 + + Adding ParadisEO Tutorial examples + +Author: evomarc +Date: Fri Apr 12 13:38:08 2002 +0000 + + Added name of the Debug library + +Author: evomarc +Date: Tue Apr 9 08:48:44 2002 +0000 + + Modified the comments so they appear in doxygen doc (and updated them also) + +Author: evomarc +Date: Mon Apr 8 18:04:32 2002 +0000 + + Modified my E-mail address (the old one at Polytechnique will soon be obsolete) + +Author: evomarc +Date: Mon Apr 8 18:03:35 2002 +0000 + + I suddenly realized that BitEA.html was NOT in the repository! + +Author: evomarc +Date: Mon Apr 8 08:50:27 2002 +0000 + + Added the eoIncrementorParam - now ALL pointers allocated in make_checkpoint + are stored somewhere (the generation counter was not) + +Author: evomarc +Date: Mon Apr 8 08:42:46 2002 +0000 + + Check that size > 1 (otherwise division by 0) + +Author: evomarc +Date: Mon Apr 8 08:42:01 2002 +0000 + + Added a few "std::" before copy and ostream_iterator + +Author: evomarc +Date: Mon Apr 1 20:15:32 2002 +0000 + + After indoduction of paradisEO, eoEaseyEA was a subclass of class eoPopAlgo + and not eoAlgo. + I don't have time to investigate, so I went back to a subclass of eoAlgo. + We'll sort that out later (after EuroGP I guess). + +Author: cahon +Date: Fri Mar 29 15:38:15 2002 +0000 + + *** empty log message *** + +Author: cahon +Date: Fri Mar 29 15:36:04 2002 +0000 + + How to build an EA with a distributed evalaution process ? + +Author: cahon +Date: Fri Mar 29 15:30:55 2002 +0000 + + How to build an homo/heterogenous island model of EAs ? + +Author: cahon +Date: Fri Mar 29 15:16:11 2002 +0000 + + *** empty log message *** + +Author: cahon +Date: Fri Mar 29 15:10:04 2002 +0000 + + For any sending message + +Author: cahon +Date: Fri Mar 29 15:05:35 2002 +0000 + + The local communication layer + +Author: cahon +Date: Fri Mar 29 15:04:49 2002 +0000 + + The global communication layer + +Author: cahon +Date: Fri Mar 29 14:59:58 2002 +0000 + + An evaluator which sequentially values individuals making the pop. + +Author: cahon +Date: Fri Mar 29 14:57:30 2002 +0000 + + The slave evaluator node + +Author: cahon +Date: Fri Mar 29 14:56:18 2002 +0000 + + The master dispatcher evaluator + +Author: cahon +Date: Fri Mar 29 14:54:52 2002 +0000 + + An EA with a distributed evaluation process + +Author: cahon +Date: Fri Mar 29 14:50:11 2002 +0000 + + Each island is connected from/to only one neighbour + +Author: cahon +Date: Fri Mar 29 14:49:04 2002 +0000 + + Each island id connected to the whole considered islands + +Author: cahon +Date: Fri Mar 29 14:47:13 2002 +0000 + + A checkpoint to send/receive pop. to/from others islands + +Author: cahon +Date: Fri Mar 29 14:45:00 2002 +0000 + + The island EA model + +Author: cahon +Date: Fri Mar 29 14:41:01 2002 +0000 + + A continuator which periodically returns false + +Author: cahon +Date: Fri Mar 29 14:38:36 2002 +0000 + + A tool to apply a process to any incoming EO ... + +Author: cahon +Date: Fri Mar 29 10:34:16 2002 +0000 + + *** empty log message *** + +Author: cahon +Date: Fri Mar 29 10:26:36 2002 +0000 + + *** empty log message *** + +Author: cahon +Date: Fri Mar 29 10:02:47 2002 +0000 + + The paradiseo interface + +Author: cahon +Date: Wed Mar 27 17:31:05 2002 +0000 + + Some changes for the use in paradisEO + +Author: cahon +Date: Wed Mar 27 17:28:04 2002 +0000 + + Defines any population-based algorithm. + +Author: cahon +Date: Wed Mar 27 17:19:25 2002 +0000 + + Any EO with an invalid fitness should be printable ! + +Author: evomarc +Date: Fri Mar 22 11:01:30 2002 +0000 + + Added the time counter in make_checkpoint + +Author: evomarc +Date: Fri Mar 22 10:57:37 2002 +0000 + + Added the eoTimeCounter that allows to use time as a base counter + for statistics (when you compare things that are not using the same + evaluation function for instance) + +Author: evomarc +Date: Fri Mar 15 06:41:54 2002 +0000 + + Added the lonk to SourceForge in the title, and to README in the "install" section + +Author: evomarc +Date: Fri Mar 15 06:28:25 2002 +0000 + + The source file names had changed, some day, in doxygen-genertaed doc ... + +Author: evomarc +Date: Fri Mar 15 06:06:22 2002 +0000 + + Corrected a few linkgs to the documentation + Reaplced eoBin with eiBit (about time!!!) + +Author: evomarc +Date: Wed Mar 6 06:54:00 2002 +0000 + + More on parameter input (getORcreateParam explained) + +Author: evomarc +Date: Wed Mar 6 06:28:27 2002 +0000 + + Added the tags to generate html nice output + +Author: evomarc +Date: Wed Mar 6 06:25:40 2002 +0000 + + Added some explanations about the memory mangement (through eoFunctorStore) + +Author: evomarc +Date: Tue Mar 5 05:46:55 2002 +0000 + + Corrected a sligth error in eoParamParam reading that resulted in making the comma + part of the stored string value + +Author: evomarc +Date: Tue Mar 5 05:38:21 2002 +0000 + + Adding class eoParetoOneConstraintFitness, multi-valued fitness + 1 constraint + This file shoudl contain the general Pareto+contraint class - but + I'm in a big hurry. + +Author: evomarc +Date: Tue Mar 5 05:34:27 2002 +0000 + + Changed the reading of parameter resDir from createParam to getORcreateParam + so it can be used in other parts of hte program (it's handy to put all + disk outputs in one dir). + +Author: evomarc +Date: Mon Feb 11 06:28:52 2002 +0000 + + Added file monitors for the population in the Pareto space (were ony available as + eoGnulpot1DSnapshors before) + +Author: evomarc +Date: Mon Feb 11 06:27:44 2002 +0000 + + Added a title (Gen. X) to the plot so you can follow what's going on + +Author: evomarc +Date: Mon Feb 11 06:26:48 2002 +0000 + + Added the getCounter() method so subclasses have a hand on the generation nb + +Author: evomarc +Date: Sat Feb 9 05:01:48 2002 +0000 + + Corrected a serious bug in eoUniformMutation (double declaration of bool HasChanged) + The consequence was that if that mutation was the only operator called on some + individual, it was not invalidated, and hence its fitness not recomputed!!! + +Author: evomarc +Date: Sat Feb 9 04:58:33 2002 +0000 + + First instances of the make_xxx_pareto, where xxx is algo, continue and checkpoint + +Author: evomarc +Date: Fri Feb 8 07:51:59 2002 +0000 + + Added the constructor from a string + +Author: evomarc +Date: Fri Feb 8 07:49:32 2002 +0000 + + Added the method getORcreateParam. + It has exactly the same syntax than the createParam method + but it first checks whether the param has been laready entered before creating it + +Author: evomarc +Date: Fri Feb 8 07:48:03 2002 +0000 + + Added a constructor from a vector - mandatory in all applications + +Author: evomarc +Date: Fri Feb 8 07:47:03 2002 +0000 + + Removed the const in method eoInit & atomInit() + +Author: jeggermo +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 +Date: Mon Feb 4 13:16:50 2002 +0000 + + Fixed some compatibility issues with GCC 3.0.1 and the Intel C++ Compiler + for Linux v5. + +Author: evomarc +Date: Sat Feb 2 07:37:54 2002 +0000 + + Added warning in case number of objective is changed (and not set) + +Author: evomarc +Date: Sat Feb 2 07:36:58 2002 +0000 + + Suppressed the lt_arity fn that was added for MSVC - and now seems unnecessary + +Author: evomarc +Date: Sat Feb 2 07:36:12 2002 +0000 + + Added warning test + +Author: evomarc +Date: Sat Feb 2 07:34:13 2002 +0000 + + Added newline at end of file (to suppress g+ warning) + +Author: evomarc +Date: Sat Feb 2 07:05:31 2002 +0000 + + Added the eoVariableParetoTraits (setup number of objcetives and min/max + at run time). + +Author: evomarc +Date: Sat Feb 2 06:43:46 2002 +0000 + + Moved the static variables of class eoVariableParetoTraits + into a separate .cpp file (eoParetoFitness.cpp) - and modified Makefile.am + +Author: evomarc +Date: Sat Feb 2 05:59:05 2002 +0000 + + Added default value for bool arg in testDirRes function + +Author: evomarc +Date: Sat Feb 2 05:51:31 2002 +0000 + + Removed comment after #endif (warning in gcc 1.96+) + +Author: evomarc +Date: Thu Jan 31 17:42:03 2002 +0000 + + Added the eoVariableParetoTraits that allows to specify the number + of objectives and the max/min for each one at run-time + +Author: evomarc +Date: Thu Jan 31 17:32:27 2002 +0000 + + Updated the comments + +Author: evomarc +Date: Wed Jan 30 12:24:42 2002 +0000 + + Added Ranking (God knows why it was mnissing!) + +Author: evomarc +Date: Thu Jan 17 17:57:55 2002 +0000 + + Added the move from Release and DEbug into the lib dir + +Author: evomarc +Date: Thu Jan 17 17:54:56 2002 +0000 + + Removed the #ifdef that protected the lt_arity avaints MSVC (!!!) + +Author: evomarc +Date: Thu Jan 17 17:51:58 2002 +0000 + + apply -> apply for MSVC + +Author: evomarc +Date: Thu Jan 17 17:51:02 2002 +0000 + + Protexted all calls to gnuplot for MSVC + +Author: evomarc +Date: Thu Jan 17 15:24:44 2002 +0000 + + Adding tutorial files + +Author: evomarc +Date: Thu Jan 17 15:21:44 2002 +0000 + + New versio of dsp files + +Author: maartenkeijzer +Date: Wed Jan 16 14:52:11 2002 +0000 + + Increased template depth + +Author: evomarc +Date: Thu Dec 20 18:04:52 2001 +0000 + + There was an error in the type of the first parameter of make_checkpoint and + make_algo_scalar (changed from eoParameterLOader to eoParser) + +Author: evomarc +Date: Fri Dec 7 06:28:38 2001 +0000 + + COnverted t_eoesall to CRLF line terminators (otherwise MSDEV cannot read properly) + +Author: evomarc +Date: Fri Dec 7 06:23:15 2001 +0000 + + Adding t_eoesall that somehow ahd managed to escape until now + + corrected the template test_dsp.tmpl + +Author: evomarc +Date: Fri Dec 7 06:14:11 2001 +0000 + + Adding the tutorials in MSVC project files + +Author: evomarc +Date: Fri Dec 7 05:51:36 2001 +0000 + + Removed all references to CrtDebug blabla that were supposed to be + MSVC specific but generated an error with MSVC 6.0 + +Author: evomarc +Date: Thu Dec 6 14:33:42 2001 +0000 + + Need to put the \r\n at end of all files after modifications!!! + +Author: evomarc +Date: Thu Dec 6 14:32:00 2001 +0000 + + Removed unknown CrtDebug directives from the MSVC version + +Author: evomarc +Date: Thu Dec 6 13:12:24 2001 +0000 + + Removed unnecessary dirs, added first Lesson of tutorial + +Author: evomarc +Date: Thu Dec 6 11:36:39 2001 +0000 + + Removed some sources that came here nobody know's how (thanks, MSDEV) + +Author: evomarc +Date: Thu Dec 6 07:02:07 2001 +0000 + + Changed ALL names of links to class files in the documentation due to the change in + Doxygen naming convention + +Author: evomarc +Date: Thu Dec 6 06:44:44 2001 +0000 + + A few corrections before the big name change + +Author: evomarc +Date: Thu Dec 6 06:38:17 2001 +0000 + + CHanged a few erroneaous comments + +Author: evomarc +Date: Wed Dec 5 06:54:38 2001 +0000 + + Added GNUPLOT protection for MSVC compiler + +Author: jeggermo +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 +Date: Tue Dec 4 11:49:25 2001 +0000 + + a different solution for lt_arity has been implemented (this time inside the + eoParseTreeDepthInit class + +Author: evomarc +Date: Mon Dec 3 16:40:32 2001 +0000 + + Renamed mastermind.cc into mastermind.cpp for MSVC + +Author: evomarc +Date: Mon Dec 3 16:38:52 2001 +0000 + + Renamed main.cc into main.cpp for MSVC + +Author: evomarc +Date: Mon Dec 3 16:35:51 2001 +0000 + + Renamed gprop.cc into gprop.cpp for MSVC + +Author: evomarc +Date: Mon Dec 3 16:28:30 2001 +0000 + + Modified the path of include eoVirus because MSVC did not find it. + Now it is assumed that src will be in the include search path, that's all. + +Author: evomarc +Date: Mon Dec 3 14:31:35 2001 +0000 + + MSVC didn't find (easily) the contrib/MGE dir. So now it's written in the code + and the Makefile.am does not have contrib in the include look path + +Author: evomarc +Date: Mon Dec 3 14:20:24 2001 +0000 + + Added partial specialization of lt_arity .. + +Author: evomarc +Date: Mon Dec 3 14:14:56 2001 +0000 + + Added the 2 fake "projects" all_lib.dsp and all_test.dsp that allow to compile + everything in 2 clics. + However, we still cannot run and watch the status output of the test executables + +Author: evomarc +Date: Mon Dec 3 11:08:17 2001 +0000 + + More details to make code MSVC-compatible + +Author: evomarc +Date: Mon Dec 3 06:59:17 2001 +0000 + + Added links to some examples in the comments + +Author: evomarc +Date: Mon Dec 3 06:56:43 2001 +0000 + + Removed dir win from list of subdirs (generated an error in make check) + +Author: evomarc +Date: Mon Dec 3 06:53:52 2001 +0000 + + Removed the trailing comment after #endif (Warning in MSVC) + +Author: jeggermo +Date: Thu Nov 22 15:01:11 2001 +0000 + + Fixed a small problem with eoPointMutation. + +Author: evomarc +Date: Sun Nov 18 07:18:11 2001 +0000 + + Introductory comment evolves ... + +Author: evomarc +Date: Sun Nov 18 06:54:13 2001 +0000 + + Added the names of the directories where the newly created files are stored. + +Author: evomarc +Date: Sat Nov 17 08:13:55 2001 +0000 + + Now the eo.dsw can be generated automatically from + eo.org + create_all_dsp.sh (that calls create_dsp.sh) + To add a new test program, simpy add 1 line in create_all_dsp.sh + and run it. + DO NOT TOUCH eo.org !!! + +Author: evomarc +Date: Sat Nov 17 07:58:16 2001 +0000 + + imply put all program names on one single line to ease bulding the win files + +Author: evomarc +Date: Sat Nov 17 07:55:39 2001 +0000 + + Bug in create_dsp when no additional library + +Author: evomarc +Date: Sat Nov 17 07:54:12 2001 +0000 + + Turned bonary_value into the onemax (not pow that exploded for even only + moderately small size of genome!) + Turned it into a double (it was a float) as floats are dead and should dissappear + +Author: evomarc +Date: Sat Nov 17 07:22:59 2001 +0000 + + Changes due to MSVC + +Author: evomarc +Date: Fri Nov 16 15:06:29 2001 +0000 + + Some error for MSVC that was not even a warning for g++ (but I'm sorry + to say that MSVC is right :-) + +Author: evomarc +Date: Fri Nov 16 15:05:41 2001 +0000 + + Changed the filenaming to comply with MacroHard + +Author: evomarc +Date: Fri Nov 16 15:02:35 2001 +0000 + + Error in argments check + +Author: evomarc +Date: Fri Nov 16 14:32:07 2001 +0000 + + The file eo.org is the base project file (no file in test involved). + It is upgraded by the create.sh script + +Author: evomarc +Date: Fri Nov 16 14:30:58 2001 +0000 + + Adding all test files for MSVC + +Author: evomarc +Date: Fri Nov 16 14:01:52 2001 +0000 + + Replaced the flat definitions of ncecessary classes (eoStatxxx and eoMonitor) + with the include of the corresponding .h file. as MSVC complained! + +Author: jeggermo +Date: Thu Nov 15 22:11:31 2001 +0000 + + small change in documentation + +Author: evomarc +Date: Mon Nov 12 16:27:37 2001 +0000 + + Announcing the MSVC++ compatibility revisited + +Author: evomarc +Date: Mon Nov 12 15:21:40 2001 +0000 + + A few more typename conditionally removed for MSVC++ + +Author: evomarc +Date: Mon Nov 12 14:59:32 2001 +0000 + + Adding Jeroen :-) + +Author: evomarc +Date: Mon Nov 12 14:51:51 2001 +0000 + + A readme for the win dir ... + +Author: evomarc +Date: Mon Nov 12 14:44:01 2001 +0000 + + Create.sh mdified to also add the new dsp file into eo.dsw + +Author: evomarc +Date: Mon Nov 12 14:27:12 2001 +0000 + + Template file for dsp project files (to be used within create_dsp.sh) + +Author: evomarc +Date: Mon Nov 12 14:17:58 2001 +0000 + + Some more small changes for MSVC++ compatibility + +Author: evomarc +Date: Sun Nov 11 06:59:42 2001 +0000 + + Adding the dsp file for t-eoReal - testing the create_dsp script. + Next step is to add them all from the test/Makefile file + +Author: evomarc +Date: Sun Nov 11 06:55:12 2001 +0000 + + Create_dsp.sh is a script that will create the .dsp file from a source file + name in the test dir + +Author: evomarc +Date: Sun Nov 11 06:43:45 2001 +0000 + + Improved the UI a lot (checking for already existing files, etc) + +Author: evomarc +Date: Sat Nov 10 14:13:21 2001 +0000 + + Files for MSVC++ generated by Olivier Meunier - Projet Fractales - INRIAC + +Author: evomarc +Date: Sat Nov 10 14:12:01 2001 +0000 + + Files for MSVC++ generated by Olivier Meunier - Projet Fractales - INRIA + +Author: evomarc +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 + +Author: evomarc +Date: Sat Nov 10 06:59:02 2001 +0000 + + Added the #pragma directive for MSVC++ in all .cpp + +Author: evomarc +Date: Sat Nov 10 06:32:05 2001 +0000 + + Added the invalidate() call - that bug was not seem before, because + we always used init on newborn genotypes! + +Author: maartenkeijzer +Date: Thu Nov 8 11:13:19 2001 +0000 + + Cleaned up + +Author: maartenkeijzer +Date: Thu Nov 8 10:17:52 2001 +0000 + + removed the return 1 in the main + +Author: evomarc +Date: Thu Nov 8 07:40:27 2001 +0000 + + Adding Distribution-based base abstract classes + +Author: evomarc +Date: Thu Nov 8 06:53:55 2001 +0000 + + Adding PBIL + +Author: evomarc +Date: Thu Nov 8 06:49:38 2001 +0000 + + Adding PBIL files - simple PBIL algorithm with simple additive update rule + +Author: evomarc +Date: Thu Nov 8 06:14:59 2001 +0000 + + I have changed all calls to use an eoParser rather than an eoParameterLoader + This is required if you want to use the method getParamWithLongName that allows + one to get a value of a parameter read somewhere else. + After changing 3 calls due to that, I decided to change ALL calls within + the make_xxx functions + +Author: evomarc +Date: Wed Nov 7 16:25:01 2001 +0000 + + Corrected a bug in the selector and replacement tournamemt parameter reading: + if you did not give the tournament sizes, the program either crashed or went + in some endless loop. + I also simplified the reading of those eoParamPram parameters! + +Author: maartenkeijzer +Date: Wed Nov 7 15:23:24 2001 +0000 + + Updated makefile.am such that "make check" will run all test programs. Fixed + a number of erronuous return values that made the script fail. What's left + is let Marc clean up the mess he made with t-eoReal and t-eoRealAllESAllAgain + +Author: maartenkeijzer +Date: Wed Nov 7 10:57:53 2001 +0000 + + Fixed call to inverse_stochastic inside eoDetTournament + +Author: evomarc +Date: Mon Nov 5 16:38:52 2001 +0000 + + Added method + eoParam* getParamWithLongName(std::string _name); + so now you can get a parameter in another place than where it was defined + just by giving its name + +Author: maartenkeijzer +Date: Mon Nov 5 14:28:14 2001 +0000 + + Just some comments + +Author: evomarc +Date: Mon Nov 5 08:24:59 2001 +0000 + + Small error in header + +Author: jeggermo +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 +Date: Thu Oct 25 10:39:55 2001 +0000 + + Some changes for using EO with libstdc++V3 and gcc-3.01 + +Author: jeggermo +Date: Fri Oct 19 12:04:12 2001 +0000 + + The nameless union in node.h has been removed because not all compilers + support it. + +Author: evomarc +Date: Thu Oct 18 11:48:52 2001 +0000 + + Replaced pushd and popd with cd and cd .. - for Windows/Cygwin compatibility + +Author: jeggermo +Date: Thu Oct 18 08:52:40 2001 +0000 + + Some changes to make gpsymreg compile correctly on windows/cygwin systems + +Author: evomarc +Date: Thu Oct 18 05:30:45 2001 +0000 + + Added MAXFLOAT and MINFLOAT as it seems that Cygwin needs that ??? + +Author: evomarc +Date: Thu Oct 18 04:57:30 2001 +0000 + + iAdding a file config.cache as it seems that the defaults don't work + in Windows/Cygwin environement. Thanks to Sebastiao CORREIA and + Jerome JEAN-CHARLES for providing this file. + +Author: evomarc +Date: Thu Oct 18 04:37:14 2001 +0000 + + All files on one line in Makefile.am (for Windows) + +Author: evomarc +Date: Thu Oct 18 04:34:58 2001 +0000 + + Modified the Makefile.am in main dir, and Makefile in tutorial dir to remove + all pushd/popd as they don't exist in Windows/bash + +Author: evomarc +Date: Wed Oct 17 17:49:54 2001 +0000 + + Corrected a few small problems - including dependencies in Makefile + thanks to Sebastiao CORREIA for pointing them out + +Author: evomarc +Date: Wed Oct 17 17:48:50 2001 +0000 + + Corrected a few small problems - + thanks to Sebastiao CORREIA for pointing them out + +Author: evomarc +Date: Mon Oct 8 09:14:15 2001 +0000 + + Removed trailing text after #endif - causes warning on many compilers + +Author: jeggermo +Date: Fri Oct 5 12:39:30 2001 +0000 + + ramped half and half initialization procedure for eoParseTree populations + added. + +Author: jeggermo +Date: Fri Oct 5 09:32:49 2001 +0000 + + Since g++ 2.95.x on our solaris server doesn't have macros to check + for infinity and NaN these checks have been removed from the source code + and a protected divided function node is now used. + +Author: evomarc +Date: Fri Oct 5 03:56:21 2001 +0000 + + Forgot to double also the parameter to initialize in the Ctor! + +Author: evomarc +Date: Fri Oct 5 03:51:15 2001 +0000 + + Modified the reseed method in RNG class so two different seeds give different + sequences, after Jeroen's remark (jeggermo@liacs.nl) + +Author: evomarc +Date: Fri Oct 5 03:30:12 2001 +0000 + + Commented out the oeprator() default function in base class: I find it more secure + to be warned at compile time that one function is still pure virtual + than to look for the error after a run-time-error that gives no clue + +Author: evomarc +Date: Thu Oct 4 20:13:03 2001 +0000 + + eoMyStructEA.cpp has turned into MyStructEA.cpp + +Author: evomarc +Date: Thu Oct 4 20:12:19 2001 +0000 + + Big modifications - now the init and most important the operators + are handled in separate files make_genotype_xxx and make_op_xxx + as it was done in the examples of Lesson4 + +Author: evomarc +Date: Mon Sep 24 05:59:42 2001 +0000 + + Suppressed most warning (except some unused variables) if you don't modify anything + +Author: evomarc +Date: Mon Sep 24 05:59:13 2001 +0000 + + Suppressed most warning (except some unused variables) if you don't modify anythig + +Author: evomarc +Date: Sat Sep 8 05:59:17 2001 +0000 + + Removed trailing string after #endif - it generates a lot of useless warning + on some versions of g++ + +Author: evomarc +Date: Sat Sep 8 05:42:24 2001 +0000 + + Added newline at end of file (prevents a warning) + +Author: evomarc +Date: Sat Sep 8 05:41:19 2001 +0000 + + Added include math.h + +Author: evomarc +Date: Tue Sep 4 08:35:22 2001 +0000 + + Added many template files, and totally modified the comments in most other. + This was when preparing Evonet Summer School - though it finally was not used there! + +Author: evomarc +Date: Tue Sep 4 06:51:59 2001 +0000 + + Modified the className() method so that the Atom underlying operator is listed + +Author: evomarc +Date: Tue Sep 4 06:50:42 2001 +0000 + + Included apply.h for consistency (though in most cases it was included from eo file + +Author: evomarc +Date: Tue Sep 4 06:48:15 2001 +0000 + + Added a class that turns an eoInit into a generator of EOT + Also added a Ctor of variable length objects that take an eoInit. + Some day we might want to clean all that stuff ... unless we leave + the choice to the user (but then the documentation shoudl be as clear + as glass, which it is not at the moment!) + +Author: evomarc +Date: Tue Sep 4 06:45:14 2001 +0000 + + In case you are trying to assign a value to a vector of different size, + previous versions raised an exception. + Now a simple warning is written to stderr - as it might be something + you need to do. + +Author: evomarc +Date: Tue Sep 4 06:43:19 2001 +0000 + + Added make_help in checkpointing, included stdexcept in eoParam. Comments + updates ... + +Author: evomarc +Date: Tue Sep 4 06:41:34 2001 +0000 + + Spotted and commented (but NOT corrected :-( a bug in case the ResDir + exists and is empty + +Author: evomarc +Date: Tue Sep 4 06:40:28 2001 +0000 + + Corrected wrong arguments for the 2D Ctor + +Author: evomarc +Date: Tue Sep 4 06:37:25 2001 +0000 + + Comments update + +Author: evomarc +Date: Tue Sep 4 06:35:58 2001 +0000 + + Changed the wrong #ifdef in make_algo_scalar (+ minor comments elsewhere) + +Author: jeggermo +Date: Tue Jul 17 13:06:28 2001 +0000 + + check for the existence of isinf didn't work the way it should so + it has been removed + +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 + added point mutation for strongly typed genetic programming + added hoist mutation for strongly typed genetic programming + +Author: evomarc +Date: Wed Jul 11 06:26:11 2001 +0000 + + Suppressed the gene mutations, as they are now in eoFlOrMonOp.h + +Author: evomarc +Date: Wed Jul 4 04:59:02 2001 +0000 + + Oups! + +Author: evomarc +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. + +Author: evomarc +Date: Tue Jul 3 12:56:44 2001 +0000 + + Added the eoPopEvalFunc class: gets the full parents + offspring populations + in order to evaluate them. + 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 + +Author: jeggermo +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) + + base documentation written for: + * eoParseTree + * eoGpDepthInitializer + * eoSubtreeXOver + * eoBranchMutation + * eoPointMutation + * 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 +Date: Mon Jul 2 11:38:27 2001 +0000 + + The constructor for the eoGpDepthInitializer has been extended with a + sort of the initializor vector containing all possible nodes. This sort + assures that the terminals are in the front of vector. Untill now this + was assumed but not checked or enforced. + +Author: jeggermo +Date: Mon Jul 2 08:28:40 2001 +0000 + + eoSubtreeXOver fixed + +Author: evomarc +Date: Sat Jun 30 05:59:26 2001 +0000 + + Added random selection + +Author: evomarc +Date: Sat Jun 30 05:57:10 2001 +0000 + + Corrected a wrong comment + +Author: maartenkeijzer +Date: Fri Jun 29 18:06:10 2001 +0000 + + oops, thanks jeroen + +Author: jeggermo +Date: Fri Jun 29 12:15:15 2001 +0000 + + checks for the existence of finite(x) and isinf(x) built into app/gpsymreg. + Linux gcc compilers have the 'macros ??' but solaris gcc does not + +Author: jeggermo +Date: Fri Jun 29 09:22:26 2001 +0000 + + app/gpsymreg/Makefile added to configure.in + +Author: jeggermo +Date: Thu Jun 28 15:03:53 2001 +0000 + + app/gpsymreg/Makefile added to configure.in + +Author: jeggermo +Date: Thu Jun 28 14:39:36 2001 +0000 + + addition file for parameters for symreg gp + +Author: jeggermo +Date: Thu Jun 28 14:38:00 2001 +0000 + + node.h containing Tree-node classes for symreg gp + +Author: jeggermo +Date: Thu Jun 28 14:33:51 2001 +0000 + + main.cc for symreg gp + +Author: jeggermo +Date: Thu Jun 28 14:26:35 2001 +0000 + + gp symbolic regression trees added + +Author: jeggermo +Date: Thu Jun 28 14:18:47 2001 +0000 + + eoGpMutate.h added containing 4 new mutation operators for eoParseTree class + +Author: jeggermo +Date: Thu Jun 28 14:11:04 2001 +0000 + + Symbolic Regression GP added app-dir + +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 + * Hoist + +Author: jmerelo +Date: Thu Jun 21 12:03:17 2001 +0000 + + Updating Royal Road + +Author: maartenkeijzer +Date: Mon Jun 11 12:37:21 2001 +0000 + + Added a check for an empty initializor + +Author: evomarc +Date: Fri May 25 16:27:59 2001 +0000 + + Added a frequency parameter to eoPopStat (dump pop every N gen) + +Author: evomarc +Date: Mon May 21 06:13:56 2001 +0000 + + Forgot to update ESEA with crossover + +Author: evomarc +Date: Mon May 21 04:16:26 2001 +0000 + + ? + +Author: evomarc +Date: Mon May 21 04:15:36 2001 +0000 + + Added libes in Makefile + +Author: evomarc +Date: Mon May 21 04:14:36 2001 +0000 + + Modifs in es (crossover added in make_op_es). + Added a dummy selector in eoReandomSelect that does work even with invalid EOs + +Author: evomarc +Date: Mon May 21 04:13:10 2001 +0000 + + Added the crossover in make_op_es (parameters were read, but that's all! + +Author: evomarc +Date: Mon May 21 04:10:55 2001 +0000 + + Normalized real_value + +Author: evomarc +Date: Sat May 19 06:15:01 2001 +0000 + + Changed name of eoEsLocalXover to eoEsStandardXover and made it an eoBinOp + Removed obsolete eoEsStdevXOver.h (see eoEsStandardXover.h above) + +Author: evomarc +Date: Fri May 18 17:46:33 2001 +0000 + + Coreected a cut-and-paste bug :-( + +Author: jmerelo +Date: Fri May 18 07:33:12 2001 +0000 + + Added the missing file + +Author: evomarc +Date: Fri May 18 03:59:22 2001 +0000 + + Removed remaining debugging comment + +Author: jmerelo +Date: Thu May 17 10:08:25 2001 +0000 + + Changed MGE to the contrib dir. No need to change the prefix, I guess + +Author: jmerelo +Date: Thu May 17 07:29:50 2001 +0000 + + Added missing files and updated old MGE files + +Author: jmerelo +Date: Fri May 11 10:44:01 2001 +0000 + + Added Royal Road, MGE now work with it, small modifications to eoPopStat + +Author: jmerelo +Date: Thu May 10 12:16:00 2001 +0000 + + Added 'Viral' operators with test. Implements the Mobile Genetic Elements Technique + +Author: evomarc +Date: Tue May 8 04:44:30 2001 +0000 + + CHanged CXXFLAGS to nothing - so lib files remain of manageable size! + +Author: evomarc +Date: Tue May 8 04:41:51 2001 +0000 + + Bing change in eoRealBounds: it is now deriving from eoPersistent. + More important, the eoRealVectorBounds, vectorized version (a vector + has also become an eoPersistent object and now derives from an eoRealBaseVectorBounds + class. + A useful consequence (and actual motivatino) was to be able to have soem + eoValueParam with all possibilities for input + (see doc for Lesson4 in the tutorial for the syntax). + +Author: evomarc +Date: Tue May 8 03:49:35 2001 +0000 + + In eoParser::readFrom, added a test to avoid reading non-parser sections + as these generally contain many -xxx that generate a reading error + when xxx is not a keyword. + This allows to use State-savec files directly as parameter files + +Author: evomarc +Date: Mon May 7 07:13:36 2001 +0000 + + Replaced stupid eoRateParam by eoValueParam + Had to transform eoHowMany into an eoPersistent ... + +Author: evomarc +Date: Fri May 4 16:51:29 2001 +0000 + + A full working version of ES is now available in tutorial/Lesson4, + that makes full use of libes.a. + The user guide is in Lesson4 of the tutorial - programmer's guide + will come later. + Plus many small changes here and there + +Author: evomarc +Date: Fri May 4 16:13:37 2001 +0000 + + Removing old trash! + +Author: evomarc +Date: Thu May 3 17:20:27 2001 +0000 + + Corrected a problem in eoEsChromInit (it refused plain eoReal) + some + other minor modications (e.g. a dir in make_checkpoint where ALL file + will go). + +Author: evomarc +Date: Thu May 3 13:06:34 2001 +0000 + + Adding code to Lesson4 + +Author: evomarc +Date: Thu May 3 05:44:29 2001 +0000 + + Lesson4 advancing + +Author: evomarc +Date: Thu May 3 05:43:40 2001 +0000 + + Hange of comments and names + +Author: evomarc +Date: Wed May 2 11:13:40 2001 +0000 + + Updated main pages of doc and tutorial. Doc now points to tutorial + +Author: evomarc +Date: Wed May 2 11:12:55 2001 +0000 + + Date change + info about Lesson4 in main tutorial page + +Author: evomarc +Date: Wed May 2 11:09:57 2001 +0000 + + Adding test file for ES - note that it's completely different from old + eoESFull.cp - and hence has an other name, t-eoESAll.cpp. + Old eoESFull.cp is still there (and working) but is not in the test targets + +Author: evomarc +Date: Wed May 2 10:57:35 2001 +0000 + + Adding files in es for ES Crossovers + +Author: evomarc +Date: Wed May 2 10:54:17 2001 +0000 + + Forgotten file ... + +Author: evomarc +Date: Wed May 2 10:53:14 2001 +0000 + + Forgotten new file + +Author: evomarc +Date: Wed May 2 10:50:01 2001 +0000 + + Added the new eoEsXXXover.h in Malefile.am + +Author: evomarc +Date: Wed May 2 10:47:56 2001 +0000 + + Forgotten ES files + start of tutorial Lesson4 (about make_XXX) + +Author: evomarc +Date: Wed May 2 10:42:32 2001 +0000 + + Adding Evolution Strategies: + 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 + +Author: evomarc +Date: Tue May 1 05:00:29 2001 +0000 + + Removing make_help.cpp + +Author: evomarc +Date: Mon Apr 30 13:24:42 2001 +0000 + + Some changes in names, before too many users have to modify their code :-) + Changed es.h in src/es into make_es.h (was ambiguous with src/es.h) + 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!). + +Author: evomarc +Date: Mon Apr 30 13:01:07 2001 +0000 + + Some changes in names, before too many users have to modify their code :-) + Changed es.h in src/es into make_es.h (was ambiguous with src/es.h) + 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!). + +Author: evomarc +Date: Mon Apr 30 12:26:31 2001 +0000 + + Some changes in names, before too many users have to modify their code :-) + Changed ga.h in src/ga into make_ga.h (was ambiguous with src/ga.h) + Chenged 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!) + +Author: evomarc +Date: Mon Apr 30 09:26:37 2001 +0000 + + Changed EA basic image: + - caption changed from population-parents to parents-genitors + - quality improved (now 177Ko instead of 53 :-( + +Author: evomarc +Date: Sun Apr 29 05:03:05 2001 +0000 + + Re-introduced the old ctors for the mutations (for backward compatibility + with the tutorial :-( + +Author: evomarc +Date: Sat Apr 28 06:06:21 2001 +0000 + + Declarations for make_xxx_real.cpp files - for eoReal genotypes + Was previously es.h - now es.h is specifically for ES genotypes + +Author: evomarc +Date: Sat Apr 28 05:53:37 2001 +0000 + + Adding first bricks of ES algorithm - make_XXX_es.cpp + +Author: evomarc +Date: Sat Apr 28 05:47:18 2001 +0000 + + Added bounds to the real operators in make_XXX (and hence in t-eoReal) + +Author: evomarc +Date: Fri Apr 27 04:03:16 2001 +0000 + + Removed the -O2 from ga and es dirs - it takes waaaaaaaaaaaaay too much time + at least with g++ 2.95.3 + +Author: evomarc +Date: Thu Apr 26 15:47:37 2001 +0000 + + The declaratio file for all make_* + +Author: evomarc +Date: Thu Apr 26 15:35:30 2001 +0000 + + Removing eoRealBounds from Makefile.am + +Author: evomarc +Date: Thu Apr 26 15:31:48 2001 +0000 + + An initializer of eoReal that uses bounds + +Author: evomarc +Date: Thu Apr 26 15:27:48 2001 +0000 + + Adding all make_*_real.* - similar to ga stuff for eoReal (not ES yet) + +Author: evomarc +Date: Thu Apr 26 15:24:53 2001 +0000 + + Doing libes.a in src/es and adding t-eoReal.cpp in test + I had to move eoRealBounds to utils dir because of global objects + Some domino consequences here and there ... + +Author: evomarc +Date: Tue Apr 24 09:42:01 2001 +0000 + + Changed obscure comment into more detailed one + +Author: evomarc +Date: Tue Apr 24 05:13:10 2001 +0000 + + CLeaning up + +Author: evomarc +Date: Tue Apr 24 05:08:08 2001 +0000 + + Forgot the 2 representation dependent make_XXX.h + +Author: evomarc +Date: Tue Apr 24 05:05:09 2001 +0000 + + Adding eoEvalContinue + +Author: evomarc +Date: Tue Apr 24 05:03:54 2001 +0000 + + Cleaning up + +Author: evomarc +Date: Tue Apr 24 04:56:12 2001 +0000 + + eoEvalFuncCounter is now in a separate file + +Author: evomarc +Date: Tue Apr 24 04:52:04 2001 +0000 + + The new libga + Apart from big changes in the src/ga dir, and the addition of the src/do dir + it also generated a few changes here and there, e.g. some include file still + missing. Also removed some warning from some test files. + +Author: evomarc +Date: Fri Apr 13 08:57:40 2001 +0000 + + Few cosmetic modifs: + put the #define of some boolean in eoData.h + added some include that were missing (unnoticed because of include) + some checks in eoXXXTournamentSelect + +Author: evomarc +Date: Thu Apr 12 16:46:55 2001 +0000 + + Added eoCloneOps.h that contains ... cloning instances of eoXXXOp (all in + 1 file, sorry JJ). + Modified eo - also added a few comments there + +Author: evomarc +Date: Thu Apr 12 05:35:05 2001 +0000 + + Modified the default behavior of eoCountedStateSaver to save the final population. + So if you don't want any population save, don't use any eoCountedStateSaver. + +Author: evomarc +Date: Thu Apr 12 05:29:34 2001 +0000 + + Added a new boolean argument to the ctor of eoBitMutation: + you can now specify a rate-per-bit that will be normalized by the chromSize + +Author: evomarc +Date: Thu Apr 12 05:28:23 2001 +0000 + + Added a few "virtual" that were missing + +Author: evomarc +Date: Wed Apr 11 12:01:51 2001 +0000 + + Changed all variables named howmany into combien (French for how many) + because of a silly problem on Solaris (howmany seems to be some macro???) + +Author: evomarc +Date: Wed Apr 11 04:44:39 2001 +0000 + + Modified printOn so that parameters that are not set explicitely by the user + are commented out - but still appear. Uses the (now public and pure virtual + in the base class eoParameterLoader) method isItThere. + +Author: evomarc +Date: Tue Apr 10 15:08:09 2001 +0000 + + Added the pure virtual isItThere method in base class eoParameterLoader + Also made the corresponding isItThere method in eoParser public. + This allows one to test if the user did actually input a given parameter + and thus not to write it in the output if not - as we want the output + of printOn to be "as identical as possible" to the actual user input + +Author: evomarc +Date: Mon Apr 9 16:03:18 2001 +0000 + + eoCtrlCcontinue had a few remaining errors :-( + +Author: evomarc +Date: Mon Apr 9 15:28:24 2001 +0000 + + Modified the eoCtrlCContinue - had to create the eoCtrlCContinue.cpp + to make t-eoGA work (you should NOT have separate functions in .h files!) + I also included everything related to Ctrl C handling in #ifndef _MSC_VER + until someone tells me how to do it in MSVC + +Author: evomarc +Date: Mon Apr 9 14:20:48 2001 +0000 + + Sorry, last check in was a mistake + +Author: evomarc +Date: Mon Apr 9 08:52:41 2001 +0000 + + Commented some ====== that resulted in error when running autogen.sh + +Author: evomarc +Date: Thu Apr 5 16:47:54 2001 +0000 + + Added the continue.tmpl template - and modified the html pages accordingly + (though eoCheckPoint.html is still a long way to complete). + Added some comments in all template files - and replaced + the protected by private (don't remember why these were protected!!!). + +Author: evomarc +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 +Date: Tue Apr 3 17:14:53 2001 +0000 + + eoOperators now is in sync with the last modif of eoPopulator by Maarten! + +Author: evomarc +Date: Tue Apr 3 17:14:08 2001 +0000 + + Modified the tempaltes to take into account + - the last modifications of the eopopulator class + - the include files (were totally missing in the old templates) + - JJ's demand for one class - one file :-) + +Author: jmerelo +Date: Tue Apr 3 10:08:08 2001 +0000 + + In eoVector, changed printOn and readFrom to virtual + +Author: maartenkeijzer +Date: Wed Mar 28 09:00:54 2001 +0000 + + eoParam, added specialization for eoValueParam::getValue + 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 +Date: Tue Mar 27 16:27:15 2001 +0000 + + Modified the names in eoPopStat! + Hoever, the way it's done now, the string gets TRUNCATED - and I dont' know why + +Author: evomarc +Date: Tue Mar 27 16:02:00 2001 +0000 + + Adding Maarten's "snippet" to dump the whole pop to the screen: eoPopStat.h + Modified utils/checkpointing accordingly. + Tested in tutorial/Lesson3/exercise3.1 + BTW, the eoFileSnapShot does not work any more - I've commented it out + and will look at that later... + +Author: maartenkeijzer +Date: Mon Mar 26 10:09:40 2001 +0000 + + NDSorting: changed exact ranking values to make check for front easier + eoRNG: changed nothing (did some debugging) + +Author: maartenkeijzer +Date: Fri Mar 23 12:24:39 2001 +0000 + + added test for printing population + +Author: maartenkeijzer +Date: Fri Mar 23 08:54:31 2001 +0000 + + let doxygen look into this dir + +Author: maartenkeijzer +Date: Fri Mar 23 08:53:48 2001 +0000 + + added + +Author: maartenkeijzer +Date: Thu Mar 22 16:23:56 2001 +0000 + + updated project number + +Author: maartenkeijzer +Date: Thu Mar 22 11:22:31 2001 +0000 + + oops + +Author: maartenkeijzer +Date: Thu Mar 22 10:51:16 2001 +0000 + + Changed the single objective shortcut calculation + +Author: maartenkeijzer +Date: Thu Mar 22 09:00:30 2001 +0000 + + temporarily added fitness_traits to keep people up to date with this proposal + +Author: jmerelo +Date: Wed Mar 21 13:35:10 2001 +0000 + + Added a new xover to varlenxover + +Author: jmerelo +Date: Wed Mar 21 13:09:47 2001 +0000 + + Added a new atommutator to Variable Length, and corrected some headers which had problems + +Author: jmerelo +Date: Wed Mar 21 12:10:13 2001 +0000 + + Moved epAtom* out of the obsolete dir; added some CVS headers to some files, and made everything work with my elipse classes + +Author: maartenkeijzer +Date: Wed Mar 21 11:09:29 2001 +0000 + + test paretofitness class + +Author: maartenkeijzer +Date: Wed Mar 21 11:08:27 2001 +0000 + + Few changes in setting up the algorithms. It now gives an example of how to + write factory functions + +Author: maartenkeijzer +Date: Wed Mar 21 10:55:22 2001 +0000 + + Changed a few things in the eoPerf2Worth classes, EO.h and eoSelectOne.h are functionally unchanged + +Author: maartenkeijzer +Date: Tue Mar 20 14:34:07 2001 +0000 + + Updated eoStat.h to also "do the right thing" when confronted with pareto style fitness + +Author: maartenkeijzer +Date: Fri Mar 16 14:19:11 2001 +0000 + + added help + +Author: maartenkeijzer +Date: Fri Mar 16 14:09:55 2001 +0000 + + Now look how perty t-eoPareto has become (though it doesn't do a proper mo modelling yet) + +Author: maartenkeijzer +Date: Fri Mar 16 13:11:32 2001 +0000 + + Some bugfixing in MO optimization and added empty check: target in tutorial + +Author: maartenkeijzer +Date: Fri Mar 16 12:09:36 2001 +0000 + + oops, ngens is now the nice 10 + +Author: maartenkeijzer +Date: Fri Mar 16 12:08:26 2001 +0000 + + Ok, made an eoParetoFitness class, which meant that I could roll back a few changes in EO.h (phew). + Also changed eoSelectFromWorth etc. + +Author: maartenkeijzer +Date: Fri Mar 16 11:48:32 2001 +0000 + + added + +Author: maartenkeijzer +Date: Thu Mar 15 14:11:24 2001 +0000 + + added dist and distdir targets + +Author: maartenkeijzer +Date: Wed Mar 14 12:47:14 2001 +0000 + + Using nd-sorting now + +Author: maartenkeijzer +Date: Wed Mar 14 12:46:37 2001 +0000 + + First go, does not do niching yet + +Author: maartenkeijzer +Date: Wed Mar 14 11:58:47 2001 +0000 + + OOPS, that was a major bug, letting non-dominating individuals dominate one another. + +Author: maartenkeijzer +Date: Wed Mar 14 10:14:27 2001 +0000 + + t-eoPareto now plots the evolving population and t-eoRandom check is slightly more strict + +Author: maartenkeijzer +Date: Wed Mar 14 10:13:27 2001 +0000 + + Added support for printing vector as a fitness + +Author: maartenkeijzer +Date: Wed Mar 14 10:12:37 2001 +0000 + + Added Multi-objective fitness monitoring added support for vector > in eoParam + and made eoFileSnapshot type-safe + +Author: maartenkeijzer +Date: Tue Mar 13 08:25:05 2001 +0000 + + Swapped linking order of utility libs + +Author: evomarc +Date: Tue Mar 13 05:25:51 2001 +0000 + + Just modified an wrong comment (after a too quick cut-and-paste) + +Author: maartenkeijzer +Date: Mon Mar 12 16:07:55 2001 +0000 + + Production of binop back to 1 + +Author: maartenkeijzer +Date: Mon Mar 12 16:04:18 2001 +0000 + + Added first batch of pareto based stuff + +Author: maartenkeijzer +Date: Mon Mar 12 16:03:08 2001 +0000 + + Added pareto based stuff + +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 +Date: Mon Mar 12 14:27:31 2001 +0000 + + invalidating supported now + +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() + +Author: maartenkeijzer +Date: Fri Mar 9 14:14:53 2001 +0000 + + Test for a ssga added. + +Author: maartenkeijzer +Date: Fri Mar 9 14:13:28 2001 +0000 + + Various bugs found and resolved. + +Author: maartenkeijzer +Date: Thu Mar 8 13:38:41 2001 +0000 + + radically simplified the Makefile.am, but this only works for headers (no idea what the problem is with sources) + +Author: maartenkeijzer +Date: Tue Feb 27 11:45:31 2001 +0000 + + put using eo::rng in top of file to help out gcc 2.91 + +Author: maartenkeijzer +Date: Tue Feb 27 11:44:28 2001 +0000 + + swapped order of libeo and libeoutils, gcc 2.91 did not like it + +Author: maartenkeijzer +Date: Tue Feb 27 11:43:06 2001 +0000 + + Made dtor virtual + +Author: evomarc +Date: Tue Feb 27 05:24:24 2001 +0000 + + Still modifying eoInit ... + +Author: evomarc +Date: Tue Feb 27 05:09:10 2001 +0000 + + Modified all init sequences in Lesson2 and Lesson3 - and all corresponding + files in html dir - after the return of eoRndGenerators and subsequent + modifications of eoInit + +Author: maartenkeijzer +Date: Mon Feb 19 12:23:13 2001 +0000 + + Modified eoInit so that it would use the eoRndGenerator base class. + 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 +Date: Sun Feb 18 06:41:30 2001 +0000 + + Date and version number + +Author: evomarc +Date: Sun Feb 18 04:34:57 2001 +0000 + + Added the eo::rng (instead of rng) as default parameter to all calls. + Also t-eoRandom was abruptly aborting-> a min was greater than a max, and + exceptions were not being caught. + +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 +Date: Sat Feb 17 08:22:53 2001 +0000 + + Now takes into account the last (and last!) modification of the operator interace: + no more invalidate, but a bool returned for simple operators, and a better description + of the eoPopulator/eoOpContainer links. + +Author: evomarc +Date: Sat Feb 17 06:47:31 2001 +0000 + + Forgot the selector in the ctor + +Author: evomarc +Date: Sat Feb 17 06:42:20 2001 +0000 + + Modified crossover and mutation to account for the new interface (bool ...) + Added the genop.tmpl, template for general op, 3 cases, growing pop, + shrinking pop through erase, thrinking pop through extra selector + +Author: evomarc +Date: Fri Feb 16 18:00:18 2001 +0000 + + Added oine star at start of comment to have Doxygen process it !!! + +Author: maartenkeijzer +Date: Fri Feb 16 09:39:06 2001 +0000 + + works for me + +Author: evomarc +Date: Fri Feb 16 08:21:25 2001 +0000 + + The perf2worth major check in + 2 new important classes: eoPerf2Worth and eoSelectFromWorth + Instances of eoPerf2Worth are eoRanking and eoLinearFitScaling. + Coming soon (piece of cake now) are the niching strategies (sharing, clearing) + +Author: evomarc +Date: Fri Feb 16 05:06:17 2001 +0000 + + Only names modifications, to comply to EO strict rules :-) + +Author: maartenkeijzer +Date: Thu Feb 15 08:31:38 2001 +0000 + + reverted the max-to-produce initializer + +Author: evomarc +Date: Thu Feb 15 05:36:28 2001 +0000 + + Changed the default values for popsize, vecsize and maxgen so + the user has a chance to see something even on Pentium 10GHz :-) + +Author: evomarc +Date: Thu Feb 15 05:35:31 2001 +0000 + + Modified the comments so that all callses are documented by Doxygen + (a comment starting with // before the class definition is not taken into account) + Also updated the initial overall comment - + and waouw, doxygen generates links there, too! Cool. + +Author: evomarc +Date: Thu Feb 15 04:47:18 2001 +0000 + + +Author: maartenkeijzer +Date: Wed Feb 14 18:05:36 2001 +0000 + + updated the dsp, dsw files for the library + +Author: maartenkeijzer +Date: Wed Feb 14 18:01:30 2001 +0000 + + no need to keep these test functions here, will start new project in /test + +Author: maartenkeijzer +Date: Wed Feb 14 14:09:16 2001 +0000 + + Changed the return value to return what it got in + +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 + invalidate the fitness, thus really pointing out the advantage of the current approach) + +Author: jmerelo +Date: Tue Feb 13 22:39:56 2001 +0000 + + Just playing with the CVS variables + +Author: jmerelo +Date: Tue Feb 13 22:38:23 2001 +0000 + + Just playing with the CVS variables + +Author: jmerelo +Date: Tue Feb 13 22:35:07 2001 +0000 + + Moved out of the 'obsolete' directory a couple of honest classes, which didn't harm anybody; activated also in Makefile.am the program that tested them + +Author: maartenkeijzer +Date: Tue Feb 13 14:43:54 2001 +0000 + + Added a bit more documentation, more to follow (I hope) + +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 +Date: Tue Feb 13 10:35:47 2001 +0000 + + Just an update + +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 + a GA-componenent that can be used in other applications without having to rebuild + the entire thing. test/t-eoGA.cpp tests this library + +Author: maartenkeijzer +Date: Sun Feb 11 16:35:21 2001 +0000 + + run_tests is expanded to run everything (but only once yet, will have + to address this later). + t-eoSymreg is build to run for just a few generations, otherwise testing + it would be an excercise in patience. + +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. + +Author: maartenkeijzer +Date: Sun Feb 11 16:01:47 2001 +0000 + + run_tests, add your own tests here + +Author: maartenkeijzer +Date: Sun Feb 11 15:58:55 2001 +0000 + + Test now is not build automatically, make test should be given explicitely, then a new script run_tests will be used to check if everything still works + +Author: maartenkeijzer +Date: Sun Feb 11 15:57:01 2001 +0000 + + Commented out the check for libtool, as we don't use it currently + +Author: evomarc +Date: Sat Feb 10 05:36:50 2001 +0000 + + Added matermind in SUBDIRS + +Author: jmerelo +Date: Fri Feb 9 16:52:06 2001 +0000 + + Minor bugs for Win quashed; fixed Win project files + +Author: maartenkeijzer +Date: Fri Feb 9 11:52:55 2001 +0000 + + Removed the -O2 flag from the makefile in the test directory. + Builds should go faster now. + +Author: evomarc +Date: Fri Feb 9 08:32:47 2001 +0000 + + Added a comment before eoPopulator class so it is documented! + +Author: evomarc +Date: Fri Feb 9 08:21:35 2001 +0000 + + Changed the first paragraph, added warning that it should be used on-line only + +Author: evomarc +Date: Fri Feb 9 05:52:44 2001 +0000 + + Big change in eoGeneralOp interface: left out! + +Author: evomarc +Date: Fri Feb 9 05:46:12 2001 +0000 + + Change in Makefile - but again it should be replaced with clean Makefile.am + +Author: evomarc +Date: Fri Feb 9 05:43:06 2001 +0000 + + The big GeneraoOp interface change - in test dir + +Author: evomarc +Date: Fri Feb 9 05:34:04 2001 +0000 + + Modified the Makefile of Lesson? to allow make all to also make the exercises + It need to be modified anyway into Makefile.am stuff + +Author: evomarc +Date: Fri Feb 9 05:28:33 2001 +0000 + + Removed eoEvolutionStrategy because it was based on eoGeneralOp old interface + +Author: evomarc +Date: Fri Feb 9 05:25:25 2001 +0000 + + Because it has not extension, I had forgotten to update the eo file itself! + Now reflects the change of eoGenOp interface and the changes of names in ga + +Author: evomarc +Date: Fri Feb 9 05:21:04 2001 +0000 + + Added the GnuPlotSnapshotMonitor, the eoScalarFitnessStat and eoFDCStat in checkpointing + +Author: evomarc +Date: Fri Feb 9 05:10:25 2001 +0000 + + Left-out from the big change of general op interface! + +Author: evomarc +Date: Fri Feb 9 05:09:26 2001 +0000 + + The BIG change of general operator interface + 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 + +Author: evomarc +Date: Wed Feb 7 05:15:18 2001 +0000 + + Added the missing include of eoScalarFitness - mandatory due to + explicit specialization for eoParamValue > + +Author: evomarc +Date: Wed Feb 7 05:13:33 2001 +0000 + + Added the handling of generic operators in Combined Ops + +Author: evomarc +Date: Wed Feb 7 05:11:37 2001 +0000 + + Added the shuffle(vector) method + +Author: evomarc +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) + +Author: evomarc +Date: Thu Feb 1 05:27:36 2001 +0000 + + Forgotten a debug print + +Author: evomarc +Date: Thu Feb 1 05:17:16 2001 +0000 + + I had forgotten to add pipecom.h + Moreover, I got fed up with error due to const/non const, so I modified + PipeComSend to take a const argument. THe consequence is that it will not run + under plain C any more. + +Author: evomarc +Date: Wed Jan 31 18:38:39 2001 +0000 + + Added the monitoring facilities for snapshots (i.e. generating and plotting a new file + 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 + - multi-objective Pareto fronts (though the multi-objective sruff isn't there yet!) + +Author: evomarc +Date: Tue Jan 30 04:53:05 2001 +0000 + + Comments added to remove undocumented classes from Doxygen documentation + +Author: evomarc +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 + +Author: evomarc +Date: Sun Jan 28 07:31:34 2001 +0000 + + Modified to use eoRealBounds rather than eoEsObjectiveBounds + +Author: evomarc +Date: Sun Jan 28 07:27:12 2001 +0000 + + Error in src/Makefile.am + +Author: evomarc +Date: Sun Jan 28 07:02:27 2001 +0000 + + Actually removed eoEsObjectiveBounds.h and evolution_strategies + +Author: evomarc +Date: Sun Jan 28 07:00:41 2001 +0000 + + Added the includes ga.h and es.h + Removed the old eoEsObjectiveBounds and evolutionar_strategies from es dir + +Author: evomarc +Date: Sat Jan 27 08:38:31 2001 +0000 + + Added some comments so eoRealVectorBounds is documented + +Author: evomarc +Date: Sat Jan 27 08:20:39 2001 +0000 + + Following the change in includes (added ga.h and es.h everywhere pfuhh) + +Author: evomarc +Date: Sat Jan 27 07:46:07 2001 +0000 + + Added eoGenericRealOp.h that are the exact copy of the operators of eoReaOp.h, + but in generic format. + They are used at the omoment only in eoEsStdevXOver.h that calls a crossover + on the object variables, then a crossover on teh stdev vectors! + A piece of cake :-) + +Author: evomarc +Date: Sat Jan 27 07:43:58 2001 +0000 + + I have separated the include files into + 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 + +Author: evomarc +Date: Sat Jan 27 07:41:46 2001 +0000 + + I have separated the include files into + 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... + +Author: evomarc +Date: Sat Jan 27 07:33:55 2001 +0000 + + A few mistakes corrected - and some comments on the setup method + +Author: evomarc +Date: Fri Jan 26 18:26:30 2001 +0000 + + Added the bounds to all eoRealOp operators (and to the eoNormalMutation). + The eoESObjectiveBounds should soon dissapear!! + +Author: evomarc +Date: Fri Jan 26 17:12:13 2001 +0000 + + Typos in comments + +Author: evomarc +Date: Fri Jan 26 17:09:33 2001 +0000 + + Some includes were missing in eoPop and eoOp that I had not noticed before + trying to compile test/t-eoSymreg.cpp + +Author: evomarc +Date: Fri Jan 26 04:06:09 2001 +0000 + + Added eoRandomReduce + +Author: evomarc +Date: Thu Jan 25 16:14:25 2001 +0000 + + Full t-eoSelect file, that allows to test all selectors + feature: generation of files suitable for gnuplot to see how individual spread out + +Author: evomarc +Date: Thu Jan 25 16:13:15 2001 +0000 + + Added ranking selection (eoRankingSelect) and (linear) fitness scaling in + proportional selection (a completely different file, eoFitnessScalingSelect.h) + +Author: evomarc +Date: Wed Jan 17 05:29:54 2001 +0000 + + Modified the link to EO pages so that users can download the development + version - as no example works with the current snapshot + +Author: evomarc +Date: Tue Jan 16 09:49:46 2001 +0000 + + Added the shuffle method + +Author: evomarc +Date: Tue Jan 16 07:20:48 2001 +0000 + + Added the normal mutation - and the 1/5 mutation in FirstRealEA in Lesson2 + +Author: evomarc +Date: Tue Jan 16 07:20:02 2001 +0000 + + Added the normal and 1/5 mutations (file es/eoNormalMutation.h) + +Author: evomarc +Date: Tue Jan 16 07:18:45 2001 +0000 + + Added the normal mutation - and the 1/5 mutation + +Author: evomarc +Date: Tue Jan 16 05:52:01 2001 +0000 + + Added the eoRandomReduce class - hence I also added the shuffle method + in eoPop (I had been postponing that for a long time!) which in turn required + another class of random generator (whose operator() takes an unsigned as argument) + +Author: evomarc +Date: Fri Jan 12 21:31:42 2001 +0000 + + Corrected some error in variable name after last changes in method append + +Author: evomarc +Date: Thu Jan 11 11:02:37 2001 +0000 + + New versions of bounds for real variables. + Should supersede eoEsObjectiveBounds, whose name was misleading anyway + as this can be used in any REal-ceded GA for isntance + +Author: evomarc +Date: Thu Jan 11 10:48:31 2001 +0000 + + GOing to the generic operators: some additions (eoGeneric*) + and some modifications in eoFixedLength and eoVariableLength. + +Author: evomarc +Date: Tue Jan 9 03:33:16 2001 +0000 + + Added the eoSurviveAndDie comments. + Should be complete!!! + +Author: evomarc +Date: Tue Jan 9 02:17:28 2001 +0000 + + Added the namespace in description of RNGs (and corrected a few broken links) + +Author: evomarc +Date: Mon Jan 8 10:07:27 2001 +0000 + + Added the namespace eo for the global variable rng in eoRNG.cpp + Also added "using eo::rng" in eoRNG.h so nothing has to be modified. + We should gradually move to write eo::rng everywhere, and remove that using + directive to be almost full-proofed against possible name collision. + +Author: evomarc +Date: Mon Jan 8 09:52:15 2001 +0000 + + Added the descrition of evolution engines in eoEngine + and links to SGAI STL Web site in eoTutorial and eoProgramming + +Author: evomarc +Date: Fri Jan 5 14:42:48 2001 +0000 + + Removed a forgotten comment :-) + +Author: evomarc +Date: Fri Jan 5 08:50:01 2001 +0000 + + I'm not sure about whether the sourceforge list is equivalent to the onelist list, + so I finally ut both in README! + +Author: evomarc +Date: Fri Jan 5 08:17:11 2001 +0000 + + Put the sourceforge name for the mailing list + +Author: evomarc +Date: Fri Jan 5 07:30:34 2001 +0000 + + Updating installation ... + +Author: evomarc +Date: Fri Jan 5 07:20:45 2001 +0000 + + Correcting my previous errors ... + +Author: evomarc +Date: Fri Jan 5 07:10:25 2001 +0000 + + Trying to make the installation lighter, but the doc and the src + would not compile, with make doc or make src ... + +Author: evomarc +Date: Fri Jan 5 06:55:16 2001 +0000 + + Removed Lesson4 from Makefile - it is not there yet, and generates an error + +Author: evomarc +Date: Fri Jan 5 06:25:26 2001 +0000 + + Added a message about generating the documentation if you have doxygen + +Author: evomarc +Date: Fri Jan 5 06:24:53 2001 +0000 + + Removed doc from the SUBDIRS as most people don't have doxygen installed. + Now you need to type in "make doc" to generate the doc + +Author: evomarc +Date: Fri Jan 5 06:23:54 2001 +0000 + + Updated Makefile.am to account for the change of names in selectors + +Author: evomarc +Date: Fri Jan 5 05:48:16 2001 +0000 + + Changed the names of the exercise files to exerciseN.p - N lesson nb, p exercise nb + +Author: evomarc +Date: Fri Jan 5 05:44:35 2001 +0000 + + eoHowMany is now included in utils dir + +Author: evomarc +Date: Fri Jan 5 05:42:08 2001 +0000 + + Checking in the name changes in selection procedures. + This impacts on many files, creating new entries in src (the old ones are moved + to obsolete dir), modifying t-eoSymreg.cpp and t-eobin.cpp in test, + as well as gprop.cc and mastermind.cc in app dir (not to mention almost all + files in tutorial:-( + +Author: evomarc +Date: Fri Jan 5 05:41:26 2001 +0000 + + Trying to ci eoTutorial.html (there is a sticky tag that keeps bothering me ...) + +Author: evomarc +Date: Thu Jan 4 15:23:14 2001 +0000 + + I had removed the wrong file!!! + +Author: evomarc +Date: Thu Jan 4 15:21:18 2001 +0000 + + removed redundant index.html in html dir + +Author: evomarc +Date: Thu Jan 4 05:06:09 2001 +0000 + + Sorry: removed eoSGATransform, that is in eoSGA.h ... + +Author: evomarc +Date: Thu Jan 4 05:00:40 2001 +0000 + + Adding the selectin and replacement procedures + +Author: evomarc +Date: Tue Jan 2 13:31:40 2001 +0000 + + Adding t-eoSelect.cpp to test selection procedures. Modified Makefile.am accordingly + +Author: evomarc +Date: Tue Jan 2 13:27:11 2001 +0000 + + Adding eoDetSelect, deterministic batch selection, that copies the individuals + one after the other. Should shuffle them in between (TODO). + +Author: evomarc +Date: Tue Jan 2 07:54:12 2001 +0000 + + A few deatils + +Author: evomarc +Date: Tue Jan 2 07:35:56 2001 +0000 + + Still the same !@#$$%% modif due to egcs problems ... + +Author: evomarc +Date: Tue Jan 2 07:23:35 2001 +0000 + + Follow-up to the modif of SecondBitEA.cpp due to egcs... + +Author: evomarc +Date: Tue Jan 2 07:19:55 2001 +0000 + + A few details in the comments + +Author: evomarc +Date: Tue Jan 2 07:03:57 2001 +0000 + + I had to change the whole way the parameters are read, because EGCS did not + allow the nice constructs I had imagined (and compiled with g++) + - I removed the createParam method in Parser class - that was creating the parameters + on the heap. Not allowed to have a templatized method ??? + - I removed the subroutine read_param in SecondBitEA, as you need to create + 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 ...) + +Author: evomarc +Date: Wed Dec 27 11:37:05 2000 +0000 + + A few additions and corrections ... + +Author: evomarc +Date: Tue Dec 26 10:28:27 2000 +0000 + + Modified the help message for the short name (added the missing =) + +Author: evomarc +Date: Tue Dec 26 08:33:48 2000 +0000 + + Moved eoSGATransform into a separate file and added the dynamic version + (where arguments can be passed by value or by reference). + Modified eo accordingly + +Author: evomarc +Date: Tue Dec 26 07:42:09 2000 +0000 + + Modified the include list after the big eoReplacement changes + +Author: evomarc +Date: Fri Dec 22 15:13:54 2000 +0000 + + Had forgotten the section name of the parser.processParam call in the + definition fo the parameter. + +Author: evomarc +Date: Fri Dec 22 14:59:10 2000 +0000 + + Back to the 3 lines to declare a parameter and read it within the parser: + some compiler (egcs) don't like the createParam method in eoParser.h + +Author: evomarc +Date: Fri Dec 22 14:56:12 2000 +0000 + + Back to the 3 lines to declare a parameter and read it within the parser: + some compiler (egcs) don't like the createParam method in eoParser.h + Also removed the reference in parameters declarations (a cut-and-paste error). + +Author: evomarc +Date: Thu Dec 21 06:49:41 2000 +0000 + + Augmented the functors and STL parts - but I still would appreciate + help on the STL part! + +Author: evomarc +Date: Thu Dec 21 05:35:01 2000 +0000 + + Removed the silly reference for all parameters (cut-and-paste error!). + But the funny thing is that my compiler did not complain ... + +Author: evomarc +Date: Tue Dec 19 22:14:29 2000 +0000 + + Updated INSTALL and README to EO-specific instructions! + +Author: evomarc +Date: Tue Dec 19 18:43:25 2000 +0000 + + Update after the change in replacements + +Author: evomarc +Date: Tue Dec 19 18:42:41 2000 +0000 + + Added t-eoRepalcement.cpp, that tests all new replacement procedures + +Author: evomarc +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 +Date: Tue Dec 19 18:32:09 2000 +0000 + + A few errors + local TOC at top of eoEngine + +Author: evomarc +Date: Tue Dec 19 18:18:08 2000 +0000 + + Bottom-Up/Top-Down modifs + +Author: evomarc +Date: Tue Dec 19 18:09:10 2000 +0000 + + A new util class to handle the rate/integer argument to selectors/replacement + +Author: evomarc +Date: Tue Dec 19 18:02:19 2000 +0000 + + Changed NoReplacement to GenerationalReplacement + +Author: evomarc +Date: Tue Dec 19 10:17:39 2000 +0000 + + Changed the "to-down / bottom-up" to "algorithm-based / component-based" + Also added all replacement procedures in eoEngine.html + and the general operator interface in eoOperators.html + +Author: evomarc +Date: Tue Dec 19 05:31:54 2000 +0000 + + A small detail ... + +Author: evomarc +Date: Sun Dec 17 07:49:55 2000 +0000 + + Updated teh INSTALL and README files that were really minimal!!! + +Author: evomarc +Date: Fri Dec 15 18:09:08 2000 +0000 + + Corrected a bad link + +Author: evomarc +Date: Fri Dec 15 17:01:11 2000 +0000 + + deleted trash file lesson1.ps + CVS ---------------------------------------------------------------------- + +Author: evomarc +Date: Fri Dec 15 16:57:37 2000 +0000 + + Added utils/eoGnuplot1DMonitor.h ni the list of includes + +Author: gustavoromero +Date: Mon Dec 11 09:28:40 2000 +0000 + + adding .deps + +Author: evomarc +Date: Fri Dec 8 15:10:13 2000 +0000 + + Adding Templates in dir tutorial, to hold some simple files that + only need to be filled by the user to code new items. + At the moment, only eoMonOp (in mutation.tmpl), and + eoBinOp and eoQuadOp (in crossover.tmpl) + +Author: evomarc +Date: Fri Dec 8 14:16:13 2000 +0000 + + Corrected a few bugs after the first "public" presentation + +Author: evomarc +Date: Thu Dec 7 09:56:00 2000 +0000 + + New base class eoUpdatable.h - for objects that need upates in eoCheckPoints + Also contains the class eoDynUpdater. They are eoUpdater, they receive an eoUpdatable + at construct time, and call their upate() method in their operator() method + +Author: gustavoromero +Date: Tue Dec 5 13:46:21 2000 +0000 + + small change + +Author: evomarc +Date: Tue Dec 5 05:27:12 2000 +0000 + + Removed trash file + +Author: evomarc +Date: Tue Dec 5 05:22:55 2000 +0000 + + Added virtual and const keywords all around - as I tried to use a derived + class for adaptive rates (see eoDynProportionalCombinedOp.h, at the moment + in the tutorial) + +Author: gustavoromero +Date: Mon Dec 4 19:26:19 2000 +0000 + + erasing comments + +Author: gustavoromero +Date: Mon Dec 4 19:10:20 2000 +0000 + + small improvements + +Author: evomarc +Date: Mon Dec 4 16:49:42 2000 +0000 + + Added normal mutation for reals, and corrected error of segment-> arithmetic + for the crossover operators + +Author: evomarc +Date: Mon Dec 4 15:01:31 2000 +0000 + + omment of line apply(pop, eval) was found misleading ... + +Author: evomarc +Date: Mon Dec 4 14:55:18 2000 +0000 + + - added the #define for eo_verbose (true) and eo_no_verbose (false) + - added the eoNormMutation, simple normal mutation for simple real variables + +Author: evomarc +Date: Mon Dec 4 14:53:59 2000 +0000 + + - added the #define for eo_verbose (true) and eo_no_verbose (false) + - added the eoNormMutation, simple normal mutation for simple real variables + Modified Files: + src/eo src/es/eoRealOp.h tutorial/Lesson2/FirstRealEA.cpp + tutorial/Lesson3/SecondBitEA.cpp + +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. + Added of course a virtual method lastCall that does nothing by default in classes + 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. + +Author: evomarc +Date: Mon Dec 4 05:55:59 2000 +0000 + + Added a comment so Doxygen documents it + +Author: evomarc +Date: Sat Dec 2 08:35:42 2000 +0000 + + eoStdoutMonitor -> eoFileMonitor to correct an abusive cut-and-paste! + +Author: evomarc +Date: Sat Dec 2 08:29:45 2000 +0000 + + Suppressed the warning for the need to create a link - see html files log. + +Author: evomarc +Date: Sat Dec 2 08:27:30 2000 +0000 + + Changed the links to the EO doc - removed the need for a (Unix) link from + tutorial/html dir to doc/ dir: it's simpler, and I was not able to do + the same thing in Windows anyway! + +Author: evomarc +Date: Sat Dec 2 08:21:18 2000 +0000 + + Changed the (abstract) name for fitness from F to FitT so it matches + that of file eoFixedLength.h - it is far clearer in the documentation + diagrams this way. + +Author: gustavoromero +Date: Fri Dec 1 19:13:12 2000 +0000 + + initial version of mastermind + +Author: gustavoromero +Date: Fri Dec 1 19:09:34 2000 +0000 + + adding a new terminator and a monitor + +Author: evomarc +Date: Fri Dec 1 18:26:16 2000 +0000 + + Corrected the outState.regiserObject(parser) ommission (see SecondBitEA.html) + +Author: evomarc +Date: Fri Dec 1 18:03:17 2000 +0000 + + I had dropped the parser from the outState - so I had to modify also + read_param to get it back! + +Author: evomarc +Date: Fri Dec 1 17:56:52 2000 +0000 + + Used spell-checker!!! + +Author: gustavoromero +Date: Fri Dec 1 15:46:07 2000 +0000 + + adding a lot of includes + +Author: gustavoromero +Date: Thu Nov 30 17:11:53 2000 +0000 + + small fix for uniform + +Author: evomarc +Date: Thu Nov 30 06:38:15 2000 +0000 + + Corrected a small bug (!): the -C=value was not processed correctly + as somebody forgot one character when counting up to ... 3 :-))) + +Author: evomarc +Date: Thu Nov 30 06:20:20 2000 +0000 + + Reversed the priority between command-line and parameter file + +Author: evomarc +Date: Thu Nov 30 06:11:49 2000 +0000 + + Moved eoCopyElite.h to obsolete dir - was redundant with eoMerge.h + +Author: evomarc +Date: Thu Nov 30 06:04:09 2000 +0000 + + Removed eoCopyElite.h, redundant with eoMerge.h + +Author: evomarc +Date: Thu Nov 30 04:44:32 2000 +0000 + + Added the tutorial SUBDIR + It works fine ... for make clean + But of course it would require some Makefile.am in each subdir of tutorial + and I am not sure I know what to put there... + +Author: gustavoromero +Date: Wed Nov 29 18:36:13 2000 +0000 + + sorry, old version was right + +Author: evomarc +Date: Wed Nov 29 18:19:57 2000 +0000 + + Initial version of the tutorial. + Warning: all Makefile's are hand-made, and will only work in Linux + +Author: evomarc +Date: Wed Nov 29 18:19:18 2000 +0000 + + dded teh comment about the link to be made from html to ../../doc + +Author: evomarc +Date: Wed Nov 29 18:06:09 2000 +0000 + + Initial version of the tutorial. + Warning: the Makefil is hand-made, and only works in Linux + +Author: evomarc +Date: Wed Nov 29 17:20:16 2000 +0000 + + An include file was missing!!! + I've inserted it in teh file actually - but if we go on with gnuplot, + it will need to be taken out again, and used in all other monitors + we will write using gnuplot (e.g. eoGnuplotWithErrorbarsMonitor, + eoGnuplotHistogramMonitor, ...). + +Author: evomarc +Date: Tue Nov 28 17:42:53 2000 +0000 + + Added eoProportionalCombinedOp.h + +Author: evomarc +Date: Tue Nov 28 17:41:41 2000 +0000 + + I added this very simple instance of operator proportional selector + for the tutorial - it is consistent with all other xxxCombined constructs. + However, I am not sure that Occam's razor will not make it widely used... + +Author: evomarc +Date: Tue Nov 28 17:17:19 2000 +0000 + + Added the class eoSGATransform: I break the one file / one class rule + a lot, but both are supposed to be used mainly in the tutorial, not + in real life :-) + +Author: evomarc +Date: Tue Nov 28 15:40:39 2000 +0000 + + Added fstream in the include files - I had an error message at some point! + +Author: evomarc +Date: Tue Nov 28 15:35:09 2000 +0000 + + Added a comment to stdout upon termination - so we know why we stop in case + of multiple criteria + +Author: evomarc +Date: Tue Nov 28 15:31:38 2000 +0000 + + Minor change of the default label + +Author: gustavoromero +Date: Tue Nov 28 13:36:29 2000 +0000 + + now works + +Author: evomarc +Date: Tue Nov 28 08:20:01 2000 +0000 + + Added a few comments so Doxygen documents all classes + +Author: evomarc +Date: Tue Nov 28 06:58:06 2000 +0000 + + This is the first attempt to use gnuplot through a fork to plot statistics. + At the moment it is only tested for Linux! + Use with care + +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). + Added the getFileName accessor. + +Author: evomarc +Date: Fri Nov 24 17:45:07 2000 +0000 + + Added eoSteadyGenContinue.h, es/eoReal.h and es/eoRealOp.h + +Author: evomarc +Date: Fri Nov 24 17:44:21 2000 +0000 + + Very simple classes for vectors of (unbounded) real numbers. + A few straightforward operators only (BLX-0, uniform mutation). + Mostly for tutorial reasons - though it might improve in usefull classes later + +Author: gustavoromero +Date: Fri Nov 24 17:43:02 2000 +0000 + + bug fix + +Author: evomarc +Date: Fri Nov 24 17:41:39 2000 +0000 + + An eoContinue class that allows a minimum number of generations, + then stops whenever a number of generations happens without fitness + improvement. + +Author: evomarc +Date: Fri Nov 24 17:36:03 2000 +0000 + + Added a verbose mode (the default behavior) which is as before. + But when in non-verbose mode, prints only one line per generation. + +Author: evomarc +Date: Fri Nov 24 17:30:37 2000 +0000 + + Turned the eoBestFitness into an eoStat (it was an eoSortedStat). + Alos added a few comments so that Doxygen documents all classes there. + +Author: evomarc +Date: Fri Nov 24 17:26:22 2000 +0000 + + Changed Maarten's 2-continuator construct into a vector of pointer, + as in all other Combined constructs in EO. + Kept the construtor with 2 eoCOntinue for backward compatibility. + Added of course the add method! + +Author: gustavoromero +Date: Fri Nov 24 12:33:44 2000 +0000 + + changing genetic operators + +Author: gustavoromero +Date: Fri Nov 24 11:52:49 2000 +0000 + + fix Fitness default construction value + +Author: gustavoromero +Date: Fri Nov 24 09:51:31 2000 +0000 + + adding new parameters + +Author: gustavoromero +Date: Thu Nov 23 19:45:49 2000 +0000 + + reordering Makefile creation + +Author: gustavoromero +Date: Thu Nov 23 19:45:13 2000 +0000 + + adding some files + +Author: gustavoromero +Date: Thu Nov 23 19:44:47 2000 +0000 + + initial release + +Author: gustavoromero +Date: Thu Nov 23 19:17:24 2000 +0000 + + initial version + +Author: gustavoromero +Date: Thu Nov 23 19:15:31 2000 +0000 + + adding Makefile.in + +Author: gustavoromero +Date: Thu Nov 23 19:14:09 2000 +0000 + + new application gprop + +Author: evomarc +Date: Fri Nov 17 17:50:08 2000 +0000 + + Made eoBestFitnessStat an eoStat, NOT an eoSortedStat + Cde VS: Committing in . + +Author: evomarc +Date: Fri Nov 17 17:06:53 2000 +0000 + + dded the className method for eoMon, eoBin and eoQuad classes + +Author: gustavoromero +Date: Mon Nov 13 12:12:14 2000 +0000 + + fixing template type + +Author: gustavoromero +Date: Mon Nov 13 12:09:53 2000 +0000 + + adding evaluation in some places + +Author: gustavoromero +Date: Fri Nov 10 09:55:10 2000 +0000 + + fix warning: no newline at end of file + +Author: gustavoromero +Date: Wed Nov 8 15:15:26 2000 +0000 + + fix no newline at end of file warning + +Author: gustavoromero +Date: Wed Nov 8 13:37:41 2000 +0000 + + choose a constructor + +Author: gustavoromero +Date: Wed Nov 8 13:26:03 2000 +0000 + + fix no newline at end of file warning + +Author: gustavoromero +Date: Wed Nov 8 12:56:14 2000 +0000 + + adding a include for apply.h + +Author: gustavoromero +Date: Wed Nov 8 12:55:26 2000 +0000 + + fix no newline at end of file warning + +Author: gustavoromero +Date: Wed Nov 8 12:38:13 2000 +0000 + + bug fix + +Author: gustavoromero +Date: Tue Nov 7 19:16:42 2000 +0000 + + adding old targets + +Author: gustavoromero +Date: Tue Nov 7 19:13:22 2000 +0000 + + removing a warning + +Author: gustavoromero +Date: Tue Nov 7 13:02:48 2000 +0000 + + adding targets + +Author: gustavoromero +Date: Mon Nov 6 12:38:54 2000 +0000 + + adding subdirectories + +Author: gustavoromero +Date: Mon Nov 6 12:37:58 2000 +0000 + + adding t-eoSymreg + +Author: gustavoromero +Date: Mon Nov 6 11:34:38 2000 +0000 + + adding target doc + +Author: gustavoromero +Date: Mon Nov 6 11:31:10 2000 +0000 + + adding doc target to all + +Author: evomarc +Date: Sun Nov 5 05:33:43 2000 +0000 + + Added constructors with 2 params _min and _max in generators + so you can now generate things in [_min, _max) instead of [0,_max) only + Modified the private data from maxim to {minim, range} accordingly. + +Author: evomarc +Date: Sun Nov 5 04:50:10 2000 +0000 + + Added a default value (0.5) to method flip + +Author: gustavoromero +Date: Fri Nov 3 21:23:09 2000 +0000 + + initial version + +Author: gustavoromero +Date: Fri Nov 3 20:03:26 2000 +0000 + + fixing autoconfiguration + +Author: evomarc +Date: Mon Oct 30 14:54:29 2000 +0000 + + Added some safety test in roulette_wheel procedures: + if total is zero, used to return iterator -1 - now returns uniform choice + +Author: evomarc +Date: Mon Oct 30 14:51:57 2000 +0000 + + Fine tuning of printOn: if fitness is invalid, now prints it + +Author: maartenkeijzer +Date: Fri Oct 27 09:13:06 2000 +0000 + + Another attempt in adding the flush + +Author: maartenkeijzer +Date: Fri Oct 27 09:12:31 2000 +0000 + + updated version info, added flush to stdoutmonitor and sprinkled a few typenames + in eoPop.h and eoGOpSelector.h (egcs 2.96 started complaining). + +Author: evomarc +Date: Fri Oct 27 04:38:29 2000 +0000 + + added a second ctor with more didactic ordering of parameters (for tutorial) + +Author: evomarc +Date: Fri Oct 27 04:07:21 2000 +0000 + + Added the member function append( unsigned _popSize, eoInit& _chromInit ) + who appends _popSize members to the population using an eoInit + +Author: evomarc +Date: Tue Oct 24 03:58:02 2000 +0000 + + dded Uniform Crossover (!) and "deterministic" bit-filp mutation + +Author: evomarc +Date: Tue Oct 24 03:57:10 2000 +0000 + + Added the calls to base class I/O routines in printOn and readFrom + +Author: maartenkeijzer +Date: Mon Oct 23 10:58:54 2000 +0000 + + It is using delim now + +Author: maartenkeijzer +Date: Mon Oct 9 16:13:20 2000 +0000 + + Changed functor base names and added to version + +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. + +Author: maartenkeijzer +Date: Fri Oct 6 07:50:10 2000 +0000 + + Updated authors and started a README + +Author: maartenkeijzer +Date: Fri Oct 6 07:32:26 2000 +0000 + + Changed ostream_iterator to use AtomType rather than double. + Stupid me! + +Author: mac +Date: Fri Sep 29 10:39:19 2000 +0000 + + Updated version no. to 0.9.1 + +Author: mac +Date: Wed Sep 20 13:32:28 2000 +0000 + + Error in random_generator removed. + +Author: mac +Date: Sat Sep 9 13:52:16 2000 +0000 + + Changed construction order as gcc was warning + +Author: mac +Date: Sat Sep 9 13:43:31 2000 +0000 + + eo: added some missing entries + Pop: error in nth_element_fitness + sga: error in eval + eoParseTree: oddities with gcc + checkpointing: added eoParser and eoState + eoParser: support for wrongly entered parameter names + rnd_generators: flip(0.5) -> flip(bias) in binary_generator + selectors.h: ??? + +Author: mac +Date: Wed Aug 23 14:56:04 2000 +0000 + + Added -O2 as compiler flag + +Author: mac +Date: Wed Aug 23 13:07:51 2000 +0000 + + ok, fixed this problem with typedefs in gcc-0.92 (strange....) + +Author: mac +Date: Wed Aug 23 12:52:48 2000 +0000 + + Yet another change in eoParseTree + +Author: mac +Date: Wed Aug 23 12:50:34 2000 +0000 + + eoParseTree-- changed typedef + +Author: mac +Date: Wed Aug 23 12:03:01 2000 +0000 + + eoCounter? + eoEasyEA -- made it copyable again + eoEvalFunc -- added specialized eoEvalFuncCounter + eoEvolutionStrategy -- nothing much + eoGenContinue -- nothing + eoPop -- fixed nth_element_fitness + eoBitOp -- fixed error in xover + eoFileMonitor -- now appends always + eoParam -- worked around memory leak in MSC's strstream + eoParser -- changed -pconfig_file to @config_file + eoParser -- added messages instead of exception when required param is missing + eoStat -- added eoDistanceStat + t-eoFunctor -- don't know + +Author: mac +Date: Fri Aug 18 08:59:20 2000 +0000 + + +Author: mac +Date: Fri Aug 18 08:57:26 2000 +0000 + + Oh, right, dangling pragma + +Author: mac +Date: Fri Aug 18 08:56:14 2000 +0000 + + some signed/unsigned comparisons removed + +Author: mac +Date: Fri Aug 18 08:44:22 2000 +0000 + + Added symbolic regression, which tests combined ops as well + +Author: root +Date: Tue Aug 15 21:15:36 2000 +0000 + + initial checkin + +Author: mac +Date: Mon Aug 14 11:18:34 2000 +0000 + + Removed a few dsp files and changed saving/loading eoPops a bit. + +Author: mac +Date: Thu Aug 10 16:43:39 2000 +0000 + + changed int to size_t + +Author: mac +Date: Thu Aug 10 16:42:37 2000 +0000 + + *** empty log message *** + +Author: mac +Date: Thu Aug 10 16:41:04 2000 +0000 + + Added binary_value.h + +Author: mac +Date: Thu Aug 10 16:36:55 2000 +0000 + + changed int compare to size_t + +Author: mac +Date: Thu Aug 10 16:35:15 2000 +0000 + + changed int compare to size_t + +Author: mac +Date: Thu Aug 10 16:34:05 2000 +0000 + + main should return int + +Author: mac +Date: Thu Aug 10 16:32:44 2000 +0000 + + changed int to size_t + +Author: mac +Date: Thu Aug 10 14:33:37 2000 +0000 + + Forgot to remove enum value init + +Author: mac +Date: Thu Aug 10 14:31:19 2000 +0000 + + Still part of extreme cleanup + +Author: mac +Date: Thu Aug 10 14:30:25 2000 +0000 + + Still part of extreme cleanup + +Author: mac +Date: Thu Aug 10 14:26:50 2000 +0000 + + Still part of extreme cleanup + +Author: mac +Date: Thu Aug 10 14:25:45 2000 +0000 + + Still part of extreme cleanup + +Author: mac +Date: Thu Aug 10 14:23:19 2000 +0000 + + no + +Author: mac +Date: Thu Aug 10 14:18:34 2000 +0000 + + Extreme cleanup, see src/obsolete for details + +Author: mac +Date: Thu Aug 3 20:00:39 2000 +0000 + + Temporarily added Makefile.am to prevent errors + +Author: mac +Date: Thu Aug 3 19:54:42 2000 +0000 + + Removed contrib dir reference + +Author: jmerelo +Date: Thu Aug 3 17:33:03 2000 +0000 + + More changes to Makefile.am + +Author: jmerelo +Date: Thu Aug 3 17:30:57 2000 +0000 + + More changes to Makefile.am + +Author: jmerelo +Date: Thu Aug 3 17:22:46 2000 +0000 + + More changes to Makefile.am + +Author: jmerelo +Date: Thu Aug 3 17:15:42 2000 +0000 + + Changes mostly to Makefile.ams here and there, to be able to do a clean distribution + +Author: mac +Date: Thu Aug 3 17:11:54 2000 +0000 + + New fresh ltconfig, works on my RedHat distr and also on geneura + +Author: mac +Date: Thu Aug 3 17:11:02 2000 +0000 + + Added a different libtool configure so it runs on more machines + +Author: jmerelo +Date: Thu Aug 3 16:37:51 2000 +0000 + + Changed some problems with Makefile.am + +Author: jmerelo +Date: Thu Aug 3 15:44:01 2000 +0000 + + Added missing files, and LICENSE + +Author: mac +Date: Fri Jul 28 10:26:44 2000 +0000 + + removed + +Author: mac +Date: Fri Jul 28 06:10:34 2000 +0000 + + testing if this configure is protable + +Author: gustavo +Date: Tue Jul 18 11:33:56 2000 +0000 + + ignore files created by examples + +Author: gustavo +Date: Tue Jul 18 11:30:39 2000 +0000 + + fix examples using binary_value + +Author: marc +Date: Thu Jun 22 03:23:15 2000 +0000 + + The initial individuals were evaluated directly using binary_value + This resulted in the fitness NOT being set, and some abort or segmentation fault later + Only eoEvalFunc shouydl be used to evaluate individuals!!! + +Author: gustavo +Date: Fri Jun 16 10:20:23 2000 +0000 + + changing version number + +Author: gustavo +Date: Fri Jun 16 09:38:43 2000 +0000 + + erasing LICENSE from test directory + +Author: gustavo +Date: Thu Jun 15 14:29:25 2000 +0000 + + *** empty log message *** + +Author: gustavo +Date: Wed Jun 14 16:29:00 2000 +0000 + + erasing warnings + +Author: mac +Date: Wed Jun 14 10:33:53 2000 +0000 + + Yet again some documentation change + +Author: mac +Date: Wed Jun 14 07:30:21 2000 +0000 + + Removed double reference to t-eoESFull + +Author: mac +Date: Wed Jun 14 07:27:51 2000 +0000 + + Removed double reference to t-eoESFull + +Author: mac +Date: Tue Jun 13 14:31:53 2000 +0000 + + Added ownership functionality and made the thing non-copyable + +Author: mac +Date: Tue Jun 13 14:31:22 2000 +0000 + + Some 'improvements' added + +Author: mac +Date: Tue Jun 13 14:30:47 2000 +0000 + + Added an ownership function to eoState + +Author: mac +Date: Tue Jun 13 10:27:10 2000 +0000 + + Changed base class eoEsBase to eoFixedLength + +Author: mac +Date: Tue Jun 13 10:25:53 2000 +0000 + + updated documentation + +Author: mac +Date: Tue Jun 13 09:48:24 2000 +0000 + + Fixed typedef Type error + +Author: mac +Date: Tue Jun 13 09:43:34 2000 +0000 + + Removed eoEsBase and created an eoFixedLength + +Author: mac +Date: Mon Jun 12 20:24:27 2000 +0000 + + Oh, right found some errors using gcc + +Author: mac +Date: Mon Jun 12 20:23:20 2000 +0000 + + Oh, right found some errors + +Author: mac +Date: Mon Jun 12 20:09:59 2000 +0000 + + New ES routines + +Author: mac +Date: Mon Jun 12 20:08:01 2000 +0000 + + Added a range member function to evaluate an iterator range + +Author: mac +Date: Mon Jun 12 20:07:25 2000 +0000 + + eoInit is a base class for making EO's, eoPop now has a constructor + for eoInit's + +Author: mac +Date: Sat Jun 10 13:22:53 2000 +0000 + + Removed dependence on eoUniform, changed it to use rng.random or rng.uniform directly + +Author: gustavo +Date: Fri May 26 17:18:06 2000 +0000 + + ignore t-eoExternalEO + +Author: mac +Date: Thu May 25 13:04:57 2000 +0000 + + Removed this ugly defaulting to 1 behaviour and solved it using template specialization + +Author: mac +Date: Thu May 25 12:21:06 2000 +0000 + + Added dummy case general: + +Author: gustavo +Date: Thu May 25 11:03:00 2000 +0000 + + warning hunting + +Author: mac +Date: Thu May 25 07:26:13 2000 +0000 + + Oops, corrected error in ctor(istream) + +Author: mac +Date: Thu May 25 07:23:24 2000 +0000 + + Oops, corrected error in adding t-eoExternalEO + +Author: mac +Date: Thu May 25 07:18:25 2000 +0000 + + eoExternalEO, support for using plain functions and structs in EO + +Author: mac +Date: Thu May 25 07:17:23 2000 +0000 + + Changed default printOn to have a trailing space instead of endl + +Author: mac +Date: Thu May 25 07:16:35 2000 +0000 + + Updated dsp, dsw and added t_eoExternalEO.dsp + +Author: mac +Date: Thu May 25 07:13:43 2000 +0000 + + Updated makefile and added t-eoExternalEO + +Author: mac +Date: Thu Apr 20 11:11:58 2000 +0000 + + removed reference to rint() (what does this function do anyway? it is not ANSI and defined nowhere in eo!) + +Author: mac +Date: Thu Apr 20 11:06:02 2000 +0000 + + Added a bias function next to bind(). This function will bias the selection to select certain specific guys... + +Author: mac +Date: Thu Apr 20 10:48:07 2000 +0000 + + Remove eoBinaryTerm, should not have been here in the first place + +Author: gustavo +Date: Wed Apr 12 09:51:50 2000 +0000 + + adding test to test/.cvsignore + +Author: gustavo +Date: Tue Apr 11 12:18:30 2000 +0000 + + some fix + +Author: mac +Date: Sun Apr 9 10:16:28 2000 +0000 + + getOp() should return a non-const reference + +Author: mac +Date: Sun Apr 9 10:13:27 2000 +0000 + + Changed int target to size_t target (produced warning) + +Author: mac +Date: Sun Apr 9 10:10:39 2000 +0000 + + eoFitTerm did not implement className + +Author: mac +Date: Sun Apr 9 10:09:32 2000 +0000 + + eoFitTerm did not implement className + +Author: mac +Date: Sun Apr 9 10:05:55 2000 +0000 + + Updated eoBreeder to use the even newer general operator interface + +Author: mac +Date: Sun Apr 9 10:00:55 2000 +0000 + + Updated eoBreeder to use the even newer general operator interface + +Author: mac +Date: Sun Apr 9 09:59:06 2000 +0000 + + Specialized it for bool, so that we don't get these MSVC warnings. + +Author: mac +Date: Sun Apr 9 09:54:25 2000 +0000 + + Oops, it's a pain to get the makefiles up to date when you are working on two machines.... + +Author: mac +Date: Sun Apr 9 09:50:44 2000 +0000 + + Oops, forgot to make operator() return an eoMonitor + +Author: mac +Date: Sun Apr 9 09:48:38 2000 +0000 + + Oops, forgot to make operator() return an eoMonitor + +Author: mac +Date: Sun Apr 9 09:46:20 2000 +0000 + + Updated documentation to give proper include file in doxygen and define a module selectors + Also added a load(stream) and save(stream) to eoState + +Author: mac +Date: Sun Apr 9 09:44:53 2000 +0000 + + Updated documentation to give proper include file in doxygen and define a module bitstring + +Author: mac +Date: Sun Apr 9 09:43:40 2000 +0000 + + Added t-eoGOpSel. + +Author: mac +Date: Sun Apr 9 09:41:29 2000 +0000 + + Changed the general operator interface to be consistent with the rest + of EO, updated some documentation. + +Author: mac +Date: Fri Apr 7 14:23:59 2000 +0000 + + updated Makefiles and removed a few unneeded files. note: ES files are pending + +Author: mac +Date: Fri Apr 7 09:04:50 2000 +0000 + + no message + +Author: gustavo +Date: Tue Apr 4 15:22:04 2000 +0000 + + changing include style from ... to <...> + +Author: gustavo +Date: Tue Apr 4 11:00:18 2000 +0000 + + initial .cvsignore + +Author: gustavo +Date: Mon Apr 3 15:52:31 2000 +0000 + + changing autonconfiguration to compile more examples and to create documentation + +Author: gustavo +Date: Mon Apr 3 15:27:56 2000 +0000 + + forgeting multiOps + +Author: gustavo +Date: Mon Apr 3 09:51:29 2000 +0000 + + too many EMPTY constructors + +Author: gustavo +Date: Mon Apr 3 09:32:43 2000 +0000 + + adding & modifying .cvsignore's + +Author: gustavo +Date: Fri Mar 31 16:23:16 2000 +0000 + + Maarten was right + +Author: gustavo +Date: Fri Mar 31 14:34:50 2000 +0000 + + Makefile.in don't need to be in cvs + +Author: gustavo +Date: Fri Mar 31 14:33:13 2000 +0000 + + more fix in makefiles + +Author: mac +Date: Fri Mar 31 10:14:15 2000 +0000 + + Added checkpointing to the makefile, but have to test it later on a Linux box + +Author: mac +Date: Fri Mar 31 10:04:39 2000 +0000 + + Finalized Checkpointing, renamed t-testSta.... to t-eoStateAndParser + added a checkpoint tester, but did not yet update the Makefiles as + I don't have automake on my machine + +Author: mac +Date: Fri Mar 31 10:02:18 2000 +0000 + + Finalized Checkpointing, see t-eoCheckpointing for a test + +Author: mac +Date: Fri Mar 31 10:00:22 2000 +0000 + + Added a className member + +Author: gustavo +Date: Thu Mar 30 18:15:14 2000 +0000 + + adding const... leaving as is + +Author: gustavo +Date: Thu Mar 30 18:02:03 2000 +0000 + + makefiles almost work + +Author: gustavo +Date: Thu Mar 30 17:11:20 2000 +0000 + + fixing makefiles + +Author: gustavo +Date: Thu Mar 30 14:20:25 2000 +0000 + + changing Makefile.am's to accept new subdiretory structure + +Author: mac +Date: Thu Mar 30 09:43:21 2000 +0000 + + changed erronuous classname() to className() + +Author: mac +Date: Thu Mar 23 14:41:12 2000 +0000 + + few minor mods + +Author: mac +Date: Wed Mar 22 18:55:12 2000 +0000 + + Adapted it for the poor stdc++ support of g++ + +Author: mac +Date: Wed Mar 22 17:10:07 2000 +0000 + + no message + +Author: mac +Date: Wed Mar 22 17:09:36 2000 +0000 + + Changed some includes for the new dir structure + +Author: mac +Date: Wed Mar 22 16:49:35 2000 +0000 + + Changed some includes for the new dir structure + +Author: mac +Date: Wed Mar 22 16:47:27 2000 +0000 + + test the state and the parser + +Author: mac +Date: Wed Mar 22 15:39:32 2000 +0000 + + Changed readFrom, which is no longer line based + +Author: mac +Date: Wed Mar 22 15:38:16 2000 +0000 + + Obsolete, now present in eoOp.h + +Author: mac +Date: Wed Mar 22 15:14:16 2000 +0000 + + Changed a few params in the configuration file + +Author: mac +Date: Wed Mar 22 15:00:38 2000 +0000 + + (re)moving... + +Author: mac +Date: Wed Mar 22 14:48:49 2000 +0000 + + (re)moving... + +Author: mac +Date: Wed Mar 22 14:38:10 2000 +0000 + + Configuration file for doxygen + +Author: mac +Date: Wed Mar 22 14:32:37 2000 +0000 + + (re)moving... + +Author: mac +Date: Wed Mar 22 14:30:57 2000 +0000 + + no message + +Author: mac +Date: Wed Mar 22 14:23:20 2000 +0000 + + moving... + +Author: mac +Date: Wed Mar 22 14:21:02 2000 +0000 + + moved old files here + +Author: mac +Date: Wed Mar 22 14:18:39 2000 +0000 + + Moved the es files to an es directory + +Author: mac +Date: Wed Mar 22 14:12:08 2000 +0000 + + no message + +Author: mac +Date: Wed Mar 22 14:04:03 2000 +0000 + + Added utilities directory, this contains state, parser etc. + +Author: mac +Date: Wed Mar 22 13:58:29 2000 +0000 + + Removed obsolete references + +Author: mac +Date: Wed Mar 22 13:57:57 2000 +0000 + + moved to utils + +Author: mac +Date: Mon Mar 20 17:35:24 2000 +0000 + + eoSelfEval was empty + +Author: mac +Date: Mon Mar 20 17:32:42 2000 +0000 + + Just changed a typo in the documentation + +Author: mac +Date: Mon Mar 20 16:13:32 2000 +0000 + + +Author: marc +Date: Mon Mar 13 10:17:12 2000 +0000 + + Put eoTerm into the eo hierarchy - it was in the air! + Added the className method + +Author: marc +Date: Mon Mar 13 10:14:20 2000 +0000 + + Changed some int into unsigned to avoid Gnu warnings + +Author: marc +Date: Mon Mar 13 10:10:00 2000 +0000 + + Removed extra {} in operator() + +Author: mac +Date: Mon Mar 6 16:28:37 2000 +0000 + + Removed the call to the istream ctor, replaced it with readFrom + +Author: mac +Date: Mon Mar 6 16:21:54 2000 +0000 + + Removed the call to the istream ctor, replaced it with readFrom + +Author: mac +Date: Mon Mar 6 16:09:46 2000 +0000 + + Removed the istream ctor + +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 +Date: Mon Mar 6 15:55:44 2000 +0000 + + Upgraded parse_tree a bit... + +Author: marc +Date: Thu Mar 2 05:54:01 2000 +0000 + + Removed extra () in method virtual const EOT& operator()(const eoPop& pop) + Changed the include of eoPop.h from <> to "" + +Author: marc +Date: Thu Mar 2 05:48:23 2000 +0000 + + - added the virtual destructors of all classes, + to suppress g++ annoying warnings when using -Wall option + +Author: marc +Date: Tue Feb 29 05:22:32 2000 +0000 + + Modified the order of base type and private data initializations + so the g++ does not complain when using the -Wall compile option + +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 + +Author: victor +Date: Mon Feb 21 18:21:58 2000 +0000 + + *** empty log message *** + +Author: victor +Date: Mon Feb 21 18:21:14 2000 +0000 + + A: has been fixed, ONCE MORE :-( + +Author: victor +Date: Mon Feb 21 18:03:31 2000 +0000 + + making the second parameter of the oprator() for binaria operators to be NON const + +Author: mac +Date: Sat Feb 19 18:21:47 2000 +0000 + + Changed double linefeeds, will undo this if it doesn't work + +Author: mac +Date: Sat Feb 19 17:37:18 2000 +0000 + + Removed double line feeds + +Author: mac +Date: Sat Feb 19 16:54:09 2000 +0000 + + Hi, just a simple test, I'm sorry to do it with the real repository, + but my machine here is not Unix + +Author: mac +Date: Sat Feb 19 16:32:12 2000 +0000 + + eoScalarFitness, 'envelope class' for making minimizing/maximizing fitness + +Author: mac +Date: Sat Feb 19 16:31:01 2000 +0000 + + Example file + +Author: mac +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 +Date: Sat Feb 19 16:27:38 2000 +0000 + + Added gp, example file in t-eoSymreg.cpp + +Author: victor +Date: Sat Feb 19 13:14:36 2000 +0000 + + Someone was using eoAltProportionalSelect.h only he/she knows whycd src + +Author: victor +Date: Sat Feb 19 12:50:48 2000 +0000 + + A: has been fixed , ONCE MORE :-( + +Author: victor +Date: Sat Feb 19 12:37:28 2000 +0000 + + Changing (ONCE MORE) eoEasyEA.h to allow 0 generation processes. + +Author: mac +Date: Wed Feb 16 15:17:43 2000 +0000 + + *** empty log message *** + +Author: mac +Date: Wed Feb 16 15:11:18 2000 +0000 + + *** empty log message *** + +Author: mac +Date: Wed Feb 16 15:05:19 2000 +0000 + + Mak: Added the eoQuadratic Op and more ... (and I hate VI) + +Author: mac +Date: Wed Feb 16 15:03:45 2000 +0000 + + *** empty log message *** + +Author: marc +Date: Wed Feb 16 04:40:20 2000 +0000 + + Changed all "float" to "double" + But more than that, this is a test of CVS for me + Marc + +Author: mac +Date: Tue Feb 15 15:08:00 2000 +0000 + + just a test + +Author: victor +Date: Fri Feb 11 12:05:07 2000 +0000 + + A: has been fixed :-)) + +Author: gustavo +Date: Wed Feb 9 19:50:02 2000 +0000 + + some test + +Author: jmerelo +Date: Mon Feb 7 17:16:16 2000 +0000 + + Added new files to the brew, mainly distance and new-op-interface related + +Author: gustavo +Date: Wed Jan 26 17:48:24 2000 +0000 + + *** empty log message *** + +Author: victor +Date: Tue Jan 25 08:20:22 2000 +0000 + + A very silly error has been fixed + +Author: gustavo +Date: Mon Jan 24 21:16:54 2000 +0000 + + some reviews + +Author: gustavo +Date: Mon Jan 24 21:13:21 2000 +0000 + + some reviews + +Author: victor +Date: Tue Jan 18 13:43:39 2000 +0000 + + I have change the do...while(terminator) into while(terminator){...}, because may be the termination condition is reached just atthe beginning (for instance 0 generations) + +Author: victor +Date: Tue Jan 11 13:25:32 2000 +0000 + + Another little bug fixed + +Author: gustavo +Date: Tue Jan 11 12:13:18 2000 +0000 + + bug fix in eoTournament + +Author: victor +Date: Tue Jan 4 13:04:00 2000 +0000 + + A little problem existed when the Parser tried to read a String because a \0 was inserted sometimes (no others) making imposible to add a new string to the one read and then turning the full string into a char* (understable? :-) + +Author: victor +Date: Tue Jan 4 10:43:06 2000 +0000 + + Changing the way parameters are shown to the user when the -h or --help flags are used + +Author: victor +Date: Tue Dec 21 13:39:42 1999 +0000 + + Minor changes in eoRNG.h + +Author: victor +Date: Tue Dec 21 12:12:29 1999 +0000 + + eoOpSelector has a method called getOp that HAD to return a non-constant reference to an operator; in fact it returned a CONST reference. Now, I've changed it + +Author: victor +Date: Tue Dec 21 11:41:19 1999 +0000 + + Updating the selectors: they inherited from eoSelect and noew the inherite from eoBinPopOp + +Author: victor +Date: Tue Dec 21 09:58:45 1999 +0000 + + Minor changes in eoParser.h + +Author: victor +Date: Fri Dec 17 12:04:06 1999 +0000 + + Moving function InitRamdom to eoParserUtils.h + +Author: jmerelo +Date: Fri Dec 17 09:19:13 1999 +0000 + + Changes + +Author: victor +Date: Wed Dec 15 16:47:41 1999 +0000 + + A little mistake has been corrected + +Author: victor +Date: Wed Dec 15 16:42:13 1999 +0000 + + The constants N,M and K are not declared twice when using RNG in different file of the same program + +Author: victor +Date: Wed Dec 15 13:57:09 1999 +0000 + + I have turned into comments the Pop constructor that used Type as the type of the gene, given that an EO can have NO genes + +Author: jmerelo +Date: Mon Nov 22 09:47:32 1999 +0000 + + Added changes mainly by Marc + +Author: jmerelo +Date: Mon Nov 15 09:26:33 1999 +0000 + + Added Marc's ES files and .dsp files for others + +Author: jmerelo +Date: Fri Oct 29 11:23:10 1999 +0000 + + Added eoParser + +Author: jmerelo +Date: Mon Oct 25 08:25:42 1999 +0000 + + Added new RNG and test files for it + +Author: jmerelo +Date: Tue Oct 19 11:47:15 1999 +0000 + + Small modifications + +Author: gustavo +Date: Fri Oct 15 13:16:50 1999 +0000 + + bug fix in eoBinBitflip + +Author: jmerelo +Date: Fri Oct 15 11:18:52 1999 +0000 + + Changed eoBinBitFlip thanks to Jacques suggestion + +Author: jmerelo +Date: Fri Oct 15 07:34:55 1999 +0000 + + Small changes to makefiles + +Author: jmerelo +Date: Wed Oct 13 08:38:33 1999 +0000 + + Changes in configure y makefiles to account for new version and new files + +Author: gustavo +Date: Mon Oct 11 10:20:39 1999 +0000 + + updating with new tests + +Author: gustavo +Date: Fri Oct 8 17:45:49 1999 +0000 + + adding more functions and tests for eoNonUniform + +Author: jmerelo +Date: Fri Oct 8 11:39:58 1999 +0000 + + Two files left over added to the repo + +Author: jmerelo +Date: Fri Oct 8 11:39:20 1999 +0000 + + Added a full algorithm to the new EO, with terminators, and things like that + +Author: jmerelo +Date: Fri Oct 8 09:52:31 1999 +0000 + + Added two more files + +Author: jmerelo +Date: Fri Oct 8 09:51:40 1999 +0000 + + Changed stuff to make eoGeneration work + +Author: jmerelo +Date: Fri Oct 8 07:40:34 1999 +0000 + + Cosmetic changes + +Author: gustavo +Date: Thu Oct 7 11:39:08 1999 +0000 + + adding t-eogeneration + +Author: gustavo +Date: Thu Oct 7 11:38:14 1999 +0000 + + putting eoNonUniform into a separate file + +Author: gustavo +Date: Tue Oct 5 11:32:17 1999 +0000 + + adding eoNonUniformOperator to eoOp.h + +Author: gustavo +Date: Mon Oct 4 11:17:19 1999 +0000 + + adding t-eogeneration.cpp + +Author: victor +Date: Fri Oct 1 17:00:38 1999 +0000 + + Updating Makefile.am to include eo2d.h and eo2dVector.h + +Author: victor +Date: Fri Oct 1 17:00:02 1999 +0000 + + Updating Makefile.am to compile t-eo2dVector.h + +Author: victor +Date: Fri Oct 1 16:36:04 1999 +0000 + + *** empty log message *** + +Author: victor +Date: Fri Oct 1 16:33:59 1999 +0000 + + All the methods have been implemented. Only three of them (asignement operator, read from and write to a stream) remain unfinished. + +Author: victor +Date: Fri Oct 1 16:32:46 1999 +0000 + + Final (or almost) version by now. + +Author: victor +Date: Wed Sep 29 11:43:34 1999 +0000 + + Adding an interface for 2-dimensional chromosomes + +Author: victor +Date: Wed Sep 29 11:41:34 1999 +0000 + + Fixing a little bug in the random generator. Variable size was used instead of _size, which is the parameter the method gets + +Author: gustavo +Date: Tue Sep 28 11:56:21 1999 +0000 + + testing and debugging eoGeneration + +Author: gustavo +Date: Tue Sep 28 10:26:39 1999 +0000 + + finish eoGeneration... still to be tested + +Author: gustavo +Date: Tue Sep 21 18:14:39 1999 +0000 + + fixing bugs in replacers and moving some code between files + +Author: gustavo +Date: Tue Sep 21 11:36:38 1999 +0000 + + pop need a reevaluation after breeding + +Author: gustavo +Date: Mon Sep 20 18:07:35 1999 +0000 + + fixing cvsignore + +Author: gustavo +Date: Mon Sep 20 11:48:52 1999 +0000 + + fixing tests + +Author: jmerelo +Date: Mon Sep 20 11:37:00 1999 +0000 + + Added LICENSE + +Author: jmerelo +Date: Mon Sep 20 11:35:01 1999 +0000 + + Changes to eo1d interface and bug fixes + +Author: gustavo +Date: Fri Sep 10 12:21:50 1999 +0000 + + *** empty log message *** + +Author: gustavo +Date: Fri Sep 10 12:13:53 1999 +0000 + + updating eo/test/.cvsignore for new eoBin tests + +Author: gustavo +Date: Fri Sep 10 12:11:11 1999 +0000 + + *** empty log message *** + +Author: gustavo +Date: Fri Sep 10 12:05:57 1999 +0000 + + *** empty log message *** + +Author: gustavo +Date: Fri Sep 10 12:03:51 1999 +0000 + + adding examples for eoBin & other stuff + +Author: gustavo +Date: Fri Sep 10 11:48:42 1999 +0000 + + adding examples for eoBin & other stuff + +Author: gustavo +Date: Fri Sep 10 11:07:46 1999 +0000 + + *** empty log message *** + +Author: gustavo +Date: Mon Feb 15 17:47:30 1999 +0000 + + adding eoGeneration + +Author: jmerelo +Date: Mon Feb 15 16:03:04 1999 +0000 + + New .dsp files for new test programs + +Author: jmerelo +Date: Mon Feb 15 16:01:35 1999 +0000 + + Compiled new stuff on VC++, changes to breeder + +Author: gustavo +Date: Mon Feb 15 11:55:59 1999 +0000 + + doing things work on VC++ + +Author: gustavo +Date: Fri Feb 12 17:56:55 1999 +0000 + + bux fix in t-eoinsertion.cpp + +Author: gustavo +Date: Fri Feb 12 17:43:28 1999 +0000 + + eoBreeder almost finished + +Author: jmerelo +Date: Wed Feb 10 17:14:08 1999 +0000 + + Added some files, compiled some stuff in VC++, and finished eoOpSelMason + +Author: gustavo +Date: Wed Feb 10 17:05:16 1999 +0000 + + adding eoBreeder + +Author: gustavo +Date: Wed Feb 10 13:39:48 1999 +0000 + + small bug fixes + +Author: gustavo +Date: Tue Feb 9 19:06:51 1999 +0000 + + *** empty log message *** + +Author: jmerelo +Date: Tue Feb 9 18:40:00 1999 +0000 + + Changes to makefiles and other things + +Author: gustavo +Date: Tue Feb 9 18:16:42 1999 +0000 + + *** empty log message *** + +Author: jmerelo +Date: Tue Feb 9 17:31:16 1999 +0000 + + New bitOp factories and things like that + +Author: gustavo +Date: Tue Feb 9 17:27:22 1999 +0000 + + new replacer + +Author: jmerelo +Date: Mon Feb 8 19:15:27 1999 +0000 + + Changed monopfactory to opfactory; changes in the examples + +Author: gustavo +Date: Mon Feb 8 18:47:07 1999 +0000 + + looking for a bug in eoInsertion + +Author: jmerelo +Date: Mon Feb 8 16:13:26 1999 +0000 + + New files added and fixes for VC++ + +Author: gustavo +Date: Mon Feb 8 16:11:55 1999 +0000 + + some bug fix + +Author: gustavo +Date: Mon Feb 8 14:15:11 1999 +0000 + + learning about autoconf: eoBin and bvector.h + +Author: gustavo +Date: Mon Feb 8 12:43:52 1999 +0000 + + eoBin/eoBinOp division + +Author: gustavo +Date: Fri Feb 5 18:25:28 1999 +0000 + + adding eoInsertion + +Author: gustavo +Date: Fri Feb 5 16:34:00 1999 +0000 + + eoLottery finished + +Author: gustavo +Date: Thu Feb 4 17:38:39 1999 +0000 + + adding acconfig.h + +Author: gustavo +Date: Wed Feb 3 20:42:57 1999 +0000 + + changes on eoLottery + +Author: jmerelo +Date: Wed Feb 3 18:34:20 1999 +0000 + + Changes to eo and opsel to quash compiling bugs + +Author: gustavo +Date: Wed Feb 3 17:28:07 1999 +0000 + + some changes to start, new work on eoLottery + +Author: jmerelo +Date: Wed Feb 3 17:26:52 1999 +0000 + + Chenges to EO + +Author: jmerelo +Date: Mon Feb 1 18:18:39 1999 +0000 + + Remove old eoObject.cpp + +Author: gustavo +Date: Fri Jan 29 12:23:55 1999 +0000 diff --git a/deprecated/eo/CMakeLists.txt b/deprecated/eo/CMakeLists.txt new file mode 100644 index 000000000..9b0050e27 --- /dev/null +++ b/deprecated/eo/CMakeLists.txt @@ -0,0 +1,139 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) + +###################################################################################### +### 0) If you want to set your variables in eo-conf.cmake and avoid the cmd line +###################################################################################### + +#INCLUDE(eo-conf.cmake OPTIONAL) + +###################################################################################### + + +###################################################################################### +### 1) Main project config +###################################################################################### + +# set the project namef and other variables +PROJECT(EO) + +# CMake > 2.8 is needed, because of the FindOpenMP feature +#cmake_minimum_required(VERSION 2.8) + +#SET(PROJECT_VERSION_MAJOR 1) +#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}${PROJECT_VERSION_MISC}" CACHE STRING "Global version" FORCE) +SET(GLOBAL_VERSION "${VERSION}") + +SET(PACKAGE_BUGREPORT "eodev-help@sourceforge.net" CACHE STRING "Package bug report" FORCE) +SET(PACKAGE_NAME "Evolving Objects" CACHE STRING "Package name" FORCE) +SET(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}"CACHE STRING "Package string full name" FORCE) +SET(PACKAGE_TARNAME "eo" CACHE STRING "Package tar name" FORCE) + +# regular expression checking +INCLUDE_REGULAR_EXPRESSION("^.*$" "^$") + +# set a language for the entire project. +ENABLE_LANGUAGE(CXX) +ENABLE_LANGUAGE(C) + +###################################################################################### + + +##################################################################################### +### 2) Include required modules / configuration files +##################################################################################### + +FIND_PACKAGE(OpenMP) +IF(OPENMP_FOUND) + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") +ENDIF() + +INCLUDE(CMakeBackwardCompatibilityCXX) + +INCLUDE(FindDoxygen) + +INCLUDE(FindGnuplot) + +INCLUDE(CheckLibraryExists) + +IF(UNIX) + INCLUDE(ConfigureChecks.cmake) +ENDIF(UNIX) + +INCLUDE(Dart OPTIONNAL) + +# now create config headers +CONFIGURE_FILE(config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h) + +# now create config install_symlink script file +CONFIGURE_FILE(install_symlink.py.cmake ${CMAKE_CURRENT_BINARY_DIR}/install_symlink.py) + +# now create PKGBUILD file for archlinux package manager +CONFIGURE_FILE(PKGBUILD.cmake ${CMAKE_CURRENT_BINARY_DIR}/PKGBUILD) + +# Set a special flag if the environment is windows (should do the same in a config.g file) +IF (WIN32) + ADD_DEFINITIONS(-D_WINDOWS=1) +ENDIF (WIN32) + +###################################################################################### + +###################################################################################### + + +###################################################################################### +### compilation of examples? +###################################################################################### + +#SET(ENABLE_CMAKE_EXAMPLE TRUE CACHE BOOL "Enable copy of benchs and parameters file?") + +###################################################################################### + + +###################################################################################### +### 4) Test config +###################################################################################### + +#IF (ENABLE_CMAKE_TESTING) +# ENABLE_TESTING() +#ENDIF (ENABLE_CMAKE_TESTING) + +###################################################################################### + + +###################################################################################### +### 5) Where must cmake go now ? +###################################################################################### + +#ADD_SUBDIRECTORY(app) +ADD_SUBDIRECTORY(doc) +ADD_SUBDIRECTORY(src) +ADD_SUBDIRECTORY(test) +ADD_SUBDIRECTORY(tutorial) + +###################################################################################### + + +###################################################################################### +### 6) Install pkg-config config file for EO +###################################################################################### + +SET(PCPREFIX "/usr") +SET(PCFLAGS "-leoutils -leo -les -lga -lcma -lgcov") +SET(PCINCLUDEDIR "eo") +CONFIGURE_FILE(pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/eo.pc) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/eo.pc DESTINATION local/${LIB}/pkgconfig COMPONENT headers) + +###################################################################################### + + +###################################################################################### +### 7) Include packaging +###################################################################################### + +#INCLUDE(Packaging.cmake) + +###################################################################################### diff --git a/deprecated/eo/COPYING b/deprecated/eo/COPYING new file mode 100644 index 000000000..b8df7fd44 --- /dev/null +++ b/deprecated/eo/COPYING @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +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 + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +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 +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +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 + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +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 + + 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 +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you 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 + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/deprecated/eo/CTestConfig.cmake b/deprecated/eo/CTestConfig.cmake new file mode 100644 index 000000000..465d208d6 --- /dev/null +++ b/deprecated/eo/CTestConfig.cmake @@ -0,0 +1,7 @@ +set(CTEST_PROJECT_NAME "ParadisEO") +set(CTEST_NIGHTLY_START_TIME "00:00:00 EST") + +set(CTEST_DROP_METHOD "http") +set(CTEST_DROP_SITE "cdash.inria.fr") +set(CTEST_DROP_LOCATION "/CDash/submit.php?project=ParadisEO") +set(CTEST_DROP_SITE_CDASH TRUE) diff --git a/deprecated/eo/ConfigureChecks.cmake b/deprecated/eo/ConfigureChecks.cmake new file mode 100644 index 000000000..5fabc9c38 --- /dev/null +++ b/deprecated/eo/ConfigureChecks.cmake @@ -0,0 +1,29 @@ +# NOTE: only add something here if it is really needed by EO + +INCLUDE(CheckIncludeFile) +INCLUDE(CheckIncludeFiles) +INCLUDE(CheckSymbolExists) +INCLUDE(CheckFunctionExists) +INCLUDE(CheckLibraryExists) + +CHECK_LIBRARY_EXISTS(m cos "/usr/lib" HAVE_LIBM) + +CHECK_INCLUDE_FILES(math.h "math.h" HAVE_MATH_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 +# cross-platform manner. It accounts for different calling +# conventions and the possibility that the symbol is defined as a +# macro. Note that some symbols require multiple includes in a +# 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) diff --git a/eo/ForRelease b/deprecated/eo/ForRelease similarity index 100% rename from eo/ForRelease rename to deprecated/eo/ForRelease diff --git a/deprecated/eo/INSTALL b/deprecated/eo/INSTALL new file mode 100644 index 000000000..6264e4cea --- /dev/null +++ b/deprecated/eo/INSTALL @@ -0,0 +1,86 @@ + +Basic Installation +================== + +The simplest way to compile the libraries or the provided softwares is to run +one of the script beginnig with "build_". Each script permits to build different +parts of the framework, with different options. + +To compile EO you will need CMake and a compiler for your system. + +So far the available scripts for posix systems using g++ are the following: + * build_gcc_linux_release : the most usefull script, build the core libraries in release mode + * build_gcc_linux_debug : build the core libraries with debugging informations in the binaries + * build_gcc_linux_tutorial : build the core libraries and the tutorials + * build_gcc_linux_unittest : build the core libraries and the tests executables + * build_gcc_linux_stl_parallel : build the core libraries enabling STL parallel algorithms (like sorting) + * build_gcc_linux_pyeo : build the core libraries and the python module + * distclean : remove the "release/" and "debug/" directories where the build scripts put the binaries + +For Windows systems using Visual Studio: + * build_vs2008_release.bat + You may need to adapt the ID to your version of Visual Studio, edit + the "Visual Studio 9 2008" string accordingly. + +The libraries are in the "release/lib/" or "debug/lib/" directories. + + +Compilers and Options +===================== + +The build scripts are really simple, take a look at them to see how to use the +build system. + +Basically, the steps are: + 0. remove any old build directory that's on the way: + rm -rf build/ + 1. create a directory in which to put build files: + mkdir build/ + 2. go in this directory: + cd build/ + 3. call cmake with the options you want, using the "-D" option and passing the + EO directory as an argument, for example: + cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_CMAKE_TESTING =1 .. + 4. now type your favorite "make" command, like: + make -j # use several processors at once when possible + 5. enjoy: + ./debug/test/t-eofitness + +Some of the available options are: + * CMAKE_BUILD_TYPE : + * "Debug" : embed debugging informations in the binaries) or + * "Release" : no debugging info and some optimizations (the default) + * ENABLE_EO_TUTORIAL : build the tutorial ("no" by default) + * ENABLE_CMAKE_TESTING : build the tests executables ("no" by default) + * ENABLE_PYEO : build the python module ("no" by default) + +You can pass generic options to the compiler, like: + * _GLIBCXX_PARALLEL : use the parallel version of the STL + + +Installation using packages +=========================== + +To construct a dummy template of the EO package you will need CPack. Be warned +that those do not guarantee correct dependencies and version management. + +Use the "package_*" scripts: + * package_deb : for debian-like systems + * package_rpm : for red-hat-like systems + +Or go through the following steps: + 1. go in the build directory where your binaries are: + cd build/ + 2. call CPack specifying the desired package system: + cpack -G DEB + 3. install the package: + sudo dpkg -i EO-1.1.1-Linux.deb + + +Basic installation +================== + +To install the framework system-wide, copy the "eo/" directory somewhere in your +path. The "lib/" directory should be reachable for the linker and the "src/" +directory must be in the compiler include path. + diff --git a/deprecated/eo/LICENSE b/deprecated/eo/LICENSE new file mode 100644 index 000000000..b8df7fd44 --- /dev/null +++ b/deprecated/eo/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +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 + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +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 +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +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 + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +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 + + 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 +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you 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 + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/deprecated/eo/NEWS b/deprecated/eo/NEWS new file mode 100644 index 000000000..f4625d6c3 --- /dev/null +++ b/deprecated/eo/NEWS @@ -0,0 +1,54 @@ +* current version + +* release 1.2 (16. May. 2011) + - fixed the incremental allocation issue in variation operators which were + taking too much time for big population sizes + - new class eoParallel enabling parallelization in EO using OpenMP. At this + time, it only concerns the evaluation operator, for advanced details go to + the file test/t-eoParallel.cpp. The default parallelization mode is off, to + switch it on, see the parameters prefixed by --parallelize-* + - pyeo compatible with the last version of Boost and Python libraries + - script installing EO manually in using symbolic links + - evaluators that throw an exception if a maximum time has been reached + (wallclock and CPU user time for POSIX systems), independently of the number of generations + - merged parser and parser-logger + - some bugfixes for windows systems + +* release 1.1 (8. Nov. 2010) + - provide cmake build system, remove the old autotools one + - package generation system + - 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 + - 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 + - dual fitness class to handle feasibility of individual with guarantee that feasible fitness will always be better than unfeasible one + - feasible fitness ratio stat + - interquartile range stat + - average size of individuals stat + - uniform(min,max) random function + - compatibility macros for compiling paradiseo with CUDACC + - removed old multi-objective classes, deprecated by the Paradiseo-MOEO project + - new website, switch from CVS to GIT, and a cool logo! + +* release 1.0.1 (23. Jan. 2006) + - Templates/ improvements + +* release 1.0 (29. Dec. 2006) + - Implement CMA-ES. + - Update introductory pages of documentation and webpage. + - 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. + 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/deprecated/eo/PKGBUILD.cmake b/deprecated/eo/PKGBUILD.cmake new file mode 100644 index 000000000..44f0b3687 --- /dev/null +++ b/deprecated/eo/PKGBUILD.cmake @@ -0,0 +1,23 @@ +# $Id: pkgbuild-mode.el,v 1.23 2007/10/20 16:02:14 juergen Exp $ +# Maintainer: Caner Candan +pkgname=libeo +pkgver=@PROJECT_VERSION@ +pkgrel=1 +pkgdesc="Evolving Objects is a template-based, ANSI-C++ evolutionary computation library which helps you to write your own stochastic optimization algorithms insanely fast." +url="" +arch=('i686' 'x86_64') +license=('LGPL') +depends=() +makedepends=('make' 'cmake') +conflicts=() +replaces=() +backup=() +install= +source=($pkgname-$pkgver.tar.gz) +md5sums=() +build() { + cd $startdir/src/$pkgname-$pkgver + cmake -DCMAKE_INSTALL_PREFIX=/usr . + make || return 1 + make DESTDIR=$startdir/pkg install +} diff --git a/deprecated/eo/README b/deprecated/eo/README new file mode 100644 index 000000000..d4268be0f --- /dev/null +++ b/deprecated/eo/README @@ -0,0 +1,89 @@ + EO README FILE + +======================================================================= + check latest news at http://eodev.sourceforge.net/ +======================================================================= + +Welcome to EO, the Evolving Objects library. + +The latest news about EO can be found on the sourceforge repository at + http://eodev.sourceforge.net/ + +In case of any problem, please e-mail us at + eodev-main@lists.sourceforge.net + +To get started, take a look at the tutorial, starting with + ./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 +the tutorial/Templates/ directory. Read Lesson 5 of the tutorial for +an introduction ;) + + +================================================================== + BUILDING EO +================================================================== +The basic installation procedure goes the following: + +Go to the "eo/" and run one of the "build_*" script.  + +Using the "build_gcc_linux_release" script is generally what you want. The +binaries are then located in the "release/" directory. + +Now you should probably go to the tutorial and start learning about EO +features and programming. + +In case of problems or if you want advanced options, you can read the INSTALL file. + +=================================================================== + DIRECTORY STRUCTURE +=================================================================== +After unpacking the archive file, you should end up with the following +structure: + +.../ the MAIN EO dir, created when unpacking + | + +-- src SOURCE dir. Contains most EO .h files + | | + | +- utils general utilities (e.g. RNG-related source files) + | | + | +- ga bistring-genotypes source files + | | + | +- es real-valued-genotypes source files + | | + | +- gp Genetic Programming source files + | | + | +- obsolete files from old versions - for upward compatibility + | + | + | + +-- 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) + | | + | +- html HTML files - start at index.html (see also tutorial) + | | + | +- latex latex files - use to generate Poatscript doc. + | | + | +- man Unix man format documentation + | + | + +-- test TEST files - for debugging purposes only + | + | + +-- app APPLICATIONS - one dir per separate application + | | + | +- gprop GA/backpropagation for neural nets + | | + | +- mastermind the wellknown MasterMind game + | + | + +-- win WINDOWS dir: project files for MS/VC5+ + diff --git a/deprecated/eo/THANKS b/deprecated/eo/THANKS new file mode 100644 index 000000000..e69de29bb diff --git a/deprecated/eo/ToDo b/deprecated/eo/ToDo new file mode 100644 index 000000000..f3da04f50 --- /dev/null +++ b/deprecated/eo/ToDo @@ -0,0 +1,2 @@ +See the code-documentation for details. +General ToDos should be documented at the end of doc/index.h. diff --git a/deprecated/eo/app/CMakeLists.txt b/deprecated/eo/app/CMakeLists.txt new file mode 100644 index 000000000..d13aac522 --- /dev/null +++ b/deprecated/eo/app/CMakeLists.txt @@ -0,0 +1,8 @@ +###################################################################################### +### 1) Where must cmake go now ? +###################################################################################### + +#ADD_SUBDIRECTORY(gprop) +#ADD_SUBDIRECTORY(gpsymreg) +ADD_SUBDIRECTORY(mastermind) +###################################################################################### diff --git a/deprecated/eo/app/gprop/CMakeLists.txt b/deprecated/eo/app/gprop/CMakeLists.txt new file mode 100644 index 000000000..e37af2e5f --- /dev/null +++ b/deprecated/eo/app/gprop/CMakeLists.txt @@ -0,0 +1,31 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Specify where CMake can find the libraries (mandatory: before 3) ) +###################################################################################### + +LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) + +###################################################################################### +### 3) Define your target(s): just an executable here +###################################################################################### + +SET (GPROP_SOURCES gprop.cpp) + +# especially for Visual Studio +IF(NOT WIN32 OR CYGWIN) + ADD_EXECUTABLE(gprop ${GPROP_SOURCES}) + ADD_DEPENDENCIES(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/deprecated/eo/app/gprop/gprop.cpp b/deprecated/eo/app/gprop/gprop.cpp new file mode 100644 index 000000000..3c8d17c44 --- /dev/null +++ b/deprecated/eo/app/gprop/gprop.cpp @@ -0,0 +1,171 @@ +//----------------------------------------------------------------------------- +// gprop +//----------------------------------------------------------------------------- + +#include // EXIT_SUCCESS EXIT_FAILURE +#include // exception +#include // cerr cout +#include // ifstream +#include // string +#include // all usefull eo stuff +#include "gprop.h" // Chrom eoChromInit eoChromMutation eoChromXover eoChromEvaluator + +using namespace std; + +//----------------------------------------------------------------------------- +// global variables +//----------------------------------------------------------------------------- + +unsigned in, out, hidden; +mlp::set train, validate, test; + +//----------------------------------------------------------------------------- +// parameters +//----------------------------------------------------------------------------- + +eoValueParam pop_size(10, "pop_size", "population size", 'p'); +eoValueParam generations(10, "generations", "number of generation", 'g'); +eoValueParam mut_rate(0.25, "mut_rate", "mutation rate", 'm'); +eoValueParam xover_rate(0.25, "xover_rate", "default crossover rate", 'x'); +eoValueParam file("", "file", "common start of patterns filenames *.trn *.val and *.tst", 'f'); +eoValueParam hiddenp(0, "hidden", "number of neurons in hidden layer", 'd'); + +//----------------------------------------------------------------------------- +// auxiliar functions +//----------------------------------------------------------------------------- + +void arg(int argc, char** argv); +void load_file(mlp::set& s1, const string& s2); +void ga(); + +//----------------------------------------------------------------------------- +// main +//----------------------------------------------------------------------------- + +int main(int argc, char** argv) +{ + try + { + arg(argc, argv); + ga(); + } + catch (exception& e) + { + cerr << argv[0] << ": " << e.what() << endl; + exit(EXIT_FAILURE); + } + + return 0; +} + +//----------------------------------------------------------------------------- +// implementation +//----------------------------------------------------------------------------- + +void arg(int argc, char** argv) +{ + eoParser parser(argc, argv); + + parser.processParam(pop_size, "genetic operators"); + parser.processParam(generations, "genetic operators"); + parser.processParam(mut_rate, "genetic operators"); + parser.processParam(xover_rate, "genetic operators"); + parser.processParam(file, "files"); + parser.processParam(hiddenp, "genetic operators"); + + if (parser.userNeedsHelp()) + { + parser.printHelp(cout); + exit(EXIT_SUCCESS); + } + + load_file(train, "trn"); + load_file(validate, "val"); + load_file(test, "tst"); + + phenotype::trn_max = train.size(); + phenotype::val_max = validate.size(); + phenotype::tst_max = test.size(); + + in = train.front().input.size(); + out = train.front().output.size(); + gprop_use_datasets(&train, &validate, &test); + hidden = hiddenp.value(); +} + +//----------------------------------------------------------------------------- + +void load_file(mlp::set& set, const string& ext) +{ + string filename = file.value(); filename += "." + ext; + + ifstream ifs(filename.c_str()); + if (!ifs) + { + cerr << "can't open file \"" << filename << "\"" << endl; + exit(EXIT_FAILURE); + } + + ifs >> set; + + if (set.size() == 0) + { + cerr << filename << " data file is empty!"; + exit(EXIT_FAILURE); + } +} + +//----------------------------------------------------------------------------- + +void ga() +{ + // create population + eoInitChrom init; + eoPop pop(pop_size.value(), init); + + // evaluate population + eoEvalFuncPtr evaluator(eoChromEvaluator); + apply(evaluator, pop); + + // selector + eoStochTournamentSelect select; + + // genetic operators + eoChromMutation mutation; + eoChromXover xover; + + // stop condition + eoGenContinue continuator1(generations.value()); + phenotype p; p.val_ok = validate.size() - 1; p.mse_error = 0; + eoFitContinue continuator2(p); + eoCombinedContinue continuator(continuator1, continuator2); + + // checkpoint + eoCheckPoint checkpoint(continuator); + + // monitor + eoStdoutMonitor monitor; + checkpoint.add(monitor); + + // statistics + eoBestFitnessStat stats; + checkpoint.add(stats); + monitor.add(stats); + + // genetic algorithm + eoSGA sga(select, + xover, xover_rate.value(), + mutation, mut_rate.value(), + evaluator, + checkpoint); + + sga(pop); + + cout << "best: " << *max_element(pop.begin(), pop.end()) << endl; +} + +//----------------------------------------------------------------------------- + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/app/gprop/gprop.h b/deprecated/eo/app/gprop/gprop.h new file mode 100644 index 000000000..db67c1885 --- /dev/null +++ b/deprecated/eo/app/gprop/gprop.h @@ -0,0 +1,239 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// gprop.h +// (c) GeNeura Team 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + + +#ifndef gprop_h +#define gprop_h + +//----------------------------------------------------------------------------- + +#include // istream ostream +#include // setprecision +#include // string +#include // EO +#include // eoMonOp eoQuadraticOp +#include // eoInit +#include // normal_generator +#include "mlp.h" // mlp::net mlp::set +#include "qp.h" // qp::set +#include "mse.h" // mse::error + +//----------------------------------------------------------------------------- +// phenotype +//----------------------------------------------------------------------------- + +struct phenotype +{ + int trn_ok, val_ok, tst_ok; + double mse_error; + + static int trn_max, val_max, tst_max; + + friend bool operator<(const phenotype& a, const phenotype& b) + { + return (a.val_ok < b.val_ok) || ((!(b.val_ok < a.val_ok)) && (b.mse_error < a.mse_error)); + } + + friend bool operator==(const phenotype& a, const phenotype& b) + { + return (a.val_ok == b.val_ok) && (b.mse_error == a.mse_error); + } + + friend bool operator>=(const phenotype& a, const phenotype& b) + { + return !(a < b); + } + + friend bool operator>(const phenotype& a, const phenotype& b) + { + return (!(a == b)) && (!(a < b)); + } + + + + friend std::ostream& operator<<(std::ostream& os, const phenotype& p) + { + return os << p.trn_ok << "/" << p.trn_max << " " + << p.val_ok << "/" << p.val_max << " " + << p.tst_ok << "/" << p.tst_max << " " + << p.mse_error; + } + + friend std::istream& operator>>(std::istream& is, phenotype& p) + { + return is; // complete me + } +}; + + +int phenotype::trn_max = 0, phenotype::val_max = 0, phenotype::tst_max = 0; + +//----------------------------------------------------------------------------- +// genotype +//----------------------------------------------------------------------------- +#ifndef GPROP_GENOTYPE +#define GPROP_GENOTYPE mlp::net +#endif + +typedef GPROP_GENOTYPE genotype; + +//----------------------------------------------------------------------------- +// Chrom +//----------------------------------------------------------------------------- + +extern unsigned in, out, hidden; + +class Chrom: public EO, public genotype +{ +public: + Chrom(): genotype(in, out, std::vector(hidden < 1 ? 0 : 1, hidden)) {} + + std::string className() const { return "Chrom"; } + + void printOn (std::ostream& os) const + { + os << std::setprecision(3) << static_cast(*this) << " \t" + << fitness(); + // os << fitness(); + } + + void readFrom (std::istream& is) + { + invalidate(); // complete me + } +}; + +//----------------------------------------------------------------------------- +// eoChromInit +//----------------------------------------------------------------------------- + +class eoInitChrom: public eoInit +{ +public: + void operator()(Chrom& chrom) + { + chrom.reset(); + chrom.invalidate(); + } +}; + +//----------------------------------------------------------------------------- +// global variables +//----------------------------------------------------------------------------- + +mlp::set *trn_set = 0, *val_set = 0, *tst_set = 0; + +void gprop_use_datasets(mlp::set *trn, mlp::set *val, mlp::set *tst) { + trn_set = trn; + val_set = val; + tst_set = tst; +} + +void ensure_datasets_initialized() { + if (!trn_set) { + std::cerr << "trn_set is not initialized. Must call gprop_use_datasets before training\n"; + std::cerr.flush(); + abort(); + } +} + +//----------------------------------------------------------------------------- +// eoChromMutation +//----------------------------------------------------------------------------- + +class eoChromMutation: public eoMonOp +{ +public: + bool operator()(Chrom& chrom) + { + mse::net tmp(chrom); + tmp.train(*trn_set, 10, 0, 0.001); + return true; + } +}; + +//----------------------------------------------------------------------------- +// eoChromXover +//----------------------------------------------------------------------------- + +class eoChromXover: public eoQuadOp +{ +public: + bool operator()(Chrom& chrom1, Chrom& chrom2) + { + chrom1.normalize(); + chrom2.desaturate(); + + mse::net tmp1(chrom1), tmp2(chrom2); + ensure_datasets_initialized(); + tmp1.train(*trn_set, 100, 0, 0.001); + tmp2.train(*trn_set, 100, 0, 0.001); + + return true; + } +}; + +//----------------------------------------------------------------------------- +// eoChromEvaluator +//----------------------------------------------------------------------------- + +int correct(const mlp::net& net, const mlp::set& set) +{ + int sum = 0; + + for (mlp::set::const_iterator s = set.begin(); s != set.end(); ++s) + { + 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 (partial == s->output.size()) + ++sum; + } + + return sum; +} + +phenotype eoChromEvaluator(const Chrom& chrom) +{ + phenotype p; + ensure_datasets_initialized(); + p.trn_ok = correct(chrom, *trn_set); + p.val_ok = correct(chrom, *val_set); + p.tst_ok = correct(chrom, *tst_set); + p.mse_error = mse::error(chrom, *val_set); + + return p; +} + +//----------------------------------------------------------------------------- + +#endif // gprop_h + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/app/gprop/l2.h b/deprecated/eo/app/gprop/l2.h new file mode 100644 index 000000000..cff4a67c3 --- /dev/null +++ b/deprecated/eo/app/gprop/l2.h @@ -0,0 +1,140 @@ +//----------------------------------------------------------------------------- +// l2.h +//----------------------------------------------------------------------------- + +#ifndef l2_h +#define l2_h + +//----------------------------------------------------------------------------- + +#include // log +#include // neuron layer net set + +//----------------------------------------------------------------------------- + +namespace l2 +{ + //--------------------------------------------------------------------------- + // useful typedefs + //--------------------------------------------------------------------------- + + using qp::real; + using qp::vector; + using qp::max_real; + using qp::min_real; + using qp::set; + using qp::neuron; + using qp::layer; + + //--------------------------------------------------------------------------- + // error + //--------------------------------------------------------------------------- + + real error(const mlp::net& net, const set& ts) + { + real error_ = 0.0; + + 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) + + (1.0 - target) * log(1.0 - value + min_real); + } + } + + return error_; + } + + //------------------------------------------------------------------------- + // 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) + { + reverse_iterator current_layer = rbegin(); + reverse_iterator backward_layer = current_layer + 1; + real error_ = 0; + + // output layer + for (unsigned j = 0; j < current_layer->size(); ++j) + { + neuron& n = (*current_layer)[j]; + real out = output[j]; + 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 + n.dxo += n.delta * input; + 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) + + (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; + + 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]; + sum += nf.delta * (nf.n->weight[j] + nf.dweight1[j]); + } + 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 + for (unsigned k = 0; k < n.dxo.size(); ++k) + n.dxo[k] += n.delta * (*backward_layer)[k].out; + } + } + + return error_; + } + }; + + //--------------------------------------------------------------------------- + +} // namespace l2 + +//----------------------------------------------------------------------------- + +#endif // l2_h + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/app/gprop/mlp.h b/deprecated/eo/app/gprop/mlp.h new file mode 100644 index 000000000..c7c612826 --- /dev/null +++ b/deprecated/eo/app/gprop/mlp.h @@ -0,0 +1,513 @@ +//----------------------------------------------------------------------------- +// mlp.h +//----------------------------------------------------------------------------- + +#ifndef mlp_h +#define mlp_h + +#include // generate +#include // exp +#include +#include +#include +#include // invalid_argument +#include +#include +#include // eoRng +#include // normal_generator +#include // * + +#include +#include + +#ifdef HAVE_LIBYAML_CPP +#include +#endif // HAVE_LIBYAML_CPP + + +namespace mlp +{ + using namespace std; + + typedef double real; + typedef std::vector vector; +} + + +namespace std { + ostream& operator<<(ostream& os, const mlp::vector& v) + { + ostream_iterator oi(os, " "); + copy(v.begin(), v.end(), oi); + return os; + } + + istream& operator>>(istream& is, mlp::vector& v) + { + for (mlp::vector::iterator vi = v.begin() ; vi != v.end() ; vi++) { + is >> *vi; + } + return is; + } +} + +namespace mlp +{ + using namespace std; + + //--------------------------------------------------------------------------- + // useful typedefs + //--------------------------------------------------------------------------- + + + const real max_real = std::numeric_limits::max(); + const real min_real = std::numeric_limits::min(); + + + //--------------------------------------------------------------------------- + // sigmoid + //--------------------------------------------------------------------------- + + real sigmoid(const real& x) + { + return 1.0 / (1.0 + exp(-x)); + } + + + //--------------------------------------------------------------------------- + // neuron + //--------------------------------------------------------------------------- + + struct neuron + { + real bias; + vector weight; + + neuron(const unsigned& num_inputs = 0): weight(num_inputs) {} + + void reset() + { + normal_generator rnd(1.0); + bias = rnd(); + generate(weight.begin(), weight.end(), rnd); + } + + real operator()(const vector& input) const + { + return sigmoid(bias + weight * input); + } + + unsigned length() const { return weight.size() + 1; } + + void normalize() + { + real n = sqrt(bias * bias + weight * weight); + bias /= n; + weight /= n; + } + + void desaturate() + { + bias = -5.0 + 10.0 / (1.0 + exp(bias / -5.0)); + + for (vector::iterator w = weight.begin(); w != weight.end(); ++w) + *w = -5.0 + 10.0 / (1.0 + exp(*w / -5.0)); + } + + void perturb_num(double &num, double magnitude) { + double scale = max(num, 0.05) * magnitude; + double perturbation = scale * (rng.uniform() - 0.5); + num += perturbation; + } + + void perturb(double magnitude = 0.3, double probability = 1.0) + { + + for (vector::iterator w = weight.begin(); w != weight.end(); ++w) + if ( probability >= 1.0 || rng.uniform() < probability) + perturb_num(*w, magnitude); + if ( probability >= 1.0 || rng.uniform() < probability) + perturb_num(bias, magnitude); + } + + #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; + } + void load_yaml(const YAML::Node& node) { + YAML_LOAD_MEMBER(node, bias); + YAML_LOAD_MEMBER(node, weight); + } + #endif + }; +} + +namespace std { + + ostream& operator<<(ostream& os, const mlp::neuron& n) + { + return os << n.bias << " " << n.weight; + } + + istream& operator>>(istream& is, mlp::neuron& n) + { + return is >> n.bias >> n.weight; + } + + +} + + +namespace mlp { + + //--------------------------------------------------------------------------- + // layer + //--------------------------------------------------------------------------- + + class layer: public std::vector + { + public: + layer(const unsigned& num_inputs = 0, const unsigned& num_neurons = 0): + std::vector(num_neurons, neuron(num_inputs)) {} + + void reset() + { + normal_generator rnd(1.0); + for(iterator n = begin(); n != end(); ++n) + n->reset(); + } + + vector operator()(const vector& input) const + { + vector output(size()); + + for(unsigned i = 0; i < output.size(); ++i) + output[i] = (*this)[i](input); + + return output; + } + + unsigned length() const { return front().length() * size(); } + + void normalize() + { + for(iterator n = begin(); n != end(); ++n) + n->normalize(); + } + + void desaturate() + { + for(iterator n = begin(); n != end(); ++n) + n->desaturate(); + } + + void perturb(double magnitude = 0.3, double probability = 1.0) + { + for(iterator n = begin(); n != end(); ++n) + n->perturb(); + } + #ifdef HAVE_LIBYAML_CPP + friend ostream& operator<<(YAML::Emitter& e, const layer &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; + } + #endif + + }; + +} + +namespace std { + + ostream& operator<<(ostream& os, const mlp::layer& l) + { + ostream_iterator oi(os, " "); + copy(l.begin(), l.end(), oi); + return os; + } + + istream& operator>>(istream& is, mlp::layer& l) + { + for (mlp::layer::iterator li = l.begin() ; li != l.end() ; li++) { + is >> *li; + } + return is; + } + +} + +namespace mlp { + + + //--------------------------------------------------------------------------- + // net + //--------------------------------------------------------------------------- + + class net: public std::vector + #ifdef HAVE_LIBYAML_CPP + , public YAML::Serializable + #endif + { + public: + net(const unsigned& num_inputs = 0, + const unsigned& num_outputs = 0, + const std::vector& hidden = std::vector()) + { + init(num_inputs,num_outputs,hidden); + } + + + net(istream &is) { + load(is); + } + #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; + } + + void load_members(const YAML::Node& node) { + std::vector* me_as_layer_vector = this; + node["layers"] >> *me_as_layer_vector; + } + #endif // HAVE_LIBYAML_CPP + + /** Virtual destructor */ + virtual ~net() {}; + + void load(istream &is) { + unsigned num_inputs; + unsigned num_outputs; + unsigned num_hidden_layers; + + is >> num_inputs >> num_outputs >> num_hidden_layers; + + std::vector layer_sizes; + for (unsigned i=0; i> layer_size; + layer_sizes.push_back(layer_size); + } + 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++) { + is >> *l; + } + do { is >> c; } while (c == ' ' && !is.eof()); + assert(c == '>'); + } + + void init( unsigned num_inputs, + unsigned num_outputs, + const std::vector& hidden ) { + clear(); + switch(hidden.size()) + { + case 0: + push_back(layer(num_inputs, num_outputs)); + break; + default: + push_back(layer(num_inputs, hidden.front())); + for (unsigned i = 0; i < hidden.size() - 1; ++i) + push_back(layer(hidden[i], hidden[i + 1])); + push_back(layer(hidden.back(), num_outputs)); + break; + } + } + + void reset() + { + normal_generator rnd(1.0); + for(iterator l = begin(); l != end(); ++l) + l->reset(); + } + + virtual vector operator()(const vector& input) const ; + + unsigned winner(const vector& input) const + { + vector tmp = (*this)(input); + return (max_element(tmp.begin(), tmp.end()) - tmp.begin()); + } + + void save(ostream &os) const { + // 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) + os << l->size() << " "; + os << "\n"; + os << "< "; + for(const_iterator l = begin(); l != end(); ++l) + os << *l << " "; + os << ">\n"; + } + + + unsigned num_inputs() const { return front().front().length() - 1; } + unsigned num_outputs() const { return back().size(); } + unsigned num_hidden_layers() const { + signed s = (signed) size() -1; + return (s<0) ? 0 : s ; + } + + + unsigned length() + { + unsigned sum = 0; + + for(iterator l = begin(); l != end(); ++l) + sum += l->length(); + + return sum; + } + + void normalize() + { + for(iterator l = begin(); l != end(); ++l) + l->normalize(); + } + + void desaturate() + { + for(iterator l = begin(); l != end(); ++l) + l->desaturate(); + } + + void perturb(double magnitude = 0.3, double probability = 1.0) + { + for(iterator l = begin(); l != end(); ++l) + l->perturb(); + } + }; + +#ifndef NO_MLP_VIRTUALS + vector net::operator()(const vector& input) const + { + vector tmp = input; + + for(const_iterator l = begin(); l != end(); ++l) + tmp = (*l)(tmp); + + return tmp; + } +#endif + + + //--------------------------------------------------------------------------- + // sample + //--------------------------------------------------------------------------- + + struct sample + { + vector input, output; + + sample(unsigned input_size = 0, unsigned output_size = 0): + input(input_size), output(output_size) {} + }; + + istream& operator>>(istream& is, sample& s) + { + return is >> s.input >> s.output; + } + + ostream& operator<<(ostream& os, const sample& s) + { + return os << s.input << " " << s.output; + } + + + //--------------------------------------------------------------------------- + // set + //--------------------------------------------------------------------------- + + class set: public std::vector + { + public: + set(unsigned input_size = 0, unsigned output_size = 0, + unsigned num_samples = 0): + std::vector(num_samples, sample(input_size, output_size)) {} + + set(istream& is) : std::vector(0, sample(0, 0)) { + clear(); + load(is); + } + + void load(istream &is) { + unsigned input_size, output_size; + is >> input_size >> output_size; + sample samp(input_size, output_size);; + while (is >> samp) { push_back(samp); } + } + + void save(ostream &os) const { + os << front().input.size() << " " << front().output.size() << endl; + copy(begin(), end(), ostream_iterator(os,"\n")); + } + }; + + ostream& operator<<(ostream& os, const set& s) + { + os << "<" << endl; + for (unsigned i = 0; i < s.size(); ++i) + os << s[i] << endl; + return os << ">"; + } + + //--------------------------------------------------------------------------- + // euclidean_distance + //--------------------------------------------------------------------------- + + real euclidean_distance(const net& n1, const net& n2) + { + real sum = 0; + + for(net::const_reverse_iterator l1 = n1.rbegin(), l2 = n2.rbegin(); + l1 != n1.rend() && l2 != n2.rend(); ++l1, ++l2) + for(layer::const_iterator n1 = l1->begin(), n2 = l2->begin(); + n1 != l1->end() && n2 != l2->end(); ++n1, ++n2) + { + real b = n1->bias - n2->bias; + vector w = n1->weight - n2->weight; + sum += b * b + w * w; + } + /* + #include + std::ofstream file("dist.stat", ios::app); + file << sqrt(sum) << endl; + */ + return sqrt(sum); + } + + //--------------------------------------------------------------------------- + +} // namespace mlp + + + +#endif // mlp_h + + +// Local Variables: +// mode:C++ +// c-file-style: "Stroustrup" +// End: diff --git a/deprecated/eo/app/gprop/mse.h b/deprecated/eo/app/gprop/mse.h new file mode 100644 index 000000000..3fb62fa09 --- /dev/null +++ b/deprecated/eo/app/gprop/mse.h @@ -0,0 +1,140 @@ +//----------------------------------------------------------------------------- +// mse.h +//----------------------------------------------------------------------------- + +#ifndef mse_h +#define mse_h + +//----------------------------------------------------------------------------- + +#include // neuron layer net set + +//----------------------------------------------------------------------------- + +namespace mse +{ + //--------------------------------------------------------------------------- + // useful typedefs + //--------------------------------------------------------------------------- + + using qp::real; + using qp::vector; + using qp::max_real; + using qp::min_real; + using qp::set; + using qp::neuron; + using qp::layer; + + //--------------------------------------------------------------------------- + // error + //--------------------------------------------------------------------------- + + real error(const mlp::net& net, const set& ts) + { + real error_ = 0.0; + + 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]; + error_ += diff * diff; + } + } + + return error_ / ts.size(); + } + //------------------------------------------------------------------------- + // 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) + { + reverse_iterator current_layer = rbegin(); + reverse_iterator backward_layer = current_layer + 1; + real error_ = 0; + + // output layer + for (unsigned j = 0; j < current_layer->size(); ++j) + { + neuron& n = (*current_layer)[j]; + + real diff = output[j] - n.out; + n.ndelta += n.delta = diff * n.out * (1.0 - n.out); + + if (size() == 1) // monolayer + n.dxo += n.delta * input; + 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]; + sum += nf.delta * (nf.n->weight[j] + nf.dweight1[j]); + } + + 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 + for (unsigned k = 0; k < n.dxo.size(); ++k) + n.dxo[k] += n.delta * (*backward_layer)[k].out; + } + } + + return error_; + } + }; + + //--------------------------------------------------------------------------- + +} // namespace mse + +//----------------------------------------------------------------------------- + +#endif // mse_h + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/app/gprop/qp.h b/deprecated/eo/app/gprop/qp.h new file mode 100644 index 000000000..fb9836759 --- /dev/null +++ b/deprecated/eo/app/gprop/qp.h @@ -0,0 +1,251 @@ +//----------------------------------------------------------------------------- +// qp.h +//----------------------------------------------------------------------------- + +#ifndef qp_h +#define qp_h + +//----------------------------------------------------------------------------- + +#include // istream ostream +#include // fill +#include // vector +#include // uniform_generator +#include // neuron layer net + +//----------------------------------------------------------------------------- + +namespace qp +{ + //--------------------------------------------------------------------------- + // useful typedefs + //--------------------------------------------------------------------------- + + using mlp::real; + using mlp::vector; + + using mlp::max_real; + using mlp::min_real; + + using mlp::set; + + //--------------------------------------------------------------------------- + // useful constants + //--------------------------------------------------------------------------- + + const real eta_default = 0.5; + const real eta_floor = 0.0001; + const real alpha_default = 0.9; + const real lambda_default = 0.5; + const real lambda0 = 0.1; + 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), + 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 + + (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 << " " + << n.dweight1 << " " << n.dweight2 << " " << n.dxo; + } + + + //--------------------------------------------------------------------------- + // layer + //--------------------------------------------------------------------------- + + class layer: public std::vector + { + public: + layer(mlp::layer& l)//: std::vector(l.begin(), l.end()) {} + { + for (mlp::layer::iterator n = l.begin(); n != l.end(); ++n) + push_back(neuron(*n)); + } + + void reset() + { + for(iterator n = begin(); n != end(); ++n) + n->reset(); + } + + vector operator()(const vector& input) + { + vector output(size()); + + for(unsigned i = 0; i < output.size(); ++i) + output[i] = (*this)[i](input); + + return output; + } + }; + + + //--------------------------------------------------------------------------- + // net + //--------------------------------------------------------------------------- + + class net: public std::vector + { + public: + net(mlp::net& n) //: std::vector(n.begin(), n.end()) { reset(); } + { + for (mlp::net::iterator l = n.begin(); l != n.end(); ++l) + push_back(*l); + } + + virtual ~net() {} + + void reset() + { + for(iterator l = begin(); l != end(); ++l) + l->reset(); + } + + real train(const set& ts, + unsigned epochs, + real target_error, + real tolerance, + 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); + weight_update(ts.size(), true, eta, momentum); + } + else + { + eta *= backtrack_step; + eta = std::max(eta, eta_floor); + momentum = eta * lambda; + weight_update(ts.size(), false, eta, momentum); + error_ = last_error; + } + } + + return error_; + } + + virtual real error(const set& ts) = 0; + + // protected: + void forward(vector input) + { + for (iterator l = begin(); l != end(); ++l) + { + vector tmp = (*l)(input); + input.swap(tmp); + } + } + + // private: + void init_delta() + { + for (iterator l = begin(); l != end(); ++l) + 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) + { + me += n->dxo * n->dxo; + 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)); + eta = std::max(eta, eta_floor); + lambda = lambda0 * me / mw; + momentum = eta * lambda; +#ifdef DEBUG + 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) + for (layer::iterator n = l->begin(); n != l->end(); ++n) + { + n->ndelta /= size; + n->dxo /= size; + if (fire) + { + n->n->weight += n->dweight1; + n->dweight2 = n->dweight1; + n->n->bias += n->dbias1; + n->dbias2 = n->dbias1; + } + n->dweight1 = eta * n->dxo + momentum * n->dweight2; + n->dbias1 = eta * n->ndelta + momentum * n->dbias2; + } + } + }; + + //--------------------------------------------------------------------------- + +} // namespace qp + +//----------------------------------------------------------------------------- + +#endif // qp_h + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/app/gprop/vecop.h b/deprecated/eo/app/gprop/vecop.h new file mode 100644 index 000000000..dd4a23a8a --- /dev/null +++ b/deprecated/eo/app/gprop/vecop.h @@ -0,0 +1,213 @@ +//----------------------------------------------------------------------------- +// vecop.h +//----------------------------------------------------------------------------- + +#ifndef VECOP_H +#define VECOP_H + +//----------------------------------------------------------------------------- + +#include // ostream istream +#include // vector +#include // plus minus multiplies divides +#include // inner_product + +//----------------------------------------------------------------------------- +// std::vector + std::vector +//----------------------------------------------------------------------------- + +template std::vector operator+(const std::vector& v1, const std::vector& v2) +{ + std::vector tmp = v1; + std::transform(tmp.begin(), tmp.end(), v2.begin(), tmp.begin(), std::plus()); + return tmp; +} + +template std::vector operator-(const std::vector& v1, const std::vector& v2) +{ + std::vector tmp = v1; + std::transform(tmp.begin(), tmp.end(), v2.begin(), tmp.begin(), std::minus()); + return tmp; +} + +template T operator*(const std::vector& v1, const std::vector& v2) +{ + return inner_product(v1.begin(), v1.end(), v2.begin(), static_cast(0)); +} + +template T operator/(const std::vector& v1, const std::vector& v2) +{ + return inner_product(v1.begin(), v1.end(), v2.begin(), static_cast(0), + std::plus(), std::divides()); +} + +//----------------------------------------------------------------------------- +// std::vector += std::vector +//----------------------------------------------------------------------------- + +template std::vector& operator+=(std::vector& v1, const std::vector& v2) +{ + std::transform(v1.begin(), v1.end(), v2.begin(), v1.begin(), std::plus()); + return v1; +} + +template std::vector& operator-=(std::vector& v1, const std::vector& v2) +{ + std::transform(v1.begin(), v1.end(), v2.begin(), v1.begin(), std::minus()); + return v1; +} + +//----------------------------------------------------------------------------- +// std::vector + number +//----------------------------------------------------------------------------- + +template std::vector operator+(const std::vector& a, const B& b) +{ + std::vector tmp = a; + std::transform(tmp.begin(), tmp.end(), tmp.begin(), std::bind2nd(std::plus(), b)); + return tmp; +} + +template std::vector operator-(const std::vector& a, const B& b) +{ + std::vector tmp = a; + std::transform(tmp.begin(), tmp.end(), tmp.begin(), std::bind2nd(std::minus(), b)); + return tmp; +} + +template std::vector operator*(const std::vector& a, const B& b) +{ + std::vector tmp = a; + std::transform(tmp.begin(), tmp.end(), tmp.begin(), std::bind2nd(std::multiplies(), b)); + return tmp; +} + +template std::vector operator/(const std::vector& a, const B& b) +{ + std::vector tmp = a; + std::transform(tmp.begin(), tmp.end(), tmp.begin(), std::bind2nd(std::divides(), b)); + return tmp; +} + +//----------------------------------------------------------------------------- +// number + std::vector +//----------------------------------------------------------------------------- + +template std::vector operator+(const B& b, const std::vector& a) +{ + std::vector tmp = a; + std::transform(tmp.begin(), tmp.end(), tmp.begin(), std::bind2nd(std::plus(), b)); + return tmp; +} + +template std::vector operator-(const B& b, const std::vector& a) +{ + std::vector tmp(a.size(), b); + std::transform(tmp.begin(), tmp.end(), a.begin(), tmp.begin(), std::minus()); + return tmp; +} + +template std::vector operator*(const B& b, const std::vector& a) +{ + std::vector tmp = a; + std::transform(tmp.begin(), tmp.end(), tmp.begin(), bind2nd(std::multiplies(), b)); + return tmp; +} + +template std::vector operator/(const B& b, const std::vector& a) +{ + std::vector tmp(a.size(), b); + std::transform(tmp.begin(), tmp.end(), a.begin(), tmp.begin(), std::divides()); + return tmp; +} + +//----------------------------------------------------------------------------- +// std::vector += number +//----------------------------------------------------------------------------- + +template std::vector& operator+=(std::vector& a, const B& b) +{ + std::transform(a.begin(), a.end(), a.begin(), std::bind2nd(std::plus(), b)); + return a; +} + +template std::vector& operator-=(std::vector& a, const B& b) +{ + std::transform(a.begin(), a.end(), a.begin(), std::bind2nd(std::minus(), b)); + return a; +} + +template std::vector& operator*=(std::vector& a, const B& b) +{ + std::transform(a.begin(), a.end(), a.begin(), std::bind2nd(std::multiplies(), b)); + return a; +} + +template std::vector& operator/=(std::vector& a, const B& b) +{ + std::transform(a.begin(), a.end(), a.begin(), std::bind2nd(std::divides(), b)); + return a; +} + +//----------------------------------------------------------------------------- +// I/O +//----------------------------------------------------------------------------- + +template std::ostream& operator<<(std::ostream& os, const std::vector& v) +{ + os << '<'; + if (v.size()) + { + std::copy(v.begin(), v.end() - 1, std::ostream_iterator(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 != '<') + is.setstate(std::ios::failbit); + else + { + T t; + do { + is >> c; + if (is && c!= '>') + { + is.putback(c); + is >> t; + if (is) + v.push_back(t); + } + } while (is && c != '>'); + } + + return is; +} + +//----------------------------------------------------------------------------- +// euclidean_distance +//----------------------------------------------------------------------------- + +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]; + sum += tmp * tmp; + } + + return sqrt(sum); +} + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/app/gpsymreg/CMakeLists.txt b/deprecated/eo/app/gpsymreg/CMakeLists.txt new file mode 100644 index 000000000..1bb258678 --- /dev/null +++ b/deprecated/eo/app/gpsymreg/CMakeLists.txt @@ -0,0 +1,38 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Specify where CMake can find the libraries (mandatory: before 3) ) +###################################################################################### + +LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) + +###################################################################################### +### 3) Define your target(s): just an executable here +###################################################################################### + +SET (GPSYMREG_SOURCES main.cpp) + +# no matter what is the OS, hopefully +ADD_EXECUTABLE(gpsymreg ${GPSYMREG_SOURCES}) + +ADD_DEPENDENCIES(gpsymreg eo eoutils) + +###################################################################################### +### 4) Optionnal: define your target(s)'s version: no effect for windows +###################################################################################### + +SET(GPSYMREG_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(gpsymreg PROPERTIES VERSION "${GPSYMREG_VERSION}") + +###################################################################################### +### 5) Link the librairies for your target(s) +###################################################################################### + +TARGET_LINK_LIBRARIES(gpsymreg eo eoutils) + +###################################################################################### diff --git a/deprecated/eo/app/gpsymreg/fitness.h b/deprecated/eo/app/gpsymreg/fitness.h new file mode 100644 index 000000000..d4fdb5056 --- /dev/null +++ b/deprecated/eo/app/gpsymreg/fitness.h @@ -0,0 +1,227 @@ +/* + This library 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 + (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 +*/ + +#ifndef _FITNESS_FUNCTION_H +#define _FITNESS_FUNCTION_H + +#include +#include + +#include +#include "parameters.h" +#include "node.h" + +using namespace gp_parse_tree; +using namespace std; + + + +// the first fitness is the normal goal fitness +// the second fitness is the tree size (we prefer smaller trees) +// lets use names to define the different fitnesses +#define NORMAL 0 // Stepwise Adaptation of Weights Fitness +#define SMALLESTSIZE 1 // The size of the tree, we want to minimize this one -- statistics will tell us the smallest tree size + + +// Look: overloading the maximization without overhead (thing can be inlined) +class MinimizingFitnessTraits : public eoParetoFitnessTraits +{ + public : + static bool maximizing(int which) { return false;} // we want to minimize both fitnesses + static unsigned nObjectives() { return 2;} // the number of fitnesses } +}; + +// Lets define our MultiObjective FitnessType +typedef eoParetoFitness FitnessType; + + +// John Koza's sextic polynomial (our example problem) + +double sextic_polynomial(double x) +{ + double result=0; + result = pow(x,6) - (2*pow(x,4)) + pow(x,2); + return result; +} + +// we use the following functions for the basic math functions + +double _plus(double arg1, double arg2) +{ + return arg1 + arg2; +} + +double _minus(double arg1, double arg2) +{ + return arg1 - arg2; +} + +double _multiplies(double arg1, double arg2) +{ + return arg1 * arg2; +} + +// the function for a protected divide looks a little bit different +double _divides(double arg1, double arg2) +{ + if (arg2 ==0) + return 0; + else + return arg1 / arg2; +} + +double _negate(double arg1) +{ + return -arg1; +} + + + +// now let's define our tree nodes + +void init(vector &initSequence) +{ + + // we have only one variable (X) + Operation varX( (unsigned int) 0, string("X") ); + + + // the main binary operators + Operation OpPLUS ( _plus, string("+")); + Operation OpMINUS( _minus,string("-")); + Operation OpMULTIPLIES(_multiplies,string("*")); + // We can use a protected divide function. + Operation OpDIVIDE( _divides, string("/") ); + + + // Now the functions as binary functions + Operation PLUS( string("plus"), _plus); + Operation MINUS( string("minus"), _minus); + Operation MULTIPLIES( string("multiply"), _multiplies); + Operation DIVIDE( string("divide"), _divides); + + + // and some unary functions + Operation NEGATE( _negate,string("-")); + Operation SIN ( sin, string("sin")); + Operation COS ( cos, string("cos")); + + // Now we are ready to add the possible nodes to our initSequence (which is used by the eoDepthInitializer) + + // so lets start with our variable + initSequence.push_back(varX); + + // followed by the constants 2, 4, 6 + for(unsigned int i=2; i <= 6; i+=2) + { + char text[255]; + sprintf(text, "%i", i); + Operation op(i*1.0, text); + initSequence.push_back( op ); + // and we add the variable again (so we have get lots of variables); + initSequence.push_back( varX ); + } + + // next we add the unary functions + + initSequence.push_back( NEGATE ); + initSequence.push_back( SIN ); + initSequence.push_back( COS ); + + // and the binary functions + initSequence.push_back( PLUS); + initSequence.push_back( MINUS ); + initSequence.push_back( MULTIPLIES ); + initSequence.push_back( DIVIDE ); + + // and the binary operators + initSequence.push_back( OpPLUS); + initSequence.push_back( OpMINUS ); + + initSequence.push_back( OpMULTIPLIES ); + initSequence.push_back( OpDIVIDE ); + + +} + + + +class RegFitness: public eoEvalFunc< eoParseTree > +{ + public: + + typedef eoParseTree EoType; + + void operator()(EoType &_eo) + { + + vector< double > input(1); // the input variable(s) + double output(0.); + double target; + FitnessType fitness; + + + float x=0; + double fit=0; + for(x=-1; x <= 1; x+=0.1) + { + input[0] = x; + target = sextic_polynomial(x); + _eo.apply(output,input); + + fit += pow(target - output, 2); + } + + fitness[NORMAL] = fit; + + fitness[SMALLESTSIZE] = _eo.size() / (1.0*parameter.MaxSize); + _eo.fitness(fitness); + + if (fitness[NORMAL] < best[NORMAL]) + { + best[NORMAL] = fitness[NORMAL]; + tree=""; + _eo.apply(tree); + } + + } + + + + RegFitness(eoValueParam &_generationCounter, vector< Node > &initSequence, Parameters &_parameter) : eoEvalFunc(), generationCounter(_generationCounter), parameter(_parameter) + { + init(initSequence); + best[NORMAL] = 1000; + tree= "not found"; + }; + + ~RegFitness() + { + cerr << "Best Fitness= " << best[NORMAL] << endl; + cerr << tree << endl; + }; + + private: + eoValueParam &generationCounter; // so we know the current generation + Parameters ¶meter; // the parameters + FitnessType best; // the best found fitness + string tree; +}; + +#endif diff --git a/deprecated/eo/app/gpsymreg/main.cpp b/deprecated/eo/app/gpsymreg/main.cpp new file mode 100644 index 000000000..6d3318ff6 --- /dev/null +++ b/deprecated/eo/app/gpsymreg/main.cpp @@ -0,0 +1,337 @@ +/* + + 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 + + (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 + +*/ + + + +#ifdef _MSC_VER + +#pragma warning(disable:4786) + +#endif + + + +#ifdef HAVE_CONFIG_H + +#include + +#endif + + + +#include + +#include "gp/eoParseTree.h" + +#include "eo" + + + +using namespace gp_parse_tree; + +using namespace std; + + + +//----------------------------------------------------------------------------- + + + +#include "node.h" + +#include "parameters.h" + +#include "fitness.h" + + + + + +// TYPE DECLARATIONS FOR GP + + + + + +typedef eoParseTree EoType; + +typedef eoPop Pop; + + + +//----------------------------------------------------------------------------- + + + +int main(int argc, char *argv[]) + +{ + + + + // the vector containing the possible nodes + + vector initSequence; + + + + // initialise parameters + + Parameters parameter(argc, argv); + + + + // set the randomseed + + rng.reseed(parameter.randomseed); + + + + // Create a generation counter + + eoValueParam generationCounter(0, "Gen."); + + + + // Create an incrementor (sub-class of eoUpdater). Note that the + + // parameter's value is passed by reference, + + // so every time the incrementer is updated (every generation), + + // the data in generationCounter will change. + + eoIncrementor increment(generationCounter.value()); + + + + + + // create an instantiation of the fitness/evaluation function + + // it initializes the initSequence vector + + // the parameters are passed on as well + + RegFitness eval(generationCounter, initSequence, parameter); + + + + // Depth Initializor, set for Ramped Half and Half Initialization + + eoParseTreeDepthInit initializer(parameter.InitMaxDepth, initSequence, true, true); + + + + // create the initial population + + Pop pop(parameter.population_size, initializer); + + + + // and evaluate the individuals + + apply(eval, pop); + + + + generationCounter.value()++; // set the generationCounter to 1 + + + + + + // define X-OVER + + + + eoSubtreeXOver xover(parameter.MaxSize); + + + + // define MUTATION + + eoBranchMutation mutation(initializer, parameter.MaxSize); + +// eoExpansionMutation mutation(initializer, parameter.MaxSize); + +// eoCollapseSubtreeMutation mutation(initializer, parameter.MaxSize); + +// eoPointMutation mutation(initSequence); + +// eoHoistMutation mutation; + + + + // The operators are encapsulated into an eoTRansform object, + + // that performs sequentially crossover and mutation + + eoSGATransform transform(xover, parameter.xover_rate, mutation, parameter.mutation_rate); + + + + // The robust tournament selection + + // in our case 5-tournament selection + + eoDetTournamentSelect selectOne(parameter.tournamentsize); + + // is now encapsulated in a eoSelectMany + + eoSelectMany select(selectOne, parameter.offspring_size, eo_is_an_integer); + + + + // and the generational replacement + + //eoGenerationalReplacement replace; + + // or the SteadtState replacment + + //eoSSGAWorseReplacement replace; + + // or comma selection + + eoCommaReplacement replace; + + + + // Terminators + + eoGenContinue term(parameter.nGenerations); + + + + eoCheckPoint checkPoint(term); + + + + // STATISTICS + + eoAverageStat avg; + + eoBestFitnessStat best; + + + + + + // Add it to the checkpoint, + + // so the counter is updated (here, incremented) every generation + + checkPoint.add(increment); + + checkPoint.add(avg); + + checkPoint.add(best); + + + +#ifdef HAVE_GNUPLOT + + eoGnuplot1DMonitor gnuplotmonitor("gnuplotBestStats"); + + gnuplotmonitor.add(generationCounter); + + gnuplotmonitor.add(best); + + // we need to add a empty string variable if we want to seed the second fitness value + + eoValueParam dummy1("", "Smallest Tree Size"); + + gnuplotmonitor.add(dummy1); + + + + eoGnuplot1DMonitor gnuplotAvgmonitor("gnuplotAvgStats"); + + gnuplotAvgmonitor.add(generationCounter); + + gnuplotAvgmonitor.add(avg); + + // we need to add a empty string variable if we want to seed the second fitness value + + eoValueParam dummy2("", "Average Tree Size"); + + gnuplotAvgmonitor.add(dummy2); + + + + checkPoint.add(gnuplotmonitor); + + checkPoint.add(gnuplotAvgmonitor); + +#endif + + // GP Generation + + eoEasyEA gp(checkPoint, eval, select, transform, replace); + + + + cout << "Initialization done" << endl; + + + + + + try + + { + + gp(pop); + + } + + catch (exception& e) + + { + + cout << "exception: " << e.what() << endl;; + + exit(EXIT_FAILURE); + + } + + + + return 1; + + + +} diff --git a/deprecated/eo/app/gpsymreg/node.h b/deprecated/eo/app/gpsymreg/node.h new file mode 100644 index 000000000..02b0279b1 --- /dev/null +++ b/deprecated/eo/app/gpsymreg/node.h @@ -0,0 +1,248 @@ +/* + This library 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 + (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 +*/ + +#ifndef _NODE_H +#define _NODE_H + + + +#include +#include +#include // for finite(double) function + +using namespace gp_parse_tree; +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 + (and possible second) child branch and use them as input variables for + the remaining second (or third) child branch. +*/ + + +typedef enum {Variable, UFunction, BFunction, BOperator, Const} Type; + +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; + BinaryFunction bFunction; + 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) + { + case Variable: id = _op.id; break; + case UFunction: uFunction = _op.uFunction; break; + case BFunction: bFunction = _op.bFunction; break; + case BOperator: bFunction = _op.bFunction; break; + case Const: constant = _op.constant; break; + } + type = _op.type; + label = _op.label; + }; + virtual ~Operation(){}; + +}; + + +class Node +{ + private: + Operation op; + + public: + + Node(void): op(Operation()){}; + Node(Operation &_op) : op(_op){}; + virtual ~Node(void) {} + + int arity(void) const + { + switch(op.type) + { + case Variable: return 0; + case UFunction: return 1; + case BFunction: return 2; + case BOperator: return 2; + case Const: 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); + break; + case BFunction: + case BOperator: args[0].apply(result0, var); + args[1].apply(result1, var); + result = op.bFunction(result0,result1); + break; + case Const: result = op.constant; + break; + + } + + } + + template + void operator()(string& result, Children args) const + { + + string subtree0; + string subtree1; + string subtree2; + + switch(op.type) + { + + case Variable: + case Const: result += op.label; + break; + + case UFunction: result += op.label; + result += "("; + args[0].apply(subtree0); + result += subtree0; + result += ")"; + break; + case BFunction: result += op.label; + result += "("; + args[0].apply(subtree0); + result += subtree0; + result += ","; + args[1].apply(subtree1); + result += subtree1; + result += ")"; + break; + case BOperator: result += "("; + args[0].apply(subtree0); + result += subtree0; + result += op.label; + args[1].apply(subtree1); + result += subtree1; + result += ")"; + break; + default: result += "ERROR in Node::operator(string,...) \n"; break; + } + } + + Operation getOp(void) const {return op;} + +}; + + + + + + + + + + + +//----------------------------------------------------------- +// saving, loading LETS LEAVE IT OUT FOR NOW + + + +std::ostream& operator<<(std::ostream& os, const Node& eot) +{ + Operation op(eot.getOp()); + + os << (eot.getOp()).label; + return os; +} + + +// we can't load because we are using function pointers. Instead we prevent a compiler warning by calling the arity() function. +std::istream& operator>>(std::istream& is, Node& eot) +{ + eot.arity(); + return is; +} + + + +#endif diff --git a/deprecated/eo/app/gpsymreg/parameters.h b/deprecated/eo/app/gpsymreg/parameters.h new file mode 100644 index 000000000..ed9a02577 --- /dev/null +++ b/deprecated/eo/app/gpsymreg/parameters.h @@ -0,0 +1,112 @@ +/* + This library 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 + (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 +*/ + +#ifndef _PARAMETERS_FUNCTION_H +#define _PARAMETERS_FUNCTION_H + +#include +#include + +using namespace gp_parse_tree; +using namespace std; + +struct Parameters{ + unsigned int nGenerations; // -G + unsigned population_size; // -P + unsigned offspring_size; // -O + unsigned int MaxSize; // -S + unsigned int InitMaxDepth; // -D + unsigned int randomseed; // -R + double xover_rate; // -x + double mutation_rate; // -y + unsigned int tournamentsize; // -t + + + 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); + } + + }; + + ~Parameters(){}; +}; + +#endif diff --git a/deprecated/eo/app/mastermind/CMakeLists.txt b/deprecated/eo/app/mastermind/CMakeLists.txt new file mode 100644 index 000000000..6fde0887c --- /dev/null +++ b/deprecated/eo/app/mastermind/CMakeLists.txt @@ -0,0 +1,38 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Specify where CMake can find the libraries (mandatory: before 3) ) +###################################################################################### + +LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) + +###################################################################################### +### 3) Define your target(s): just an executable here +###################################################################################### + +SET (MASTERMIND_SOURCES mastermind.cpp) + +# no matter what is the OS, hopefully +ADD_EXECUTABLE(mastermind ${MASTERMIND_SOURCES}) + +ADD_DEPENDENCIES(mastermind eo eoutils) + +###################################################################################### +### 4) Optionnal: define your target(s)'s version: no effect for windows +###################################################################################### + +SET(MASTERMIND_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(mastermind PROPERTIES VERSION "${MASTERMIND_VERSION}") + +###################################################################################### +### 5) Link the librairies for your target(s) +###################################################################################### + +TARGET_LINK_LIBRARIES(mastermind eo eoutils) + +###################################################################################### diff --git a/deprecated/eo/app/mastermind/mastermind.cpp b/deprecated/eo/app/mastermind/mastermind.cpp new file mode 100644 index 000000000..c17889913 --- /dev/null +++ b/deprecated/eo/app/mastermind/mastermind.cpp @@ -0,0 +1,138 @@ +//----------------------------------------------------------------------------- +// mastermind +//----------------------------------------------------------------------------- + +#include // EXIT_SUCCESS EXIT_FAILURE +#include // exception +#include // cerr cout +#include // ifstream +#include // string +#include // all usefull eo stuff + +#include "mastermind.h" // Chrom eoChromInit eoChromMutation eoChromXover eoChromEvaluator + +using namespace std; + +//----------------------------------------------------------------------------- +// global variables +//----------------------------------------------------------------------------- + +unsigned in, out, hidden; + +//----------------------------------------------------------------------------- +// parameters +//----------------------------------------------------------------------------- + +eoValueParam pop_size(16, "pop_size", "population size", 'p'); +eoValueParam generations(100, "generations", "number of generation", 'g'); +eoValueParam mut_rate(0.1, "mut_rate", "mutation rate", 'm'); +eoValueParam xover_rate(0.5, "xover_rate", "default crossover rate", 'x'); +eoValueParam col_p(default_colors, "colors", "number of colors", 'c'); +eoValueParam len_p(default_length, "legth", "solution legth", 'l'); +eoValueParam sol_p(default_solution, "solution", "problem solution", 's'); + +//----------------------------------------------------------------------------- +// auxiliar functions +//----------------------------------------------------------------------------- + +void arg(int argc, char** argv); +void ga(); + +//----------------------------------------------------------------------------- +// main +//----------------------------------------------------------------------------- + +int main(int argc, char** argv) +{ + try + { + arg(argc, argv); + ga(); + } + catch (exception& e) + { + cerr << argv[0] << ": " << e.what() << endl; + exit(EXIT_FAILURE); + } + + return 0; +} + +//----------------------------------------------------------------------------- +// implementation +//----------------------------------------------------------------------------- + +void arg(int argc, char** argv) +{ + eoParser parser(argc, argv); + + parser.processParam(pop_size, "genetic operators"); + parser.processParam(generations, "genetic operators"); + parser.processParam(mut_rate, "genetic operators"); + parser.processParam(xover_rate, "genetic operators"); + parser.processParam(col_p, "problem"); + parser.processParam(len_p, "problem"); + parser.processParam(sol_p, "problem"); + + if (parser.userNeedsHelp()) + { + parser.printHelp(cout); + exit(EXIT_SUCCESS); + } + + init_eoChromEvaluator(col_p.value(), len_p.value(), sol_p.value()); +} + +//----------------------------------------------------------------------------- + +void ga() +{ + // create population + eoInitChrom init; + eoPop pop(pop_size.value(), init); + + // evaluate population + eoEvalFuncPtr evaluator(eoChromEvaluator); + apply(evaluator, pop); + + // selector + eoProportionalSelect select(pop); + + // genetic operators + eoChromMutation mutation; + eoChromXover xover; + + // stop condition + eoGenContinue continuator1(generations.value()); + eoFitContinue continuator2(solution.fitness()); + eoCombinedContinue continuator(continuator1, continuator2); + + // checkpoint + eoCheckPoint checkpoint(continuator); + + // monitor + eoStdoutMonitor monitor; + checkpoint.add(monitor); + + // statistics + eoBestFitnessStat stats; + checkpoint.add(stats); + monitor.add(stats); + + // genetic algorithm + eoSGA sga(select, + xover, xover_rate.value(), + mutation, mut_rate.value(), + evaluator, + checkpoint); + sga(pop); + + cout << "solution = " << solution << endl + << "best = " << *max_element(pop.begin(), pop.end()) << endl; +} + +//----------------------------------------------------------------------------- + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/app/mastermind/mastermind.h b/deprecated/eo/app/mastermind/mastermind.h new file mode 100644 index 000000000..13066036e --- /dev/null +++ b/deprecated/eo/app/mastermind/mastermind.h @@ -0,0 +1,199 @@ +//----------------------------------------------------------------------------- +// mastermind.h +//----------------------------------------------------------------------------- + +#ifndef mastermind_h +#define mastermind_h + +//----------------------------------------------------------------------------- + +#include // exit EXIT_FAILURE +#include // eoVectorLength +#include // eoMonOp eoQuadraticOp +#include // eoInit +#include "utils/rnd_generators.h" // uniform_generator + +//----------------------------------------------------------------------------- +// phenotype +//----------------------------------------------------------------------------- + +typedef float phenotype; + +//----------------------------------------------------------------------------- +// genotype +//----------------------------------------------------------------------------- + +typedef std::vector genotype; + +//----------------------------------------------------------------------------- +// Chrom +//----------------------------------------------------------------------------- + +typedef eoVector Chrom; + +//----------------------------------------------------------------------------- +// eoChromEvaluator +//----------------------------------------------------------------------------- + +// const unsigned points_per_black = 3, points_per_white = 1; +Chrom solution; + +phenotype eoChromEvaluator(const Chrom& chrom) +{ + Chrom tmp = solution; + unsigned black = 0, white = 0; + + // look for blacks + for (unsigned i = 0; i < chrom.size(); ++i) + if (chrom[i] == tmp[i]) + { + ++black; + tmp[i] = -1; + } + + // look for whites + for (unsigned i = 0; i < chrom.size(); ++i) + for (unsigned j = 0; j < tmp.size(); ++j) + if (chrom[i] == tmp[j]) + { + ++white; + tmp[j] = -1; + break; + } + + // return black * points_per_black + white * points_per_white; + return black * chrom.size() + white; +} + +const unsigned default_length = 8; +const unsigned default_colors = 8; +const std::string default_solution = "01234567"; + + +unsigned num_colors; + +void init_eoChromEvaluator(const unsigned& c, const unsigned& l, std::string s) +{ + num_colors = c; + + // check consistency between parameters + if (s != default_solution) + { + // check length + if (l != default_length && s.size() != l) + { + std::cerr << "solution length != length" << std::endl; + exit(EXIT_FAILURE); + } + + // check number of colors + if ((c != default_colors) && (c < unsigned(*max_element(s.begin(), s.end()) - '0'))) + { + std::cerr << "too high color number found!" << std::endl; + exit(EXIT_FAILURE); + } + } + else + if (l != default_length || c != default_colors ) + // generate a random solution + if(num_colors <= 10) + { + uniform_generator color('0', static_cast('0' + c)); + s.resize(l); + generate(s.begin(), s.end(), color); + } + + // put the solution parameter on the solution chromosome + if (num_colors <= 10) + { + solution.resize(s.size()); + for (unsigned i = 0; i < solution.size(); ++i) + solution[i] = s[i] - '0'; + } + else + { + solution.resize(l); + uniform_generator color(0, num_colors); + generate(solution.begin(), solution.end(), color); + } + + solution.fitness(eoChromEvaluator(solution)); +} + +//----------------------------------------------------------------------------- +// eoChromInit +//----------------------------------------------------------------------------- + +class eoInitChrom: public eoInit +{ +public: + void operator()(Chrom& chrom) + { + uniform_generator color(0, num_colors); + chrom.resize(solution.size()); + generate(chrom.begin(), chrom.end(), color); + chrom.invalidate(); + } +}; + +//----------------------------------------------------------------------------- +// eoChromMutation +//----------------------------------------------------------------------------- + +class eoChromMutation: public eoMonOp +{ + // many operators in one :( + bool operator()(Chrom& chrom) + { + uniform_generator what(0, 2); + uniform_generator position(0, chrom.size()); + + switch(what()) + { + case 0: + { + // mutation + uniform_generator color(0, num_colors); + chrom[position()] = color(); + break; + } + case 1: + { + // transposition + std::swap(chrom[position()], chrom[position()]); + break; + } + default: + { + std::cerr << "unknown operator!" << std::endl; + exit(EXIT_FAILURE); + break; + } + } + + return true; + } +}; + +//----------------------------------------------------------------------------- +// eoChromXover +//----------------------------------------------------------------------------- + +class eoChromXover: public eoQuadOp +{ +public: + bool operator()(Chrom& chrom1, Chrom& chrom2) + { + uniform_generator position(0, chrom1.size()); + swap_ranges(chrom1.begin(), chrom1.begin() + position(), chrom2.begin()); + return true; + } +}; + +//----------------------------------------------------------------------------- + +#endif // mastermind_h + +// Local Variables: +// mode:C++ +// End: diff --git a/deprecated/eo/cmake/modules/FindEO.cmake b/deprecated/eo/cmake/modules/FindEO.cmake new file mode 100644 index 000000000..8bf3ac130 --- /dev/null +++ b/deprecated/eo/cmake/modules/FindEO.cmake @@ -0,0 +1,100 @@ +# File: FindEO.cmake +# CMAKE commands to actually use the EO library +# Version: 0.0.1 +# +# The following variables are filled out: +# - EO_INCLUDE_DIRS +# - EO_LIBRARY_DIRS +# - EO_LIBRARIES +# - EO_FOUND +# +# Here are the components: +# - PyEO +# - es +# - ga +# - cma +# +# You can use FIND_PACKAGE( EO COMPONENTS ... ) to enable one or several components. +# + +# Default enabled components +SET(EO_LIBRARIES_TO_FIND eo eoutils) + +# Use FIND_PACKAGE( EO COMPONENTS ... ) to enable modules +IF(EO_FIND_COMPONENTS) + FOREACH(component ${EO_FIND_COMPONENTS}) + STRING(TOUPPER ${component} _COMPONENT) + SET(EO_USE_${_COMPONENT} 1) + ENDFOREACH(component) + + # To make sure we don't use PyEO, ES, GA, CMA when not in COMPONENTS + IF(NOT EO_USE_PYEO) + SET(EO_DONT_USE_PYEO 1) + ELSE(NOT EO_USE_PYEO) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} PyEO) + ENDIF(NOT EO_USE_PYEO) + + IF(NOT EO_USE_ES) + SET(EO_DONT_USE_ES 1) + ELSE(NOT EO_USE_ES) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} es) + ENDIF(NOT EO_USE_ES) + + IF(NOT EO_USE_GA) + SET(EO_DONT_USE_GA 1) + ELSE(NOT EO_USE_GA) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} ga) + ENDIF(NOT EO_USE_GA) + + IF(NOT EO_USE_CMA) + SET(EO_DONT_USE_CMA 1) + ELSE(NOT EO_USE_CMA) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} cma) + ENDIF(NOT EO_USE_CMA) +ENDIF(EO_FIND_COMPONENTS) + +IF(NOT EO_INCLUDE_DIRS) + FIND_PATH( + EO_INCLUDE_DIRS + EO.h + PATHS + /usr/include/eo + /usr/local/include/eo + ) +ENDIF(NOT EO_INCLUDE_DIRS) + +IF(NOT EO_LIBRARY_DIRS) + FIND_PATH( + EO_LIBRARY_DIRS + libeo.a + PATHS + /usr/lib + /usr/local/lib + ) +ENDIF(NOT EO_LIBRARY_DIRS) + +IF(NOT EO_LIBRARIES) + SET(EO_LIBRARIES) + FOREACH(component ${EO_LIBRARIES_TO_FIND}) + FIND_LIBRARY( + EO_${component}_LIBRARY + NAMES ${component} + PATHS + /usr/lib + /usr/local/lib + ) + IF(EO_${component}_LIBRARY) + SET(EO_LIBRARIES ${EO_LIBRARIES} ${EO_${component}_LIBRARY}) + ELSE(EO_${component}_LIBRARY) + MESSAGE(FATAL_ERROR "${component} component not found.") + ENDIF(EO_${component}_LIBRARY) + ENDFOREACH(component) +ENDIF(NOT EO_LIBRARIES) + +IF(EO_INCLUDE_DIRS AND EO_LIBRARY_DIRS AND EO_LIBRARIES) + SET(EO_FOUND 1) + MARK_AS_ADVANCED(EO_FOUND) + MARK_AS_ADVANCED(EO_INCLUDE_DIRS) + MARK_AS_ADVANCED(EO_LIBRARY_DIRS) + MARK_AS_ADVANCED(EO_LIBRARIES) +ENDIF(EO_INCLUDE_DIRS AND EO_LIBRARY_DIRS AND EO_LIBRARIES) diff --git a/deprecated/eo/config.h.cmake b/deprecated/eo/config.h.cmake new file mode 100644 index 000000000..24568be10 --- /dev/null +++ b/deprecated/eo/config.h.cmake @@ -0,0 +1,73 @@ +/* config.h.cmake */ + +/* Debugging flag */ +#cmakedefine DEBUG + +/* gnuplot graphical display */ +#cmakedefine HAVE_GNUPLOT + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_INTTYPES_H + +/* Define to 1 if you have the `m' library (-lm). */ +#cmakedefine HAVE_LIBM + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_MEMORY_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDLIB_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRING_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TYPES_H + +/* Define to 1 if the system has the type `uint32_t'. */ +#cmakedefine HAVE_UINT32_T + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UNISTD_H + +/* no debugging */ +#cmakedefine NDEBUG + +/* no debugging */ +#cmakedefine NODEBUG + +/* Name of package */ +#cmakedefine PACKAGE "eo" + +/* Define to the address where bug reports for this package should be sent. */ +#cmakedefine PACKAGE_BUGREPORT "@PACKAGE_BUGREPORT@" + +/* Define to the full name of this package. */ +#cmakedefine PACKAGE_NAME "@PACKAGE_NAME@" + +/* Define to the full name and version of this package. */ +#cmakedefine PACKAGE_STRING "@PACKAGE_STRING@" + +/* Define to the one symbol short name of this package. */ +#cmakedefine PACKAGE_TARNAME "@PACKAGE_TARNAME@" + +/* Define to the version of this package. */ +#cmakedefine PACKAGE_VERSION "@PACKAGE_VERSION@" + +/* Define to 1 if you have the ANSI C header files. */ +#cmakedefine STDC_HEADERS + +/* Version number of package */ +#cmakedefine "@VERSION VERSION@" + +/* Define to `unsigned int' if does not define. */ +#cmakedefine size_t diff --git a/deprecated/eo/contrib/MGE/ChangeLog b/deprecated/eo/contrib/MGE/ChangeLog new file mode 100644 index 000000000..9e42e0b02 --- /dev/null +++ b/deprecated/eo/contrib/MGE/ChangeLog @@ -0,0 +1,11 @@ +2006-12-02 Jochen Kpper + + * contrib/MGE/VirusOp.h (VirusShiftMutation::operator()): Fix test for + i>1. This makes t-MGE1bit pass on x86_64 using GCC. + + + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/deprecated/eo/contrib/MGE/VirusOp.h b/deprecated/eo/contrib/MGE/VirusOp.h new file mode 100644 index 000000000..54d7b4aaf --- /dev/null +++ b/deprecated/eo/contrib/MGE/VirusOp.h @@ -0,0 +1,145 @@ +/* + ViruOp.h + (c) GeNeura Team 2001, 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: eodev-main@lists.sourceforge.net + old contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr +*/ + +#ifndef VirusOp_h +#define VirusOp_h + +//----------------------------------------------------------------------------- + +#include // ostream, istream +#include // bind2nd +#include // std::string + +#include +#include "eoVirus.h" + +/** VirusBitFlip --> changes 1 bit +*/ + +template +class VirusBitFlip: public eoMonOp > { + public: + /// The class name. + virtual std::string className() const { return "VirusBitFlip"; }; + + /** Change one bit. + + @param chrom The cromosome which one bit is going to be changed. + */ + bool operator()(eoVirus& _chrom) { + unsigned i = eo::rng.random(_chrom.size()); + _chrom.virusBitSet(i, _chrom.virusBit(i) ? false : true ); + return true; + } +}; + + +template +class VirusMutation: public eoMonOp > { +public: + /// The class name. + virtual std::string className() const { return "VirusMutation"; }; + + /** Change one bit. + + @param chrom The cromosome which one bit is going to be changed. + */ + bool operator()(eoVirus& _chrom) { + // Search for virus bits + std::vector bitsSet; + for ( unsigned i = 0; i < _chrom.size(); i ++ ) { + if ( _chrom.virusBit(i) ) { + bitsSet.push_back( i ); + } + } + if ( !bitsSet.size() ) { + return false; + } + unsigned flipSite = eo::rng.random(bitsSet.size()); + unsigned flipValue = bitsSet[ flipSite ]; + _chrom[flipValue] = _chrom[flipValue] ? false : true; + return true; + } +}; + + +/// Works for 1-bit virus; shifts the one to the right or left +template +class VirusShiftMutation: public eoMonOp > +{ +public: + + /// Ctor + VirusShiftMutation( ) {}; + + /// The class name. + virtual std::string className() const { return "VirusShiftMutation"; }; + + /** Change one bit. + + @param chrom The cromosome which one bit is going to be changed. + */ + bool operator()(eoVirus& _chrom) { + // Search for virus bits + eoBooleanGenerator gen; + for ( unsigned i = 0; i < _chrom.size(); i ++ ) { + if ( _chrom.virusBit(i) ) { + if ( gen() ) { + if ( i + 1 < _chrom.size() ) { + _chrom.virusBitSet(i+1,true); + _chrom.virusBitSet(i, false); + } + } else { + if ( i > 1 ) { + _chrom.virusBitSet(i-1,true); + _chrom.virusBitSet(i, false); + } + } + } + } + return true; + } +}; + + +template +class VirusTransmission: public eoBinOp > { + public: + /// The class name. + virtual std::string className() const { return "VirusTransmission"; }; + + /** + * Change one bit. + * @param _chrom The "receptor" chromosome + * @param _chrom2 The "donor" chromosome + */ + bool operator()(eoVirus& _chrom,const eoVirus& _chrom2) { + // Search for virus bits + for ( unsigned i = 0; i < _chrom.size(); i ++ ) { + _chrom.virusBitSet(i, _chrom2.virusBit(i) ); + } + return true; + } +}; + +#endif //VirusOp_h diff --git a/deprecated/eo/contrib/MGE/eoInitVirus.h b/deprecated/eo/contrib/MGE/eoInitVirus.h new file mode 100644 index 000000000..f4cb53072 --- /dev/null +++ b/deprecated/eo/contrib/MGE/eoInitVirus.h @@ -0,0 +1,86 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoInit.h +// (c) Maarten Keijzer 2000, GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoInitVirus_H +#define _eoInitVirus_H + +#include + +#include +#include +#include +#include + +/** + Initializer for binary chromosome with MGE +*/ +template +class eoInitVirus: public eoInit< eoVirus > { +public: + + eoInitVirus(unsigned _combien, eoRndGenerator& _generator ) + : combien(_combien), generator(_generator) {} + + virtual void operator()( eoVirus& chrom) + { + chrom.resize(combien); + chrom.virResize(combien); + std::generate(chrom.begin(), chrom.end(), generator); + for ( unsigned i = 0; i < combien; i ++ ) { + chrom.virusBitSet(i, generator() ); + } + chrom.invalidate(); + } + +private : + unsigned combien; + /// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics + eoSTLF generator; +}; + +/// Inits the virus with one bit to the left set to one +template +class eoInitVirus1bit: public eoInit< eoVirus > { +public: + + eoInitVirus1bit(unsigned _combien, eoRndGenerator& _generator ) + : combien(_combien), generator(_generator) {} + + virtual void operator()( eoVirus& chrom) + { + chrom.resize(combien); + chrom.virResize(combien); + std::generate(chrom.begin(), chrom.end(), generator); + chrom.virusBitSet(0, true ); + chrom.invalidate(); + } + +private : + unsigned combien; + /// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics + eoSTLF generator; +}; +#endif diff --git a/deprecated/eo/contrib/MGE/eoVirus.h b/deprecated/eo/contrib/MGE/eoVirus.h new file mode 100644 index 000000000..a7c6aaeea --- /dev/null +++ b/deprecated/eo/contrib/MGE/eoVirus.h @@ -0,0 +1,130 @@ +/* eoVirus.h + +(c) GeNeura Team 2001, 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 version 2 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +USA + +Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr +*/ + + +#ifndef eoVirus_h +#define eoVirus_h + +#include +#include +#include +#include + +#include "ga/eoBit.h" + +/** +\defgroup bitstring + + Various functions for a bitstring representation +*/ + +/** Implementation of bitstring chromosome. + +@class eoBit eoBit.h ga/eoBit.h +@ingroup bitstring + +Based on STL's vector specialization. +*/ +template +class eoVirus : public eoBit +{ +public: + + using eoBit::begin; + using eoBit::end; + using eoBit::size; + + + /** (Default) Constructor + + @param size Size of the binary std::string. + */ + eoVirus(unsigned _size = 0, bool _value = false, bool _virValue = false): + eoBit(_size, _value), virus( _size, _virValue) {} + + /// My class name + virtual std::string className() const { + return "eoVirus"; + } + + /// Access to virus features + void virResize( unsigned _i ) { + virus.resize(_i ); + } + + /// Access to virus features + bool virusBit( unsigned _i ) const { + return virus[_i]; + } + + /// Change virus features + void virusBitSet( unsigned _i, bool _bit ) { + virus[_i ] = _bit; + } + + /** To print me on a stream. + + @param os The ostream. + */ + virtual void printOn(std::ostream& os) const { + EO::printOn(os); + os << ' '; + os << size() << ' '; + std::copy(begin(), end(), std::ostream_iterator(os)); + std::cout << std::endl; + std::copy(virus.begin(), virus.end(), std::ostream_iterator(os)); + } + + /** To read me from a stream. + + @param is The istream. + */ + virtual void readFrom(std::istream& is){ + eoBit::readFrom(is); + unsigned s; + is >> s; + std::string bits; + is >> bits; + if (is) { + virus.resize(bits.size()); + std::transform(bits.begin(), bits.end(), virus.begin(), + std::bind2nd(std::equal_to(), '1')); + } + } + + +private: + + std::vector virus; +}; + +//----------------------------------------------------------------------------- + +#endif //eoBit_h + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-style: "Stroustrup" +// End: diff --git a/deprecated/eo/contrib/boost/config.hpp b/deprecated/eo/contrib/boost/config.hpp new file mode 100644 index 000000000..176b4391c --- /dev/null +++ b/deprecated/eo/contrib/boost/config.hpp @@ -0,0 +1,59 @@ +// 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 +// 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. + +// Boost config.hpp policy and rationale documentation has been moved to +// http://www.boost.org/libs/config +// +// CAUTION: This file is intended to be completely stable - +// DO NOT MODIFY THIS FILE! +// + +#ifndef BOOST_CONFIG_HPP +#define BOOST_CONFIG_HPP + +// if we don't have a user config, then use the default location: +#if !defined(BOOST_USER_CONFIG) && !defined(BOOST_NO_USER_CONFIG) +# define BOOST_USER_CONFIG +#endif +// include it first: +#ifdef BOOST_USER_CONFIG +# include BOOST_USER_CONFIG +#endif + +// if we don't have a compiler config set, try and find one: +#if !defined(BOOST_COMPILER_CONFIG) && !defined(BOOST_NO_COMPILER_CONFIG) && !defined(BOOST_NO_CONFIG) +# include +#endif +// if we have a compiler config, include it now: +#ifdef BOOST_COMPILER_CONFIG +# include BOOST_COMPILER_CONFIG +#endif + +// if we don't have a std library config set, try and find one: +#if !defined(BOOST_STDLIB_CONFIG) && !defined(BOOST_NO_STDLIB_CONFIG) && !defined(BOOST_NO_CONFIG) +# include +#endif +// if we have a std library config, include it now: +#ifdef BOOST_STDLIB_CONFIG +# include BOOST_STDLIB_CONFIG +#endif + +// if we don't have a platform config set, try and find one: +#if !defined(BOOST_PLATFORM_CONFIG) && !defined(BOOST_NO_PLATFORM_CONFIG) && !defined(BOOST_NO_CONFIG) +# include +#endif +// if we have a platform config, include it now: +#ifdef BOOST_PLATFORM_CONFIG +# include BOOST_PLATFORM_CONFIG +#endif + +// get config suffix code: +#include + +#endif // BOOST_CONFIG_HPP diff --git a/deprecated/eo/contrib/boost/config/abi_prefix.hpp b/deprecated/eo/contrib/boost/config/abi_prefix.hpp new file mode 100644 index 000000000..a1d93a2a5 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/abi_prefix.hpp @@ -0,0 +1,20 @@ +// 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). + +#ifndef BOOST_CONFIG_ABI_PREFIX_HPP +# define BOOST_CONFIG_ABI_PREFIX_HPP +#else +# error double inclusion of header boost/config/abi_prefix.hpp is an error +#endif + +#include + +// this must occur after all other includes and before any code appears: +#ifdef BOOST_HAS_ABI_HEADERS +# include BOOST_ABI_PREFIX +#endif diff --git a/deprecated/eo/contrib/boost/config/abi_suffix.hpp b/deprecated/eo/contrib/boost/config/abi_suffix.hpp new file mode 100644 index 000000000..f9eb493d9 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/abi_suffix.hpp @@ -0,0 +1,21 @@ +// 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). + +// This header should be #included AFTER code that was preceded by a #include +// . + +#ifndef BOOST_CONFIG_ABI_PREFIX_HPP +# error Header boost/config/abi_prefix.hpp must only be used after boost/config/abi_prefix.hpp +#else +# undef BOOST_CONFIG_ABI_PREFIX_HPP +#endif + +// the suffix header occurs after all of our code: +#ifdef BOOST_HAS_ABI_HEADERS +# include BOOST_ABI_SUFFIX +#endif diff --git a/deprecated/eo/contrib/boost/config/auto_link.hpp b/deprecated/eo/contrib/boost/config/auto_link.hpp new file mode 100644 index 000000000..8a3c2e194 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/auto_link.hpp @@ -0,0 +1,344 @@ +// (C) 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) + + /* + * LOCATION: see http://www.boost.org for most recent version. + * FILE auto_link.hpp + * VERSION see + * DESCRIPTION: Automatic library inclusion for Borland/Microsoft compilers. + */ + +/************************************************************************* + +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. +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). +BOOST_AUTO_LINK_NOMANGLE: Specifies that we should link to BOOST_LIB_NAME.lib, + 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! + +Algorithm: +~~~~~~~~~~ + +Libraries for Borland and Microsoft compilers are automatically +selected here, the name of the lib is selected according to the following +formula: + +BOOST_LIB_PREFIX + + BOOST_LIB_NAME + + "_" + + BOOST_LIB_TOOLSET + + BOOST_LIB_THREAD_OPT + + BOOST_LIB_RT_OPT + "-" + + BOOST_LIB_VERSION + +These are defined as: + +BOOST_LIB_PREFIX: "lib" for static libraries otherwise "". + +BOOST_LIB_NAME: The base name of the lib ( for example boost_regex). + +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: + + 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. + + +***************************************************************************/ + +#ifdef __cplusplus +# ifndef BOOST_CONFIG_HPP +# include +# endif +#elif defined(_MSC_VER) && !defined(__MWERKS__) && !defined(__EDG_VERSION__) +// +// C language compatability (no, honestly) +// +# define BOOST_MSVC _MSC_VER +# define BOOST_STRINGIZE(X) BOOST_DO_STRINGIZE(X) +# define BOOST_DO_STRINGIZE(X) #X +#endif +// +// Only include what follows for known and supported compilers: +// +#if defined(BOOST_MSVC) \ + || defined(__BORLANDC__) \ + || (defined(__MWERKS__) && defined(_WIN32) && (__MWERKS__ >= 0x3000)) \ + || (defined(__ICL) && defined(_MSC_EXTENSIONS) && (_MSC_VER >= 1200)) + +#ifndef BOOST_VERSION_HPP +# include +#endif + +#ifndef BOOST_LIB_NAME +# error "Macro BOOST_LIB_NAME not set (internal error)" +#endif + +// +// error check: +// +#if defined(__MSVC_RUNTIME_CHECKS) && !defined(_DEBUG) +# pragma message("Using the /RTC option without specifying a debug runtime will lead to linker errors") +# pragma message("Hint: go to the code generation options and switch to one of the debugging runtimes") +# error "Incompatible build options" +#endif +// +// select toolset if not defined already: +// +#ifndef BOOST_LIB_TOOLSET +#if defined(BOOST_MSVC) && (BOOST_MSVC == 1200) + + // vc6: +# define BOOST_LIB_TOOLSET "vc6" + +#elif defined(BOOST_MSVC) && (BOOST_MSVC == 1300) + + // vc7: +# define BOOST_LIB_TOOLSET "vc7" + +#elif defined(BOOST_MSVC) && (BOOST_MSVC == 1310) + + // vc71: +# define BOOST_LIB_TOOLSET "vc71" + +#elif defined(BOOST_MSVC) && (BOOST_MSVC >= 1400) + + // vc80: +# define BOOST_LIB_TOOLSET "vc80" + +#elif defined(__BORLANDC__) + + // CBuilder 6: +# define BOOST_LIB_TOOLSET "bcb" + +#elif defined(__ICL) + + // Intel C++, no version number: +# define BOOST_LIB_TOOLSET "iw" + +#elif defined(__MWERKS__) && (__MWERKS__ <= 0x31FF ) + + // Metrowerks CodeWarrior 8.x +# define BOOST_LIB_TOOLSET "cw8" + +#elif defined(__MWERKS__) && (__MWERKS__ <= 0x32FF ) + + // Metrowerks CodeWarrior 9.x +# define BOOST_LIB_TOOLSET "cw9" + +#endif +#endif // BOOST_LIB_TOOLSET + +// +// select thread opt: +// +#if defined(_MT) || defined(__MT__) +# define BOOST_LIB_THREAD_OPT "-mt" +#else +# define BOOST_LIB_THREAD_OPT +#endif + +#if defined(_MSC_VER) || defined(__MWERKS__) + +# ifdef _DLL + +# if (defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) && (defined(_STLP_OWN_IOSTREAMS) || defined(__STL_OWN_IOSTREAMS)) + +# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG)) +# define BOOST_LIB_RT_OPT "-gdp" +# elif defined(_DEBUG) +# define BOOST_LIB_RT_OPT "-gdp" +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") +# error "Build options aren't compatible with pre-built libraries" +# else +# define BOOST_LIB_RT_OPT "-p" +# endif + +# elif defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) + +# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG)) +# define BOOST_LIB_RT_OPT "-gdpn" +# elif defined(_DEBUG) +# define BOOST_LIB_RT_OPT "-gdpn" +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") +# error "Build options aren't compatible with pre-built libraries" +# else +# define BOOST_LIB_RT_OPT "-pn" +# endif + +# else + +# if defined(_DEBUG) +# define BOOST_LIB_RT_OPT "-gd" +# else +# define BOOST_LIB_RT_OPT +# endif + +# endif + +# else + +# if (defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) && (defined(_STLP_OWN_IOSTREAMS) || defined(__STL_OWN_IOSTREAMS)) + +# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG)) +# define BOOST_LIB_RT_OPT "-sgdp" +# elif defined(_DEBUG) +# define BOOST_LIB_RT_OPT "-sgdp" +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") +# error "Build options aren't compatible with pre-built libraries" +# else +# define BOOST_LIB_RT_OPT "-sp" +# endif + +# elif defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) + +# if defined(_DEBUG) && (defined(__STL_DEBUG) || defined(_STLP_DEBUG)) +# define BOOST_LIB_RT_OPT "-sgdpn" +# elif defined(_DEBUG) +# define BOOST_LIB_RT_OPT "-sgdpn" +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") +# error "Build options aren't compatible with pre-built libraries" +# else +# define BOOST_LIB_RT_OPT "-spn" +# endif + +# else + +# if defined(_DEBUG) +# define BOOST_LIB_RT_OPT "-sgd" +# else +# define BOOST_LIB_RT_OPT "-s" +# endif + +# endif + +# endif + +#elif defined(__BORLANDC__) + +// +// figure out whether we want the debug builds or not: +// +#if __BORLANDC__ > 0x561 +#pragma defineonoption BOOST_BORLAND_DEBUG -v +#endif +// +// sanity check: +// +#if defined(__STL_DEBUG) || defined(_STLP_DEBUG) +#error "Pre-built versions of the Boost libraries are not provided in STLPort-debug form" +#endif + +# ifdef _RTLDLL + +# ifdef BOOST_BORLAND_DEBUG +# define BOOST_LIB_RT_OPT "-d" +# else +# define BOOST_LIB_RT_OPT +# endif + +# else + +# ifdef BOOST_BORLAND_DEBUG +# define BOOST_LIB_RT_OPT "-sd" +# else +# define BOOST_LIB_RT_OPT "-s" +# endif + +# endif + +#endif + +// +// select linkage opt: +// +#if (defined(_DLL) || defined(_RTLDLL)) && defined(BOOST_DYN_LINK) +# define BOOST_LIB_PREFIX +#elif defined(BOOST_DYN_LINK) +# error "Mixing a dll boost library with a static runtime is a really bad idea..." +#else +# define BOOST_LIB_PREFIX "lib" +#endif + +// +// now include the lib: +// +#if defined(BOOST_LIB_NAME) \ + && defined(BOOST_LIB_PREFIX) \ + && defined(BOOST_LIB_TOOLSET) \ + && defined(BOOST_LIB_THREAD_OPT) \ + && defined(BOOST_LIB_RT_OPT) \ + && defined(BOOST_LIB_VERSION) + +#ifndef BOOST_AUTO_LINK_NOMANGLE +# pragma comment(lib, BOOST_LIB_PREFIX BOOST_STRINGIZE(BOOST_LIB_NAME) "-" BOOST_LIB_TOOLSET BOOST_LIB_THREAD_OPT BOOST_LIB_RT_OPT "-" BOOST_LIB_VERSION ".lib") +# ifdef BOOST_LIB_DIAGNOSTIC +# pragma message ("Linking to lib file: " BOOST_LIB_PREFIX BOOST_STRINGIZE(BOOST_LIB_NAME) "-" BOOST_LIB_TOOLSET BOOST_LIB_THREAD_OPT BOOST_LIB_RT_OPT "-" BOOST_LIB_VERSION ".lib") +# endif +#else +# pragma comment(lib, BOOST_STRINGIZE(BOOST_LIB_NAME) ".lib") +# ifdef BOOST_LIB_DIAGNOSTIC +# pragma message ("Linking to lib file: " BOOST_STRINGIZE(BOOST_LIB_NAME) ".lib") +# endif +#endif + +#else +# error "some required macros where not defined (internal logic error)." +#endif + + +#endif // _MSC_VER || __BORLANDC__ + +// +// finally undef any macros we may have set: +// +#ifdef BOOST_LIB_PREFIX +# undef BOOST_LIB_PREFIX +#endif +#if defined(BOOST_LIB_NAME) +# undef BOOST_LIB_NAME +#endif +#if defined(BOOST_LIB_TOOLSET) +# undef BOOST_LIB_TOOLSET +#endif +#if defined(BOOST_LIB_THREAD_OPT) +# undef BOOST_LIB_THREAD_OPT +#endif +#if defined(BOOST_LIB_RT_OPT) +# undef BOOST_LIB_RT_OPT +#endif +#if defined(BOOST_LIB_LINK_OPT) +# undef BOOST_LIB_LINK_OPT +#endif +#if defined(BOOST_LIB_DEBUG_OPT) +# undef BOOST_LIB_DEBUG_OPT +#endif +#if defined(BOOST_DYN_LINK) +# undef BOOST_DYN_LINK +#endif +#if defined(BOOST_AUTO_LINK_NOMANGLE) +# undef BOOST_AUTO_LINK_NOMANGLE +#endif diff --git a/deprecated/eo/contrib/boost/config/compiler/borland.hpp b/deprecated/eo/contrib/boost/config/compiler/borland.hpp new file mode 100644 index 000000000..66769bec5 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/borland.hpp @@ -0,0 +1,175 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Aleksey Gurtovoy 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 for most recent version. + +// Borland C++ compiler setup: + +// Version 5.0 and below: +# if __BORLANDC__ <= 0x0550 +// Borland C++Builder 4 and 5: +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# if __BORLANDC__ == 0x0550 +// Borland C++Builder 5, command-line compiler 5.5: +# define BOOST_NO_OPERATORS_IN_NAMESPACE +# endif +# endif + +// Version 5.51 and below: +#if (__BORLANDC__ <= 0x551) +# define BOOST_NO_CV_SPECIALIZATIONS +# define BOOST_NO_CV_VOID_SPECIALIZATIONS +# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +# define BOOST_NO_DEDUCED_TYPENAME +// workaround for missing WCHAR_MAX/WCHAR_MIN: +#include +#include +#ifndef WCHAR_MAX +# define WCHAR_MAX 0xffff +#endif +#ifndef WCHAR_MIN +# define WCHAR_MIN 0 +#endif +#endif + +// Version 7.0 (Kylix) and below: +#if (__BORLANDC__ <= 0x570) +# define BOOST_NO_SFINAE +# define BOOST_NO_INTEGRAL_INT64_T +# define BOOST_NO_DEPENDENT_NESTED_DERIVATIONS +# define BOOST_NO_PRIVATE_IN_AGGREGATE +# define BOOST_NO_USING_TEMPLATE +# define BOOST_BCB_PARTIAL_SPECIALIZATION_BUG +# define BOOST_NO_TEMPLATE_TEMPLATES +# define BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS + // we shouldn't really need this - but too many things choke + // without it, this needs more investigation: +# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +# define BOOST_NO_IS_ABSTRACT +# ifdef NDEBUG + // fix broken so that Boost.test works: +# include +# undef strcmp +# endif + +// +// new bug in 5.61: +#if (__BORLANDC__ >= 0x561) && (__BORLANDC__ <= 0x570) + // this seems to be needed by the command line compiler, but not the IDE: +# define BOOST_NO_MEMBER_FUNCTION_SPECIALIZATIONS +#endif + +# ifdef _WIN32 +# define BOOST_NO_SWPRINTF +# elif defined(linux) || defined(__linux__) || defined(__linux) + // we should really be able to do without this + // but the wcs* functions aren't imported into std:: +# define BOOST_NO_STDC_NAMESPACE + // _CPPUNWIND doesn't get automatically set for some reason: +# pragma defineonoption BOOST_CPPUNWIND -x +# endif +#endif + +// +// Post 0x561 we have long long and stdint.h: +#if __BORLANDC__ >= 0x561 +# ifndef __NO_LONG_LONG +# define BOOST_HAS_LONG_LONG +# endif + // On non-Win32 platforms let the platform config figure this out: +# ifdef _WIN32 +# define BOOST_HAS_STDINT_H +# endif +#endif + +// Borland C++Builder 6 defaults to using STLPort. If _USE_OLD_RW_STL is +// defined, then we have 0x560 or greater with the Rogue Wave implementation +// which presumably has the std::DBL_MAX bug. +#if ((__BORLANDC__ >= 0x550) && (__BORLANDC__ < 0x560)) || defined(_USE_OLD_RW_STL) +// is partly broken, some macros define symbols that are really in +// namespace std, so you end up having to use illegal constructs like +// std::DBL_MAX, as a fix we'll just include float.h and have done with: +#include +#endif +// +// __int64: +// +#if (__BORLANDC__ >= 0x530) && !defined(__STRICT_ANSI__) +# define BOOST_HAS_MS_INT64 +#endif +// +// check for exception handling support: +// +#if !defined(_CPPUNWIND) && !defined(BOOST_CPPUNWIND) && !defined(__EXCEPTIONS) +# define BOOST_NO_EXCEPTIONS +#endif +// +// all versions have a : +// +#ifndef __STRICT_ANSI__ +# define BOOST_HAS_DIRENT_H +#endif +// +// all versions support __declspec: +// +#ifndef __STRICT_ANSI__ +# define BOOST_HAS_DECLSPEC +#endif +// +// ABI fixing headers: +// +#if __BORLANDC__ < 0x600 // not implemented for version 6 compiler yet +#ifndef BOOST_ABI_PREFIX +# define BOOST_ABI_PREFIX "boost/config/abi/borland_prefix.hpp" +#endif +#ifndef BOOST_ABI_SUFFIX +# define BOOST_ABI_SUFFIX "boost/config/abi/borland_suffix.hpp" +#endif +#endif +// +// Disable Win32 support in ANSI mode: +// +#if __BORLANDC__ < 0x600 +# pragma defineonoption BOOST_DISABLE_WIN32 -A +#elif defined(__STRICT_ANSI__) +# define BOOST_DISABLE_WIN32 +#endif +// +// MSVC compatibility mode does some nasty things: +// +#if defined(_MSC_VER) && (_MSC_VER <= 1200) +# define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP +# define BOOST_NO_VOID_RETURNS +#endif + +#define BOOST_COMPILER "Borland C++ version " BOOST_STRINGIZE(__BORLANDC__) + +// +// versions check: +// we don't support Borland prior to version 5.4: +#if __BORLANDC__ < 0x540 +# error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 1536 (Builder X preview): +#if (__BORLANDC__ > 1536) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# else +# pragma message( "Unknown compiler version - please run the configure tests and report the results") +# endif +#endif + + + + + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/comeau.hpp b/deprecated/eo/contrib/boost/config/compiler/comeau.hpp new file mode 100644 index 000000000..1b71008e0 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/comeau.hpp @@ -0,0 +1,59 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright Douglas Gregor 2001. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright Aleksey Gurtovoy 2003. +// (C) Copyright Beman Dawes 2003. +// (C) Copyright Jens Maurer 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) + +// See http://www.boost.org for most recent version. + +// Comeau C++ compiler setup: + +#include "boost/config/compiler/common_edg.hpp" + +#if (__COMO_VERSION__ <= 4245) + +# if defined(_MSC_VER) && _MSC_VER <= 1300 +# if _MSC_VER > 100 + // only set this in non-strict mode: +# define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP +# endif +# endif + +// Void returns don't work when emulating VC 6 (Peter Dimov) + +# if defined(_MSC_VER) && (_MSC_VER == 1200) +# define BOOST_NO_VOID_RETURNS +# endif + +#endif // version 4245 + +// +// enable __int64 support in VC emulation mode +// +# if defined(_MSC_VER) && (_MSC_VER >= 1200) +# define BOOST_HAS_MS_INT64 +# endif + +#define BOOST_COMPILER "Comeau compiler version " BOOST_STRINGIZE(__COMO_VERSION__) + +// +// versions check: +// we don't know Comeau prior to version 4245: +#if __COMO_VERSION__ < 4245 +# error "Compiler not configured - please reconfigure" +#endif +// +// last known and checked version is 4245: +#if (__COMO_VERSION__ > 4245) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/common_edg.hpp b/deprecated/eo/contrib/boost/config/compiler/common_edg.hpp new file mode 100644 index 000000000..0443be1ae --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/common_edg.hpp @@ -0,0 +1,62 @@ +// (C) Copyright John Maddock 2001 - 2002. +// (C) Copyright Jens Maurer 2001. +// (C) Copyright David Abrahams 2002. +// (C) Copyright Aleksey Gurtovoy 2002. +// (C) Copyright Markus Schoepflin 2005. +// 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 for most recent version. + +// +// Options common to all edg based compilers. +// +// This is included from within the individual compiler mini-configs. + +#ifndef __EDG_VERSION__ +# error This file requires that __EDG_VERSION__ be defined. +#endif + +#if (__EDG_VERSION__ <= 238) +# define BOOST_NO_INTEGRAL_INT64_T +# define BOOST_NO_SFINAE +#endif + +#if (__EDG_VERSION__ <= 240) +# define BOOST_NO_VOID_RETURNS +#endif + +#if (__EDG_VERSION__ <= 241) && !defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP) +# define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP +#endif + +#if (__EDG_VERSION__ <= 244) && !defined(BOOST_NO_TEMPLATE_TEMPLATES) +# define BOOST_NO_TEMPLATE_TEMPLATES +#endif + +#if (__EDG_VERSION__ < 300) && !defined(BOOST_NO_IS_ABSTRACT) +# define BOOST_NO_IS_ABSTRACT +#endif + +#if (__EDG_VERSION__ <= 303) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL) +# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +#endif + +// See also kai.hpp which checks a Kai-specific symbol for EH +# if !defined(__KCC) && !defined(__EXCEPTIONS) +# define BOOST_NO_EXCEPTIONS +# endif + +# if !defined(__NO_LONG_LONG) +# define BOOST_HAS_LONG_LONG +# endif + +#ifdef c_plusplus +// EDG has "long long" in non-strict mode +// However, some libraries have insufficient "long long" support +// #define BOOST_HAS_LONG_LONG +#endif + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/compaq_cxx.hpp b/deprecated/eo/contrib/boost/config/compiler/compaq_cxx.hpp new file mode 100644 index 000000000..a52e66a29 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/compaq_cxx.hpp @@ -0,0 +1,19 @@ +// (C) Copyright John Maddock 2001 - 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) + +// See http://www.boost.org for most recent version. + +// Dec Alpha True64 C++ compiler setup: + +#define BOOST_COMPILER "Dec Alpha True64 " BOOST_STRINGIZE(__DECCXX_VER) + +#include "boost/config/compiler/common_edg.hpp" + +// +// versions check: +// Nothing to do here? + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/digitalmars.hpp b/deprecated/eo/contrib/boost/config/compiler/digitalmars.hpp new file mode 100644 index 000000000..32fc71faf --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/digitalmars.hpp @@ -0,0 +1,49 @@ +// Copyright (C) Christof Meerwald 2003 +// Copyright (C) Dan Watkins 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) + +// Digital Mars C++ compiler setup: +#define BOOST_COMPILER __DMC_VERSION_STRING__ + +#define BOOST_HAS_LONG_LONG +#define BOOST_HAS_PRAGMA_ONCE + +#if (__DMC__ <= 0x833) +#define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +#define BOOST_NO_TEMPLATE_TEMPLATES +#define BOOST_NEEDS_TOKEN_PASTING_OP_FOR_TOKENS_JUXTAPOSING +#define BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS +#define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +#endif +#if (__DMC__ <= 0x840) || !defined(BOOST_STRICT_CONFIG) +#define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +#define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +#define BOOST_NO_OPERATORS_IN_NAMESPACE +#define BOOST_NO_UNREACHABLE_RETURN_DETECTION +#define BOOST_NO_SFINAE +#define BOOST_NO_USING_TEMPLATE +#define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +#endif + +// +// has macros: +#if (__DMC__ >= 0x840) +#define BOOST_HAS_DIRENT_H +#define BOOST_HAS_STDINT_H +#define BOOST_HAS_WINTHREADS +#endif + + +// check for exception handling support: +#ifndef _CPPUNWIND +# define BOOST_NO_EXCEPTIONS +#endif + +#if (__DMC__ < 0x840) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif diff --git a/deprecated/eo/contrib/boost/config/compiler/gcc.hpp b/deprecated/eo/contrib/boost/config/compiler/gcc.hpp new file mode 100644 index 000000000..d94b16b76 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/gcc.hpp @@ -0,0 +1,105 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001 - 2002. +// (C) Copyright Jens Maurer 2001 - 2002. +// (C) Copyright Beman Dawes 2001 - 2003. +// (C) Copyright Douglas Gregor 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Synge Todo 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) + +// See http://www.boost.org for most recent version. + +// GNU C++ compiler setup: + +#if __GNUC__ < 3 +# if __GNUC_MINOR__ == 91 + // egcs 1.1 won't parse shared_ptr.hpp without this: +# define BOOST_NO_AUTO_PTR +# endif +# if __GNUC_MINOR__ < 95 + // + // Prior to gcc 2.95 member templates only partly + // work - define BOOST_MSVC6_MEMBER_TEMPLATES + // instead since inline member templates mostly work. + // +# define BOOST_NO_MEMBER_TEMPLATES +# if __GNUC_MINOR__ >= 9 +# define BOOST_MSVC6_MEMBER_TEMPLATES +# endif +# endif + +# if __GNUC_MINOR__ < 96 +# define BOOST_NO_SFINAE +# endif + +# if __GNUC_MINOR__ <= 97 +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# define BOOST_NO_OPERATORS_IN_NAMESPACE +# endif + +# define BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE +# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +# define BOOST_NO_IS_ABSTRACT +#elif __GNUC__ == 3 + // + // gcc-3.x problems: + // + // Bug specific to gcc 3.1 and 3.2: + // +# if ((__GNUC_MINOR__ == 1) || (__GNUC_MINOR__ == 2)) +# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +# endif +# if __GNUC_MINOR__ < 4 +# define BOOST_NO_IS_ABSTRACT +# endif +#endif + +#ifndef __EXCEPTIONS +# define BOOST_NO_EXCEPTIONS +#endif + + +// +// Threading support: Turn this on unconditionally here (except for +// those platforms where we can know for sure). It will get turned off again +// later if no threading API is detected. +// +#if !defined(__MINGW32__) && !defined(linux) && !defined(__linux) && !defined(__linux__) +# define BOOST_HAS_THREADS +#endif + +// +// gcc has "long long" +// +#define BOOST_HAS_LONG_LONG + +// +// gcc implements the named return value optimization since version 3.1 +// +#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) +#define BOOST_HAS_NRVO +#endif + +#define BOOST_COMPILER "GNU C++ version " __VERSION__ + +// +// versions check: +// we don't know gcc prior to version 2.90: +#if (__GNUC__ == 2) && (__GNUC_MINOR__ < 90) +# error "Compiler not configured - please reconfigure" +#endif +// +// last known and checked version is 4.0 (Pre-release): +#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# else +// we don't emit warnings here anymore since there are no defect macros defined for +// gcc post 3.4, so any failures are gcc regressions... +//# warning "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + diff --git a/deprecated/eo/contrib/boost/config/compiler/greenhills.hpp b/deprecated/eo/contrib/boost/config/compiler/greenhills.hpp new file mode 100644 index 000000000..038b6b2b5 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/greenhills.hpp @@ -0,0 +1,28 @@ +// (C) Copyright John Maddock 2001. +// 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 for most recent version. + +// Greenhills C++ compiler setup: + +#define BOOST_COMPILER "Greenhills C++ version " BOOST_STRINGIZE(__ghs) + +#include "boost/config/compiler/common_edg.hpp" + +// +// versions check: +// we don't support Greenhills prior to version 0: +#if __ghs < 0 +# error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 0: +#if (__ghs > 0) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + diff --git a/deprecated/eo/contrib/boost/config/compiler/hp_acc.hpp b/deprecated/eo/contrib/boost/config/compiler/hp_acc.hpp new file mode 100644 index 000000000..3d05ba563 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/hp_acc.hpp @@ -0,0 +1,70 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001 - 2003. +// (C) Copyright Aleksey Gurtovoy 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Toon Knapen 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) + +// See http://www.boost.org for most recent version. + +// HP aCC C++ compiler setup: + +#if (__HP_aCC <= 33100) +# define BOOST_NO_INTEGRAL_INT64_T +# define BOOST_NO_OPERATORS_IN_NAMESPACE +# if !defined(_NAMESPACE_STD) +# define BOOST_NO_STD_LOCALE +# define BOOST_NO_STRINGSTREAM +# endif +#endif + +#if (__HP_aCC <= 33300) +// member templates are sufficiently broken that we disable them for now +# define BOOST_NO_MEMBER_TEMPLATES +# define BOOST_NO_DEPENDENT_NESTED_DERIVATIONS +# define BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE +#endif + +#if (__HP_aCC <= 33900) || !defined(BOOST_STRICT_CONFIG) +# define BOOST_NO_UNREACHABLE_RETURN_DETECTION +# define BOOST_NO_TEMPLATE_TEMPLATES +# define BOOST_NO_SWPRINTF +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +# define BOOST_NO_IS_ABSTRACT +// std lib config should set this one already: +//# define BOOST_NO_STD_ALLOCATOR +#endif + +// optional features rather than defects: +#if (__HP_aCC >= 33900) +# define BOOST_HAS_LONG_LONG +# define BOOST_HAS_PARTIAL_STD_ALLOCATOR +#endif + +#if (__HP_aCC >= 50000 ) && (__HP_aCC <= 53800 ) || (__HP_aCC < 31300 ) +# define BOOST_NO_MEMBER_TEMPLATE_KEYWORD +#endif + +#define BOOST_NO_MEMBER_TEMPLATE_FRIENDS + +#define BOOST_COMPILER "HP aCC version " BOOST_STRINGIZE(__HP_aCC) + +// +// versions check: +// we don't support HP aCC prior to version 0: +#if __HP_aCC < 33000 +# error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 0: +#if (__HP_aCC > 53800) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/intel.hpp b/deprecated/eo/contrib/boost/config/compiler/intel.hpp new file mode 100644 index 000000000..652557766 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/intel.hpp @@ -0,0 +1,146 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright Jens Maurer 2001. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Aleksey Gurtovoy 2002 - 2003. +// (C) Copyright Guillaume Melquiond 2002 - 2003. +// (C) Copyright Beman Dawes 2003. +// (C) Copyright Martin Wille 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) + +// See http://www.boost.org for most recent version. + +// Intel compiler setup: + +#include "boost/config/compiler/common_edg.hpp" + +#if defined(__INTEL_COMPILER) +# define BOOST_INTEL_CXX_VERSION __INTEL_COMPILER +#elif defined(__ICL) +# define BOOST_INTEL_CXX_VERSION __ICL +#elif defined(__ICC) +# define BOOST_INTEL_CXX_VERSION __ICC +#elif defined(__ECC) +# define BOOST_INTEL_CXX_VERSION __ECC +#endif + +#define BOOST_COMPILER "Intel C++ version " BOOST_STRINGIZE(BOOST_INTEL_CXX_VERSION) +#define BOOST_INTEL BOOST_INTEL_CXX_VERSION + +#if defined(_WIN32) || defined(_WIN64) +# define BOOST_INTEL_WIN BOOST_INTEL +#else +# define BOOST_INTEL_LINUX BOOST_INTEL +#endif + +#if (BOOST_INTEL_CXX_VERSION <= 500) && defined(_MSC_VER) +# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +# define BOOST_NO_TEMPLATE_TEMPLATES +#endif + +#if (BOOST_INTEL_CXX_VERSION <= 600) + +# if defined(_MSC_VER) && (_MSC_VER <= 1300) // added check for <= VC 7 (Peter Dimov) + +// Boost libraries assume strong standard conformance unless otherwise +// indicated by a config macro. As configured by Intel, the EDG front-end +// requires certain compiler options be set to achieve that strong conformance. +// Particularly /Qoption,c,--arg_dep_lookup (reported by Kirk Klobe & Thomas Witt) +// and /Zc:wchar_t,forScope. See boost-root/tools/build/intel-win32-tools.jam for +// details as they apply to particular versions of the compiler. When the +// compiler does not predefine a macro indicating if an option has been set, +// this config file simply assumes the option has been set. +// Thus BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP will not be defined, even if +// the compiler option is not enabled. + +# define BOOST_NO_SWPRINTF +# endif + +// Void returns, 64 bit integrals don't work when emulating VC 6 (Peter Dimov) + +# if defined(_MSC_VER) && (_MSC_VER <= 1200) +# define BOOST_NO_VOID_RETURNS +# define BOOST_NO_INTEGRAL_INT64_T +# endif + +#endif + +#if (BOOST_INTEL_CXX_VERSION <= 710) && defined(_WIN32) +# define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS +#endif + +// See http://aspn.activestate.com/ASPN/Mail/Message/boost/1614864 +#if BOOST_INTEL_CXX_VERSION < 600 +# define BOOST_NO_INTRINSIC_WCHAR_T +#else +// We should test the macro _WCHAR_T_DEFINED to check if the compiler +// supports wchar_t natively. *BUT* there is a problem here: the standard +// headers define this macro if they typedef wchar_t. Anyway, we're lucky +// because they define it without a value, while Intel C++ defines it +// to 1. So we can check its value to see if the macro was defined natively +// or not. +// Under UNIX, the situation is exactly the same, but the macro _WCHAR_T +// is used instead. +# if ((_WCHAR_T_DEFINED + 0) == 0) && ((_WCHAR_T + 0) == 0) +# define BOOST_NO_INTRINSIC_WCHAR_T +# endif +#endif + +// +// Verify that we have actually got BOOST_NO_INTRINSIC_WCHAR_T +// set correctly, if we don't do this now, we will get errors later +// in type_traits code among other things, getting this correct +// for the Intel compiler is actually remarkably fragile and tricky: +// +#if defined(BOOST_NO_INTRINSIC_WCHAR_T) +#include +template< typename T > struct assert_no_intrinsic_wchar_t; +template<> struct assert_no_intrinsic_wchar_t { typedef void type; }; +// if you see an error here then you need to unset BOOST_NO_INTRINSIC_WCHAR_T +// where it is defined above: +typedef assert_no_intrinsic_wchar_t::type assert_no_intrinsic_wchar_t_; +#else +template< typename T > struct assert_intrinsic_wchar_t; +template<> struct assert_intrinsic_wchar_t {}; +// if you see an error here then define BOOST_NO_INTRINSIC_WCHAR_T on the command line: +template<> struct assert_intrinsic_wchar_t {}; +#endif + +#if _MSC_VER+0 >= 1000 +# if _MSC_VER >= 1200 +# define BOOST_HAS_MS_INT64 +# endif +# define BOOST_NO_SWPRINTF +#elif defined(_WIN32) +# define BOOST_DISABLE_WIN32 +#endif + +// I checked version 6.0 build 020312Z, it implements the NRVO. +// Correct this as you find out which version of the compiler +// implemented the NRVO first. (Daniel Frey) +#if (BOOST_INTEL_CXX_VERSION >= 600) +# define BOOST_HAS_NRVO +#endif + +// +// versions check: +// we don't support Intel prior to version 5.0: +#if BOOST_INTEL_CXX_VERSION < 500 +# error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version: +#if (BOOST_INTEL_CXX_VERSION > 900) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# elif defined(_MSC_VER) +# pragma message("Unknown compiler version - please run the configure tests and report the results") +# endif +#endif + + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/kai.hpp b/deprecated/eo/contrib/boost/config/compiler/kai.hpp new file mode 100644 index 000000000..de16f1a67 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/kai.hpp @@ -0,0 +1,35 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright David Abrahams 2002. +// (C) Copyright Aleksey Gurtovoy 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 for most recent version. + +// Kai C++ compiler setup: + +#include "boost/config/compiler/common_edg.hpp" + +# if (__KCC_VERSION <= 4001) || !defined(BOOST_STRICT_CONFIG) + // at least on Sun, the contents of is not in namespace std +# define BOOST_NO_STDC_NAMESPACE +# endif + +// see also common_edg.hpp which needs a special check for __KCC +# if !defined(_EXCEPTIONS) +# define BOOST_NO_EXCEPTIONS +# endif + +#define BOOST_COMPILER "Kai C++ version " BOOST_STRINGIZE(__KCC_VERSION) + +// +// last known and checked version is 4001: +#if (__KCC_VERSION > 4001) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/metrowerks.hpp b/deprecated/eo/contrib/boost/config/compiler/metrowerks.hpp new file mode 100644 index 000000000..f173295eb --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/metrowerks.hpp @@ -0,0 +1,104 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright Darin Adler 2001. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright David Abrahams 2001 - 2002. +// (C) Copyright Beman Dawes 2001 - 2003. +// (C) Copyright Stefan Slapeta 2004. +// 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 for most recent version. + +// Metrowerks C++ compiler setup: + +// locale support is disabled when linking with the dynamic runtime +# ifdef _MSL_NO_LOCALE +# define BOOST_NO_STD_LOCALE +# endif + +# if __MWERKS__ <= 0x2301 // 5.3 +# define BOOST_NO_FUNCTION_TEMPLATE_ORDERING +# define BOOST_NO_POINTER_TO_MEMBER_CONST +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +# define BOOST_NO_MEMBER_TEMPLATE_KEYWORD +# endif + +# if __MWERKS__ <= 0x2401 // 6.2 +//# define BOOST_NO_FUNCTION_TEMPLATE_ORDERING +# endif + +# if(__MWERKS__ <= 0x2407) // 7.x +# define BOOST_NO_MEMBER_FUNCTION_SPECIALIZATIONS +# define BOOST_NO_UNREACHABLE_RETURN_DETECTION +# endif + +# if(__MWERKS__ <= 0x3003) // 8.x +# define BOOST_NO_SFINAE +# endif + +// the "|| !defined(BOOST_STRICT_CONFIG)" part should apply to the last +// tested version *only*: +# if(__MWERKS__ <= 0x3206) || !defined(BOOST_STRICT_CONFIG) // 9.5 +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# define BOOST_NO_IS_ABSTRACT +# endif + +#if !__option(wchar_type) +# define BOOST_NO_INTRINSIC_WCHAR_T +#endif + +#if !__option(exceptions) +# define BOOST_NO_EXCEPTIONS +#endif + +#if (__INTEL__ && _WIN32) || (__POWERPC__ && macintosh) +# if __MWERKS__ == 0x3000 +# define BOOST_COMPILER_VERSION 8.0 +# elif __MWERKS__ == 0x3001 +# define BOOST_COMPILER_VERSION 8.1 +# elif __MWERKS__ == 0x3002 +# define BOOST_COMPILER_VERSION 8.2 +# elif __MWERKS__ == 0x3003 +# define BOOST_COMPILER_VERSION 8.3 +# elif __MWERKS__ == 0x3200 +# define BOOST_COMPILER_VERSION 9.0 +# elif __MWERKS__ == 0x3201 +# define BOOST_COMPILER_VERSION 9.1 +# elif __MWERKS__ == 0x3202 +# define BOOST_COMPILER_VERSION 9.2 +# elif __MWERKS__ == 0x3204 +# define BOOST_COMPILER_VERSION 9.3 +# elif __MWERKS__ == 0x3205 +# define BOOST_COMPILER_VERSION 9.4 +# elif __MWERKS__ == 0x3206 +# define BOOST_COMPILER_VERSION 9.5 +# else +# define BOOST_COMPILER_VERSION __MWERKS__ +# endif +#else +# define BOOST_COMPILER_VERSION __MWERKS__ +#endif + +#define BOOST_COMPILER "Metrowerks CodeWarrior C++ version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) + +// +// versions check: +// we don't support Metrowerks prior to version 5.3: +#if __MWERKS__ < 0x2301 +# error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version: +#if (__MWERKS__ > 0x3205) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + + + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/mpw.hpp b/deprecated/eo/contrib/boost/config/compiler/mpw.hpp new file mode 100644 index 000000000..8ab2aacb6 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/mpw.hpp @@ -0,0 +1,51 @@ +// (C) Copyright John Maddock 2001 - 2002. +// (C) Copyright Aleksey Gurtovoy 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 for most recent version. + +// MPW C++ compilers setup: + +# if defined(__SC__) +# define BOOST_COMPILER "MPW SCpp version " BOOST_STRINGIZE(__SC__) +# elif defined(__MRC__) +# define BOOST_COMPILER "MPW MrCpp version " BOOST_STRINGIZE(__MRC__) +# else +# error "Using MPW compiler configuration by mistake. Please update." +# endif + +// +// MPW 8.90: +// +#if (MPW_CPLUS <= 0x890) || !defined(BOOST_STRICT_CONFIG) +# define BOOST_NO_CV_SPECIALIZATIONS +# define BOOST_NO_DEPENDENT_NESTED_DERIVATIONS +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION +# define BOOST_NO_INTRINSIC_WCHAR_T +# define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION +# define BOOST_NO_USING_TEMPLATE + +# define BOOST_NO_CWCHAR +# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS + +# define BOOST_NO_STD_ALLOCATOR /* actually a bug with const reference overloading */ +#endif + +// +// versions check: +// we don't support MPW prior to version 8.9: +#if MPW_CPLUS < 0x890 +# error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 0x890: +#if (MPW_CPLUS > 0x890) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + diff --git a/deprecated/eo/contrib/boost/config/compiler/sgi_mipspro.hpp b/deprecated/eo/contrib/boost/config/compiler/sgi_mipspro.hpp new file mode 100644 index 000000000..689b67eeb --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/sgi_mipspro.hpp @@ -0,0 +1,24 @@ +// (C) Copyright John Maddock 2001 - 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 for most recent version. + +// SGI C++ compiler setup: + +#define BOOST_COMPILER "SGI Irix compiler version " BOOST_STRINGIZE(_COMPILER_VERSION) + +#include "boost/config/compiler/common_edg.hpp" + +// +// Threading support: +// Turn this on unconditionally here, it will get turned off again later +// if no threading API is detected. +// +#define BOOST_HAS_THREADS +// +// version check: +// probably nothing to do here? + + diff --git a/deprecated/eo/contrib/boost/config/compiler/sunpro_cc.hpp b/deprecated/eo/contrib/boost/config/compiler/sunpro_cc.hpp new file mode 100644 index 000000000..eca19feb0 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/sunpro_cc.hpp @@ -0,0 +1,90 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright Jens Maurer 2001 - 2003. +// (C) Copyright Peter Dimov 2002. +// (C) Copyright Aleksey Gurtovoy 2002 - 2003. +// (C) Copyright David Abrahams 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 for most recent version. + +// Sun C++ compiler setup: + +# if __SUNPRO_CC <= 0x500 +# define BOOST_NO_MEMBER_TEMPLATES +# define BOOST_NO_FUNCTION_TEMPLATE_ORDERING +# endif + +# if (__SUNPRO_CC <= 0x520) + // + // Sunpro 5.2 and earler: + // + // although sunpro 5.2 supports the syntax for + // inline initialization it often gets the value + // wrong, especially where the value is computed + // from other constants (J Maddock 6th May 2001) +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION + + // Although sunpro 5.2 supports the syntax for + // partial specialization, it often seems to + // bind to the wrong specialization. Better + // to disable it until suppport becomes more stable + // (J Maddock 6th May 2001). +# define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION +# endif + +# if (__SUNPRO_CC <= 0x530) + // Requesting debug info (-g) with Boost.Python results + // in an internal compiler error for "static const" + // initialized in-class. + // >> Assertion: (../links/dbg_cstabs.cc, line 611) + // while processing ../test.cpp at line 0. + // (Jens Maurer according to Gottfried Ganauge 04 Mar 2002) +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION + + // SunPro 5.3 has better support for partial specialization, + // but breaks when compiling std::less > + // (Jens Maurer 4 Nov 2001). + + // std::less specialization fixed as reported by George + // Heintzelman; partial specialization re-enabled + // (Peter Dimov 17 Jan 2002) + +//# define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION + + // integral constant expressions with 64 bit numbers fail +# define BOOST_NO_INTEGRAL_INT64_T +# endif + +# if (__SUNPRO_CC < 0x570) +# define BOOST_NO_TEMPLATE_TEMPLATES + // see http://lists.boost.org/MailArchives/boost/msg47184.php + // and http://lists.boost.org/MailArchives/boost/msg47220.php +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION +# define BOOST_NO_SFINAE +# define BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS +# define BOOST_NO_IS_ABSTRACT +# endif + +#define BOOST_COMPILER "Sun compiler version " BOOST_STRINGIZE(__SUNPRO_CC) + +// +// versions check: +// we don't support sunpro prior to version 4: +#if __SUNPRO_CC < 0x400 +#error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 0x570: +#if (__SUNPRO_CC > 0x570) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/vacpp.hpp b/deprecated/eo/contrib/boost/config/compiler/vacpp.hpp new file mode 100644 index 000000000..4cf0de7c1 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/vacpp.hpp @@ -0,0 +1,58 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Toon Knapen 2001 - 2003. +// (C) Copyright Lie-Quan Lee 2001. +// (C) Copyright Markus Schpflin 2002 - 2003. +// (C) Copyright Beman Dawes 2002 - 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) + +// See http://www.boost.org for most recent version. + +// Visual Age (IBM) C++ compiler setup: + +#if __IBMCPP__ <= 501 +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# define BOOST_NO_MEMBER_FUNCTION_SPECIALIZATIONS +#endif + +#if (__IBMCPP__ <= 502) +// Actually the compiler supports inclass member initialization but it +// requires a definition for the class member and it doesn't recognize +// it as an integral constant expression when used as a template argument. +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION +# define BOOST_NO_INTEGRAL_INT64_T +# define BOOST_NO_MEMBER_TEMPLATE_KEYWORD +#endif + +#if (__IBMCPP__ <= 600) || !defined(BOOST_STRICT_CONFIG) +# define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS +# define BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES 1 +#endif + +// +// On AIX thread support seems to be indicated by _THREAD_SAFE: +// +#ifdef _THREAD_SAFE +# define BOOST_HAS_THREADS +#endif + +#define BOOST_COMPILER "IBM Visual Age version " BOOST_STRINGIZE(__IBMCPP__) + +// +// versions check: +// we don't support Visual age prior to version 5: +#if __IBMCPP__ < 500 +#error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 600: +#if (__IBMCPP__ > 600) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# endif +#endif + + + + diff --git a/deprecated/eo/contrib/boost/config/compiler/visualc.hpp b/deprecated/eo/contrib/boost/config/compiler/visualc.hpp new file mode 100644 index 000000000..1ce600ccf --- /dev/null +++ b/deprecated/eo/contrib/boost/config/compiler/visualc.hpp @@ -0,0 +1,147 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001 - 2002. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright Aleksey Gurtovoy 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Beman Dawes 2002 - 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) + +// See http://www.boost.org for most recent version. + +// Microsoft Visual C++ compiler setup: + +#define BOOST_MSVC _MSC_VER + +// turn off the warnings before we #include anything +#pragma warning( disable : 4503 ) // warning: decorated name length exceeded + +#if _MSC_VER < 1300 // 1200 == VC++ 6.0, 1201 == EVC4.2 +#pragma warning( disable : 4786 ) // ident trunc to '255' chars in debug info +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +# define BOOST_NO_VOID_RETURNS +# define BOOST_NO_EXCEPTION_STD_NAMESPACE + // disable min/max macro defines on vc6: + // +#endif + +#if (_MSC_VER <= 1300) // 1300 == VC++ 7.0 + +#if !defined(_MSC_EXTENSIONS) && !defined(BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS) // VC7 bug with /Za +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +#endif + +# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION +# define BOOST_NO_PRIVATE_IN_AGGREGATE +# define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP +# define BOOST_NO_INTEGRAL_INT64_T +# define BOOST_NO_DEDUCED_TYPENAME +# define BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE + +// VC++ 6/7 has member templates but they have numerous problems including +// cases of silent failure, so for safety we define: +# define BOOST_NO_MEMBER_TEMPLATES +// For VC++ experts wishing to attempt workarounds, we define: +# define BOOST_MSVC6_MEMBER_TEMPLATES + +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION +# define BOOST_NO_CV_VOID_SPECIALIZATIONS +# define BOOST_NO_FUNCTION_TEMPLATE_ORDERING +# define BOOST_NO_USING_TEMPLATE +# define BOOST_NO_SWPRINTF +# define BOOST_NO_TEMPLATE_TEMPLATES +# define BOOST_NO_SFINAE +# define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS +# define BOOST_NO_IS_ABSTRACT +# if (_MSC_VER > 1200) +# define BOOST_NO_MEMBER_FUNCTION_SPECIALIZATIONS +# endif + +#endif + +#if _MSC_VER < 1310 // 1310 == VC++ 7.1 +# define BOOST_NO_SWPRINTF +#endif + +#if _MSC_VER <= 1400 // 1400 == VC++ 8.0 +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +#endif + +#ifndef _NATIVE_WCHAR_T_DEFINED +# define BOOST_NO_INTRINSIC_WCHAR_T +#endif + +#ifdef _WIN32_WCE +# define BOOST_NO_THREADEX +# define BOOST_NO_GETSYSTEMTIMEASFILETIME +#endif + +// +// check for exception handling support: +#ifndef _CPPUNWIND +# define BOOST_NO_EXCEPTIONS +#endif + +// +// __int64 support: +// +#if (_MSC_VER >= 1200) +# define BOOST_HAS_MS_INT64 +#endif +#if (_MSC_VER >= 1310) && defined(_MSC_EXTENSIONS) +# define BOOST_HAS_LONG_LONG +#endif +// +// disable Win32 API's if compiler extentions are +// turned off: +// +#ifndef _MSC_EXTENSIONS +# define BOOST_DISABLE_WIN32 +#endif + +// +// all versions support __declspec: +// +#define BOOST_HAS_DECLSPEC +// +// prefix and suffix headers: +// +#ifndef BOOST_ABI_PREFIX +# define BOOST_ABI_PREFIX "boost/config/abi/msvc_prefix.hpp" +#endif +#ifndef BOOST_ABI_SUFFIX +# define BOOST_ABI_SUFFIX "boost/config/abi/msvc_suffix.hpp" +#endif + +# if _MSC_VER == 1200 +# define BOOST_COMPILER_VERSION 6.0 +# elif _MSC_VER == 1300 +# define BOOST_COMPILER_VERSION 7.0 +# elif _MSC_VER == 1310 +# define BOOST_COMPILER_VERSION 7.1 +# elif _MSC_VER == 1400 +# define BOOST_COMPILER_VERSION 8.0 +# else +# define BOOST_COMPILER_VERSION _MSC_VER +# endif + +#define BOOST_COMPILER "Microsoft Visual C++ version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) + +// +// versions check: +// we don't support Visual C++ prior to version 6: +#if _MSC_VER < 1200 +#error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 1310: +#if (_MSC_VER > 1400) +# if defined(BOOST_ASSERT_CONFIG) +# error "Unknown compiler version - please run the configure tests and report the results" +# else +# pragma message("Unknown compiler version - please run the configure tests and report the results") +# endif +#endif diff --git a/deprecated/eo/contrib/boost/config/platform/aix.hpp b/deprecated/eo/contrib/boost/config/platform/aix.hpp new file mode 100644 index 000000000..894ef42ce --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/aix.hpp @@ -0,0 +1,33 @@ +// (C) Copyright John Maddock 2001 - 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 for most recent version. + +// IBM/Aix specific config options: + +#define BOOST_PLATFORM "IBM Aix" + +#define BOOST_HAS_UNISTD_H +#define BOOST_HAS_NL_TYPES_H +#define BOOST_HAS_NANOSLEEP +#define BOOST_HAS_CLOCK_GETTIME + +// This needs support in "boost/cstdint.hpp" exactly like FreeBSD. +// This platform has header named which includes all +// the things needed. +#define BOOST_HAS_STDINT_H + +// Threading API's: +#define BOOST_HAS_PTHREADS +#define BOOST_HAS_PTHREAD_DELAY_NP +#define BOOST_HAS_SCHED_YIELD +//#define BOOST_HAS_PTHREAD_YIELD + +// boilerplate code: +#include + + + + diff --git a/deprecated/eo/contrib/boost/config/platform/amigaos.hpp b/deprecated/eo/contrib/boost/config/platform/amigaos.hpp new file mode 100644 index 000000000..34bcf4128 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/amigaos.hpp @@ -0,0 +1,15 @@ +// (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 for most recent version. + +#define BOOST_PLATFORM "AmigaOS" + +#define BOOST_DISABLE_THREADS +#define BOOST_NO_CWCHAR +#define BOOST_NO_STD_WSTRING +#define BOOST_NO_INTRINSIC_WCHAR_T + + diff --git a/deprecated/eo/contrib/boost/config/platform/beos.hpp b/deprecated/eo/contrib/boost/config/platform/beos.hpp new file mode 100644 index 000000000..48c3d8dc5 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/beos.hpp @@ -0,0 +1,26 @@ +// (C) Copyright John Maddock 2001. +// 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 for most recent version. + +// BeOS specific config options: + +#define BOOST_PLATFORM "BeOS" + +#define BOOST_NO_CWCHAR +#define BOOST_NO_CWCTYPE +#define BOOST_HAS_UNISTD_H + +#define BOOST_HAS_BETHREADS + +#ifndef BOOST_DISABLE_THREADS +# define BOOST_HAS_THREADS +#endif + +// boilerplate code: +#include + + + diff --git a/deprecated/eo/contrib/boost/config/platform/bsd.hpp b/deprecated/eo/contrib/boost/config/platform/bsd.hpp new file mode 100644 index 000000000..09988e0ca --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/bsd.hpp @@ -0,0 +1,71 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001. +// (C) Copyright Douglas Gregor 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 for most recent version. + +// generic BSD config options: + +#if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) +#error "This platform is not BSD" +#endif + +#ifdef __FreeBSD__ +#define BOOST_PLATFORM "FreeBSD " BOOST_STRINGIZE(__FreeBSD__) +#elif defined(__NetBSD__) +#define BOOST_PLATFORM "NetBSD " BOOST_STRINGIZE(__NetBSD__) +#elif defined(__OpenBSD__) +#define BOOST_PLATFORM "OpenBSD " BOOST_STRINGIZE(__OpenBSD__) +#endif + +// +// is this the correct version check? +// FreeBSD has but does not +// advertise the fact in : +// +#if defined(__FreeBSD__) && (__FreeBSD__ >= 3) +# define BOOST_HAS_NL_TYPES_H +#endif + +// +// FreeBSD 3.x has pthreads support, but defines _POSIX_THREADS in +// and not in +// +#if defined(__FreeBSD__) && (__FreeBSD__ <= 3) +# define BOOST_HAS_PTHREADS +#endif + +// +// No wide character support in the BSD header files: +// +#if !(defined(__FreeBSD__) && (__FreeBSD__ >= 5)) +# define BOOST_NO_CWCHAR +#endif +// +// The BSD has macros only, no functions: +// +#if !defined(__OpenBSD__) +# define BOOST_NO_CTYPE_FUNCTIONS +#endif + +// +// thread API's not auto detected: +// +#define BOOST_HAS_SCHED_YIELD +#define BOOST_HAS_NANOSLEEP +#define BOOST_HAS_GETTIMEOFDAY +#define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +#define BOOST_HAS_SIGACTION + +// boilerplate code: +#define BOOST_HAS_UNISTD_H +#include + + + + + + diff --git a/deprecated/eo/contrib/boost/config/platform/cygwin.hpp b/deprecated/eo/contrib/boost/config/platform/cygwin.hpp new file mode 100644 index 000000000..0fd2ebe2d --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/cygwin.hpp @@ -0,0 +1,48 @@ +// (C) Copyright John Maddock 2001 - 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) + +// See http://www.boost.org for most recent version. + +// cygwin specific config options: + +#define BOOST_PLATFORM "Cygwin" +#define BOOST_NO_CWCTYPE +#define BOOST_NO_CWCHAR +#define BOOST_NO_SWPRINTF +#define BOOST_HAS_DIRENT_H + +// +// Threading API: +// See if we have POSIX threads, if we do use them, otherwise +// revert to native Win threads. +#define BOOST_HAS_UNISTD_H +#include +#if defined(_POSIX_THREADS) && (_POSIX_THREADS+0 >= 0) && !defined(BOOST_HAS_WINTHREADS) +# define BOOST_HAS_PTHREADS +# define BOOST_HAS_SCHED_YIELD +# define BOOST_HAS_GETTIMEOFDAY +# define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +# define BOOST_HAS_SIGACTION +#else +# if !defined(BOOST_HAS_WINTHREADS) +# define BOOST_HAS_WINTHREADS +# endif +# define BOOST_HAS_FTIME +#endif + +// +// find out if we have a stdint.h, there should be a better way to do this: +// +#include +#ifdef _STDINT_H +#define BOOST_HAS_STDINT_H +#endif + +// boilerplate code: +#include + + + + diff --git a/deprecated/eo/contrib/boost/config/platform/hpux.hpp b/deprecated/eo/contrib/boost/config/platform/hpux.hpp new file mode 100644 index 000000000..fa773aa79 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/hpux.hpp @@ -0,0 +1,68 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001 - 2003. +// (C) Copyright David Abrahams 2002. +// (C) Copyright Toon Knapen 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) + +// See http://www.boost.org for most recent version. + +// hpux specific config options: + +#define BOOST_PLATFORM "HP-UX" + +// In principle, HP-UX has a nice under the name +// However, it has the following problem: +// Use of UINT32_C(0) results in "0u l" for the preprocessed source +// (verifyable with gcc 2.95.3, assumed for HP aCC) +// #define BOOST_HAS_STDINT_H + +#define BOOST_NO_SWPRINTF +#define BOOST_NO_CWCTYPE + +#if defined(__GNUC__) +# if (__GNUC__ < 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ < 3)) + // GNU C on HP-UX does not support threads (checked up to gcc 3.3) +# define BOOST_DISABLE_THREADS +# elif !defined(BOOST_DISABLE_THREADS) + // threads supported from gcc-3.3 onwards: +# define BOOST_HAS_THREADS +# define BOOST_HAS_PTHREADS +# endif +#endif + +// boilerplate code: +#define BOOST_HAS_UNISTD_H +#include + +// the following are always available: +#ifndef BOOST_HAS_GETTIMEOFDAY +# define BOOST_HAS_GETTIMEOFDAY +#endif +#ifndef BOOST_HAS_SCHED_YIELD +# define BOOST_HAS_SCHED_YIELD +#endif +#ifndef BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +# define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +#endif +#ifndef BOOST_HAS_NL_TYPES_H +# define BOOST_HAS_NL_TYPES_H +#endif +#ifndef BOOST_HAS_NANOSLEEP +# define BOOST_HAS_NANOSLEEP +#endif +#ifndef BOOST_HAS_GETTIMEOFDAY +# define BOOST_HAS_GETTIMEOFDAY +#endif +#ifndef BOOST_HAS_DIRENT_H +# define BOOST_HAS_DIRENT_H +#endif +#ifndef BOOST_HAS_CLOCK_GETTIME +# define BOOST_HAS_CLOCK_GETTIME +#endif +#ifndef BOOST_HAS_SIGACTION +# define BOOST_HAS_SIGACTION +#endif + + diff --git a/deprecated/eo/contrib/boost/config/platform/irix.hpp b/deprecated/eo/contrib/boost/config/platform/irix.hpp new file mode 100644 index 000000000..aeae49c8b --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/irix.hpp @@ -0,0 +1,31 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 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) + + +// See http://www.boost.org for most recent version. + +// SGI Irix specific config options: + +#define BOOST_PLATFORM "SGI Irix" + +#define BOOST_NO_SWPRINTF +// +// these are not auto detected by POSIX feature tests: +// +#define BOOST_HAS_GETTIMEOFDAY +#define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE + +#ifdef __GNUC__ + // GNU C on IRIX does not support threads (checked up to gcc 3.3) +# define BOOST_DISABLE_THREADS +#endif + +// boilerplate code: +#define BOOST_HAS_UNISTD_H +#include + + + diff --git a/deprecated/eo/contrib/boost/config/platform/linux.hpp b/deprecated/eo/contrib/boost/config/platform/linux.hpp new file mode 100644 index 000000000..51ae13347 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/linux.hpp @@ -0,0 +1,98 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001 - 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) + +// See http://www.boost.org for most recent version. + +// linux specific config options: + +#define BOOST_PLATFORM "linux" + +// make sure we have __GLIBC_PREREQ if available at all +#include + +// +// added to glibc 2.1.1 +// We can only test for 2.1 though: +// +#if defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1))) + // defines int64_t unconditionally, but defines + // int64_t only if __GNUC__. Thus, assume a fully usable + // only when using GCC. +# if defined __GNUC__ +# define BOOST_HAS_STDINT_H +# endif +#endif + +#if defined(__LIBCOMO__) + // + // como on linux doesn't have std:: c functions: + // NOTE: versions of libcomo prior to beta28 have octal version numbering, + // e.g. version 25 is 21 (dec) + // +# if __LIBCOMO_VERSION__ <= 20 +# define BOOST_NO_STDC_NAMESPACE +# endif + +# if __LIBCOMO_VERSION__ <= 21 +# define BOOST_NO_SWPRINTF +# endif + +#endif + +// +// If glibc is past version 2 then we definitely have +// gettimeofday, earlier versions may or may not have it: +// +#if defined(__GLIBC__) && (__GLIBC__ >= 2) +# define BOOST_HAS_GETTIMEOFDAY +#endif + +#ifdef __USE_POSIX199309 +# define BOOST_HAS_NANOSLEEP +#endif + +#if defined(__GLIBC__) && defined(__GLIBC_PREREQ) +// __GLIBC_PREREQ is available since 2.1.2 + + // swprintf is available since glibc 2.2.0 +# if !__GLIBC_PREREQ(2,2) || (!defined(__USE_ISOC99) && !defined(__USE_UNIX98)) +# define BOOST_NO_SWPRINTF +# endif +#else +# define BOOST_NO_SWPRINTF +#endif + +// boilerplate code: +#define BOOST_HAS_UNISTD_H +#include + +#ifndef __GNUC__ +// +// if the compiler is not gcc we still need to be able to parse +// the GNU system headers, some of which (mainly ) +// use GNU specific extensions: +// +# ifndef __extension__ +# define __extension__ +# endif +# ifndef __const__ +# define __const__ const +# endif +# ifndef __volatile__ +# define __volatile__ volatile +# endif +# ifndef __signed__ +# define __signed__ signed +# endif +# ifndef __typeof__ +# define __typeof__ typeof +# endif +# ifndef __inline__ +# define __inline__ inline +# endif +#endif + + diff --git a/deprecated/eo/contrib/boost/config/platform/macos.hpp b/deprecated/eo/contrib/boost/config/platform/macos.hpp new file mode 100644 index 000000000..d6877d311 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/macos.hpp @@ -0,0 +1,78 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001 - 2002. +// (C) Copyright Bill Kempf 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 for most recent version. + +// Mac OS specific config options: + +#define BOOST_PLATFORM "Mac OS" + +#if __MACH__ && !defined(_MSL_USING_MSL_C) + +// Using the Mac OS X system BSD-style C library. + +# ifndef BOOST_HAS_UNISTD_H +# define BOOST_HAS_UNISTD_H +# endif +// +// Begin by including our boilerplate code for POSIX +// feature detection, this is safe even when using +// the MSL as Metrowerks supply their own +// to replace the platform-native BSD one. G++ users +// should also always be able to do this on MaxOS X. +// +# include +# ifndef BOOST_HAS_STDINT_H +# define BOOST_HAS_STDINT_H +# endif + +// +// BSD runtime has pthreads, sigaction, sched_yield and gettimeofday, +// of these only pthreads are advertised in , so set the +// other options explicitly: +// +# define BOOST_HAS_SCHED_YIELD +# define BOOST_HAS_GETTIMEOFDAY +# define BOOST_HAS_SIGACTION + +# if (__GNUC__ < 3) && !defined( __APPLE_CC__) + +// GCC strange "ignore std" mode works better if you pretend everything +// is in the std namespace, for the most part. + +# define BOOST_NO_STDC_NAMESPACE +# endif + +#else + +// Using the MSL C library. + +// We will eventually support threads in non-Carbon builds, but we do +// not support this yet. +# if ( defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON ) || ( defined(TARGET_CARBON) && TARGET_CARBON ) + +# if !defined(BOOST_HAS_PTHREADS) +# define BOOST_HAS_MPTASKS +# elif ( __dest_os == __mac_os_x ) +// We are doing a Carbon/Mach-O/MSL build which has pthreads, but only the +// gettimeofday and no posix. +# define BOOST_HAS_GETTIMEOFDAY +# endif + +// The MP task implementation of Boost Threads aims to replace MP-unsafe +// parts of the MSL, so we turn on threads unconditionally. +# define BOOST_HAS_THREADS + +// The remote call manager depends on this. +# define BOOST_BIND_ENABLE_PASCAL + +# endif + +#endif + + + diff --git a/deprecated/eo/contrib/boost/config/platform/solaris.hpp b/deprecated/eo/contrib/boost/config/platform/solaris.hpp new file mode 100644 index 000000000..700dc3ce6 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/solaris.hpp @@ -0,0 +1,21 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 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) + +// See http://www.boost.org for most recent version. + +// sun specific config options: + +#define BOOST_PLATFORM "Sun Solaris" + +#define BOOST_HAS_GETTIMEOFDAY + +// boilerplate code: +#define BOOST_HAS_UNISTD_H +#include + + + + diff --git a/deprecated/eo/contrib/boost/config/platform/win32.hpp b/deprecated/eo/contrib/boost/config/platform/win32.hpp new file mode 100644 index 000000000..548bff280 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/platform/win32.hpp @@ -0,0 +1,50 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Bill Kempf 2001. +// (C) Copyright Aleksey Gurtovoy 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) + +// See http://www.boost.org for most recent version. + +// Win32 specific config options: + +#define BOOST_PLATFORM "Win32" + +#if defined(__GNUC__) && !defined(BOOST_NO_SWPRINTF) +# define BOOST_NO_SWPRINTF +#endif + +#if !defined(__GNUC__) && !defined(BOOST_HAS_DECLSPEC) +# define BOOST_HAS_DECLSPEC +#endif + +#if defined(__MINGW32__) && ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 2))) +# define BOOST_HAS_STDINT_H +# define __STDC_LIMIT_MACROS +#endif + +// +// Win32 will normally be using native Win32 threads, +// but there is a pthread library avaliable as an option, +// we used to disable this when BOOST_DISABLE_WIN32 was +// defined but no longer - this should allow some +// files to be compiled in strict mode - while maintaining +// a consistent setting of BOOST_HAS_THREADS across +// all translation units (needed for shared_ptr etc). +// + +#ifdef _WIN32_WCE +# define BOOST_NO_ANSI_APIS +#endif + +#ifndef BOOST_HAS_PTHREADS +# define BOOST_HAS_WINTHREADS +#endif + +#ifndef BOOST_DISABLE_WIN32 +// WEK: Added +#define BOOST_HAS_FTIME +#define BOOST_WINDOWS 1 + +#endif diff --git a/deprecated/eo/contrib/boost/config/posix_features.hpp b/deprecated/eo/contrib/boost/config/posix_features.hpp new file mode 100644 index 000000000..4afb476b7 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/posix_features.hpp @@ -0,0 +1,87 @@ +// (C) Copyright John Maddock 2001 - 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) + + +// See http://www.boost.org for most recent version. + +// All POSIX feature tests go in this file, +// Note that we test _POSIX_C_SOURCE and _XOPEN_SOURCE as well +// _POSIX_VERSION and _XOPEN_VERSION: on some systems POSIX API's +// may be present but none-functional unless _POSIX_C_SOURCE and +// _XOPEN_SOURCE have been defined to the right value (it's up +// to the user to do this *before* including any header, although +// in most cases the compiler will do this for you). + +# if defined(BOOST_HAS_UNISTD_H) +# include + + // XOpen has , but is this the correct version check? +# if defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 3) +# define BOOST_HAS_NL_TYPES_H +# endif + + // POSIX version 6 requires +# if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 200100) +# define BOOST_HAS_STDINT_H +# endif + + // POSIX version 2 requires +# if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 199009L) +# define BOOST_HAS_DIRENT_H +# endif + + // POSIX version 3 requires to have sigaction: +# if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 199506L) +# define BOOST_HAS_SIGACTION +# endif + // POSIX defines _POSIX_THREADS > 0 for pthread support, + // however some platforms define _POSIX_THREADS without + // a value, hence the (_POSIX_THREADS+0 >= 0) check. + // Strictly speaking this may catch platforms with a + // non-functioning stub , but such occurrences should + // occur very rarely if at all. +# if defined(_POSIX_THREADS) && (_POSIX_THREADS+0 >= 0) && !defined(BOOST_HAS_WINTHREADS) && !defined(BOOST_HAS_MPTASKS) +# define BOOST_HAS_PTHREADS +# endif + + // BOOST_HAS_NANOSLEEP: + // This is predicated on _POSIX_TIMERS or _XOPEN_REALTIME: +# if (defined(_POSIX_TIMERS) && (_POSIX_TIMERS+0 >= 0)) \ + || (defined(_XOPEN_REALTIME) && (_XOPEN_REALTIME+0 >= 0)) +# define BOOST_HAS_NANOSLEEP +# endif + + // BOOST_HAS_CLOCK_GETTIME: + // This is predicated on _POSIX_TIMERS (also on _XOPEN_REALTIME + // but at least one platform - linux - defines that flag without + // defining clock_gettime): +# if (defined(_POSIX_TIMERS) && (_POSIX_TIMERS+0 >= 0)) +# define BOOST_HAS_CLOCK_GETTIME +# endif + + // BOOST_HAS_SCHED_YIELD: + // This is predicated on _POSIX_PRIORITY_SCHEDULING or + // on _POSIX_THREAD_PRIORITY_SCHEDULING or on _XOPEN_REALTIME. +# if defined(_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING+0 > 0)\ + || (defined(_POSIX_THREAD_PRIORITY_SCHEDULING) && (_POSIX_THREAD_PRIORITY_SCHEDULING+0 > 0))\ + || (defined(_XOPEN_REALTIME) && (_XOPEN_REALTIME+0 >= 0)) +# define BOOST_HAS_SCHED_YIELD +# endif + + // BOOST_HAS_GETTIMEOFDAY: + // BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE: + // These are predicated on _XOPEN_VERSION, and appears to be first released + // in issue 4, version 2 (_XOPEN_VERSION > 500). +# if defined(_XOPEN_VERSION) && (_XOPEN_VERSION+0 >= 500) +# define BOOST_HAS_GETTIMEOFDAY +# if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE+0 >= 500) +# define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +# endif +# endif + +# endif + + + diff --git a/deprecated/eo/contrib/boost/config/requires_threads.hpp b/deprecated/eo/contrib/boost/config/requires_threads.hpp new file mode 100644 index 000000000..cfaff2302 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/requires_threads.hpp @@ -0,0 +1,92 @@ +// (C) 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) + + +#ifndef BOOST_CONFIG_REQUIRES_THREADS_HPP +#define BOOST_CONFIG_REQUIRES_THREADS_HPP + +#ifndef BOOST_CONFIG_HPP +# include +#endif + +#if defined(BOOST_DISABLE_THREADS) + +// +// special case to handle versions of gcc which don't currently support threads: +// +#if defined(__GNUC__) && ((__GNUC__ < 3) || (__GNUC_MINOR__ <= 3) || !defined(BOOST_STRICT_CONFIG)) +// +// this is checked up to gcc 3.3: +// +#if defined(__sgi) || defined(__hpux) +# error "Multi-threaded programs are not supported by gcc on HPUX or Irix (last checked with gcc 3.3)" +#endif + +#endif + +# error "Threading support unavaliable: it has been explicitly disabled with BOOST_DISABLE_THREADS" + +#elif !defined(BOOST_HAS_THREADS) + +# if defined __COMO__ +// Comeau C++ +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -D_MT (Windows) or -D_REENTRANT (Unix)" + +#elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) +// Intel +#ifdef _WIN32 +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: either /MT /MTd /MD or /MDd" +#else +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -openmp" +#endif + +# elif defined __GNUC__ +// GNU C++: +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -pthread (Linux), -pthreads (Solaris) or -mthreads (Mingw32)" + +#elif defined __sgi +// SGI MIPSpro C++ +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -D_SGI_MP_SOURCE" + +#elif defined __DECCXX +// Compaq Tru64 Unix cxx +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -pthread" + +#elif defined __BORLANDC__ +// Borland +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -tWM" + +#elif defined __MWERKS__ +// Metrowerks CodeWarrior +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: either -runtime sm, -runtime smd, -runtime dm, or -runtime dmd" + +#elif defined __SUNPRO_CC +// Sun Workshop Compiler C++ +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -mt" + +#elif defined __HP_aCC +// HP aCC +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -mt" + +#elif defined(__IBMCPP__) +// IBM Visual Age +# error "Compiler threading support is not turned on. Please compile the code with the xlC_r compiler" + +#elif defined _MSC_VER +// Microsoft Visual C++ +// +// Must remain the last #elif since some other vendors (Metrowerks, for +// example) also #define _MSC_VER +# error "Compiler threading support is not turned on. Please set the correct command line options for threading: either /MT /MTd /MD or /MDd" + +#else + +# error "Compiler threading support is not turned on. Please consult your compiler's documentation for the appropriate options to use" + +#endif // compilers + +#endif // BOOST_HAS_THREADS + +#endif // BOOST_CONFIG_REQUIRES_THREADS_HPP diff --git a/deprecated/eo/contrib/boost/config/select_compiler_config.hpp b/deprecated/eo/contrib/boost/config/select_compiler_config.hpp new file mode 100644 index 000000000..3453f1a35 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/select_compiler_config.hpp @@ -0,0 +1,83 @@ +// Boost compiler configuration selection header file + +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Martin Wille 2003. +// (C) Copyright Guillaume Melquiond 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) + +// See http://www.boost.org for most recent version. + +// locate which compiler we are using and define +// BOOST_COMPILER_CONFIG as needed: + +# if defined __COMO__ +// Comeau C++ +# define BOOST_COMPILER_CONFIG "boost/config/compiler/comeau.hpp" + +#elif defined __DMC__ +// Digital Mars C++ +# define BOOST_COMPILER_CONFIG "boost/config/compiler/digitalmars.hpp" + +#elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) +// Intel +# define BOOST_COMPILER_CONFIG "boost/config/compiler/intel.hpp" + +# elif defined __GNUC__ +// GNU C++: +# define BOOST_COMPILER_CONFIG "boost/config/compiler/gcc.hpp" + +#elif defined __KCC +// Kai C++ +# define BOOST_COMPILER_CONFIG "boost/config/compiler/kai.hpp" + +#elif defined __sgi +// SGI MIPSpro C++ +# define BOOST_COMPILER_CONFIG "boost/config/compiler/sgi_mipspro.hpp" + +#elif defined __DECCXX +// Compaq Tru64 Unix cxx +# define BOOST_COMPILER_CONFIG "boost/config/compiler/compaq_cxx.hpp" + +#elif defined __ghs +// Greenhills C++ +# define BOOST_COMPILER_CONFIG "boost/config/compiler/greenhills.hpp" + +#elif defined __BORLANDC__ +// Borland +# define BOOST_COMPILER_CONFIG "boost/config/compiler/borland.hpp" + +#elif defined __MWERKS__ +// Metrowerks CodeWarrior +# define BOOST_COMPILER_CONFIG "boost/config/compiler/metrowerks.hpp" + +#elif defined __SUNPRO_CC +// Sun Workshop Compiler C++ +# define BOOST_COMPILER_CONFIG "boost/config/compiler/sunpro_cc.hpp" + +#elif defined __HP_aCC +// HP aCC +# define BOOST_COMPILER_CONFIG "boost/config/compiler/hp_acc.hpp" + +#elif defined(__MRC__) || defined(__SC__) +// MPW MrCpp or SCpp +# define BOOST_COMPILER_CONFIG "boost/config/compiler/mpw.hpp" + +#elif defined(__IBMCPP__) +// IBM Visual Age +# define BOOST_COMPILER_CONFIG "boost/config/compiler/vacpp.hpp" + +#elif defined _MSC_VER +// Microsoft Visual C++ +// +// Must remain the last #elif since some other vendors (Metrowerks, for +// example) also #define _MSC_VER +# define BOOST_COMPILER_CONFIG "boost/config/compiler/visualc.hpp" + +#elif defined (BOOST_ASSERT_CONFIG) +// this must come last - generate an error if we don't +// recognise the compiler: +# error "Unknown compiler - please configure (http://www.boost.org/libs/config/config.htm#configuring) and report the results to the main boost mailing list (http://www.boost.org/more/mailing_lists.htm#main)" + +#endif diff --git a/deprecated/eo/contrib/boost/config/select_platform_config.hpp b/deprecated/eo/contrib/boost/config/select_platform_config.hpp new file mode 100644 index 000000000..60bfa5095 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/select_platform_config.hpp @@ -0,0 +1,86 @@ +// Boost compiler configuration selection header file + +// (C) Copyright John Maddock 2001 - 2002. +// (C) Copyright Jens Maurer 2001. +// 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 for most recent version. + +// locate which platform we are on and define BOOST_PLATFORM_CONFIG as needed. +// Note that we define the headers to include using "header_name" not +// in order to prevent macro expansion within the header +// name (for example "linux" is a macro on linux systems). + +#if defined(linux) || defined(__linux) || defined(__linux__) +// linux: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/linux.hpp" + +#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) +// BSD: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/bsd.hpp" + +#elif defined(sun) || defined(__sun) +// solaris: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/solaris.hpp" + +#elif defined(__sgi) +// SGI Irix: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/irix.hpp" + +#elif defined(__hpux) +// hp unix: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/hpux.hpp" + +#elif defined(__CYGWIN__) +// cygwin is not win32: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/cygwin.hpp" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +// win32: +# define BOOST_PLATFORM_CONFIG "boost/config/platform/win32.hpp" + +#elif defined(__BEOS__) +// BeOS +# define BOOST_PLATFORM_CONFIG "boost/config/platform/beos.hpp" + +#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) +// MacOS +# define BOOST_PLATFORM_CONFIG "boost/config/platform/macos.hpp" + +#elif defined(__IBMCPP__) || defined(_AIX) +// IBM +# define BOOST_PLATFORM_CONFIG "boost/config/platform/aix.hpp" + +#elif defined(__amigaos__) +// AmigaOS +# define BOOST_PLATFORM_CONFIG "boost/config/platform/amigaos.hpp" + +#else + +# if defined(unix) \ + || defined(__unix) \ + || defined(_XOPEN_SOURCE) \ + || defined(_POSIX_SOURCE) + + // generic unix platform: + +# ifndef BOOST_HAS_UNISTD_H +# define BOOST_HAS_UNISTD_H +# endif + +# include + +# endif + +# if defined (BOOST_ASSERT_CONFIG) + // this must come last - generate an error if we don't + // recognise the platform: +# error "Unknown platform - please configure and report the results to boost.org" +# endif + +#endif + + + diff --git a/deprecated/eo/contrib/boost/config/select_stdlib_config.hpp b/deprecated/eo/contrib/boost/config/select_stdlib_config.hpp new file mode 100644 index 000000000..b7bf59143 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/select_stdlib_config.hpp @@ -0,0 +1,68 @@ +// Boost compiler configuration selection header file + +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001 - 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 for most recent version. + +// locate which std lib we are using and define BOOST_STDLIB_CONFIG as needed: + +// we need to include a std lib header here in order to detect which +// library is in use, use as it's about the smallest +// of the std lib headers - do not rely on this header being included - +// users can short-circuit this header if they know whose std lib +// they are using. + +#include + +#if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) +// STLPort library; this _must_ come first, otherwise since +// STLport typically sits on top of some other library, we +// can end up detecting that first rather than STLport: +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/stlport.hpp" + +#elif defined(__LIBCOMO__) +// Comeau STL: +#define BOOST_STDLIB_CONFIG "boost/config/stdlib/libcomo.hpp" + +#elif defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER) +// Rogue Wave library: +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/roguewave.hpp" + +#elif defined(__GLIBCPP__) || defined(__GLIBCXX__) +// GNU libstdc++ 3 +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/libstdcpp3.hpp" + +#elif defined(__STL_CONFIG_H) +// generic SGI STL +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/sgi.hpp" + +#elif defined(__MSL_CPP__) +// MSL standard lib: +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/msl.hpp" + +#elif defined(__IBMCPP__) +// take the default VACPP std lib +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/vacpp.hpp" + +#elif defined(MSIPL_COMPILE_H) +// Modena C++ standard library +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/modena.hpp" + +#elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER) +// Dinkumware Library (this has to appear after any possible replacement libraries): +# define BOOST_STDLIB_CONFIG "boost/config/stdlib/dinkumware.hpp" + +#elif defined (BOOST_ASSERT_CONFIG) +// this must come last - generate an error if we don't +// recognise the library: +# error "Unknown standard library - please configure and report the results to boost.org" + +#endif + + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/dinkumware.hpp b/deprecated/eo/contrib/boost/config/stdlib/dinkumware.hpp new file mode 100644 index 000000000..aa214fc1b --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/dinkumware.hpp @@ -0,0 +1,106 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright David Abrahams 2002. +// (C) Copyright Guillaume Melquiond 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) + +// See http://www.boost.org for most recent version. + +// Dinkumware standard library config: + +#if !defined(_YVALS) && !defined(_CPPLIB_VER) +#include +#if !defined(_YVALS) && !defined(_CPPLIB_VER) +#error This is not the Dinkumware lib! +#endif +#endif + + +#if defined(_CPPLIB_VER) && (_CPPLIB_VER >= 306) + // full dinkumware 3.06 and above + // fully conforming provided the compiler supports it: +# if !(defined(_GLOBAL_USING) && (_GLOBAL_USING+0 > 0)) && !defined(__BORLANDC__) && !defined(_STD) && !(defined(__ICC) && (__ICC >= 700)) // can be defined in yvals.h +# define BOOST_NO_STDC_NAMESPACE +# endif +# if !(defined(_HAS_MEMBER_TEMPLATES_REBIND) && (_HAS_MEMBER_TEMPLATES_REBIND+0 > 0)) && !(defined(_MSC_VER) && (_MSC_VER > 1300)) && defined(BOOST_MSVC) +# define BOOST_NO_STD_ALLOCATOR +# endif +# define BOOST_HAS_PARTIAL_STD_ALLOCATOR +# if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) + // if this lib version is set up for vc6 then there is no std::use_facet: +# define BOOST_NO_STD_USE_FACET +# define BOOST_HAS_TWO_ARG_USE_FACET + // C lib functions aren't in namespace std either: +# define BOOST_NO_STDC_NAMESPACE + // and nor is +# define BOOST_NO_EXCEPTION_STD_NAMESPACE +# endif +// There's no numeric_limits support unless _LONGLONG is defined: +# if !defined(_LONGLONG) && (_CPPLIB_VER <= 310) +# define BOOST_NO_MS_INT64_NUMERIC_LIMITS +# endif +// 3.06 appears to have (non-sgi versions of) & , +// and no at all +#else +# define BOOST_MSVC_STD_ITERATOR 1 +# define BOOST_NO_STD_ITERATOR +# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS +# define BOOST_NO_STD_ALLOCATOR +# define BOOST_NO_STDC_NAMESPACE +# define BOOST_NO_STD_USE_FACET +# define BOOST_NO_STD_OUTPUT_ITERATOR_ASSIGN +# define BOOST_HAS_MACRO_USE_FACET +# ifndef _CPPLIB_VER + // Updated Dinkum library defines this, and provides + // its own min and max definitions. +# define BOOST_NO_STD_MIN_MAX +# define BOOST_NO_MS_INT64_NUMERIC_LIMITS +# endif +#endif + +// +// std extension namespace is stdext for vc7.1 and later, +// the same applies to other compilers that sit on top +// of vc7.1 (Intel and Comeau): +// +#if defined(_MSC_VER) && (_MSC_VER >= 1310) && !defined(__BORLANDC__) +# define BOOST_STD_EXTENSION_NAMESPACE stdext +#endif + + +#if (defined(_MSC_VER) && (_MSC_VER <= 1300) && !defined(__BORLANDC__)) || !defined(_CPPLIB_VER) || (_CPPLIB_VER < 306) + // if we're using a dinkum lib that's + // been configured for VC6/7 then there is + // no iterator traits (true even for icl) +# define BOOST_NO_STD_ITERATOR_TRAITS +#endif + +#if defined(__ICL) && (__ICL < 800) && defined(_CPPLIB_VER) && (_CPPLIB_VER <= 310) +// Intel C++ chokes over any non-trivial use of +// this may be an overly restrictive define, but regex fails without it: +# define BOOST_NO_STD_LOCALE +#endif + +#ifdef _CPPLIB_VER +# define BOOST_DINKUMWARE_STDLIB _CPPLIB_VER +#else +# define BOOST_DINKUMWARE_STDLIB 1 +#endif + +#ifdef _CPPLIB_VER +# define BOOST_STDLIB "Dinkumware standard library version " BOOST_STRINGIZE(_CPPLIB_VER) +#else +# define BOOST_STDLIB "Dinkumware standard library version 1.x" +#endif + + + + + + + + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/libcomo.hpp b/deprecated/eo/contrib/boost/config/stdlib/libcomo.hpp new file mode 100644 index 000000000..b2c8e4400 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/libcomo.hpp @@ -0,0 +1,46 @@ +// (C) Copyright John Maddock 2002 - 2003. +// (C) Copyright Jens Maurer 2002 - 2003. +// (C) Copyright Beman Dawes 2002 - 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) + +// See http://www.boost.org for most recent version. + +// Comeau STL: + +#if !defined(__LIBCOMO__) +# include +# if !defined(__LIBCOMO__) +# error "This is not the Comeau STL!" +# endif +#endif + +// +// std::streambuf is non-standard +// NOTE: versions of libcomo prior to beta28 have octal version numbering, +// e.g. version 25 is 21 (dec) +#if __LIBCOMO_VERSION__ <= 22 +# define BOOST_NO_STD_WSTREAMBUF +#endif + +#if (__LIBCOMO_VERSION__ <= 31) && defined(_WIN32) +#define BOOST_NO_SWPRINTF +#endif + +#if __LIBCOMO_VERSION__ >= 31 +# define BOOST_HAS_HASH +# define BOOST_HAS_SLIST +#endif + +// +// Intrinsic type_traits support. +// The SGI STL has it's own __type_traits class, which +// has intrinsic compiler support with SGI's compilers. +// Whatever map SGI style type traits to boost equivalents: +// +#define BOOST_HAS_SGI_TYPE_TRAITS + +#define BOOST_STDLIB "Comeau standard library " BOOST_STRINGIZE(__LIBCOMO_VERSION__) + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/libstdcpp3.hpp b/deprecated/eo/contrib/boost/config/stdlib/libstdcpp3.hpp new file mode 100644 index 000000000..f367fa0f1 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/libstdcpp3.hpp @@ -0,0 +1,61 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright Jens Maurer 2001. +// 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 for most recent version. + +// config for libstdc++ v3 +// not much to go in here: + +#ifdef __GLIBCXX__ +#define BOOST_STDLIB "GNU libstdc++ version " BOOST_STRINGIZE(__GLIBCXX__) +#else +#define BOOST_STDLIB "GNU libstdc++ version " BOOST_STRINGIZE(__GLIBCPP__) +#endif + +#if !defined(_GLIBCPP_USE_WCHAR_T) && !defined(_GLIBCXX_USE_WCHAR_T) +# define BOOST_NO_CWCHAR +# define BOOST_NO_CWCTYPE +# define BOOST_NO_STD_WSTRING +# define BOOST_NO_STD_WSTREAMBUF +#endif + +#if defined(__osf__) && !defined(_REENTRANT) \ + && ( defined(_GLIBCXX_HAVE_GTHR_DEFAULT) || defined(_GLIBCPP_HAVE_GTHR_DEFAULT) ) +// GCC 3 on Tru64 forces the definition of _REENTRANT when any std lib header +// file is included, therefore for consistency we define it here as well. +# define _REENTRANT +#endif + +#ifdef __GLIBCXX__ // gcc 3.4 and greater: +# ifdef _GLIBCXX_HAVE_GTHR_DEFAULT + // + // If the std lib has thread support turned on, then turn it on in Boost + // as well. We do this because some gcc-3.4 std lib headers define _REENTANT + // while others do not... + // +# define BOOST_HAS_THREADS +# else +# define BOOST_DISABLE_THREADS +# endif +#elif defined(__GLIBCPP__) && !defined(_GLIBCPP_HAVE_GTHR_DEFAULT) + // disable thread support if the std lib was built single threaded: +# define BOOST_DISABLE_THREADS +#endif + +#if (defined(linux) || defined(__linux) || defined(__linux__)) && defined(__arm__) && defined(_GLIBCPP_HAVE_GTHR_DEFAULT) +// linux on arm apparently doesn't define _REENTRANT +// so just turn on threading support whenever the std lib is thread safe: +# define BOOST_HAS_THREADS +#endif + + +#if !defined(_GLIBCPP_USE_LONG_LONG) \ + && !defined(_GLIBCXX_USE_LONG_LONG)\ + && defined(BOOST_HAS_LONG_LONG) +// May have been set by compiler/*.hpp, but "long long" without library +// support is useless. +# undef BOOST_HAS_LONG_LONG +#endif diff --git a/deprecated/eo/contrib/boost/config/stdlib/modena.hpp b/deprecated/eo/contrib/boost/config/stdlib/modena.hpp new file mode 100644 index 000000000..61e31b7d1 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/modena.hpp @@ -0,0 +1,30 @@ +// (C) Copyright Jens Maurer 2001. +// 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 for most recent version. + +// Modena C++ standard library (comes with KAI C++) + +#if !defined(MSIPL_COMPILE_H) +# include +# if !defined(__MSIPL_COMPILE_H) +# error "This is not the Modena C++ library!" +# endif +#endif + +#ifndef MSIPL_NL_TYPES +#define BOOST_NO_STD_MESSAGES +#endif + +#ifndef MSIPL_WCHART +#define BOOST_NO_STD_WSTRING +#endif + +#define BOOST_STDLIB "Modena C++ standard library" + + + + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/msl.hpp b/deprecated/eo/contrib/boost/config/stdlib/msl.hpp new file mode 100644 index 000000000..0df8e0e3b --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/msl.hpp @@ -0,0 +1,59 @@ +// (C) Copyright John Maddock 2001. +// (C) Copyright Darin Adler 2001. +// 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 for most recent version. + +// Metrowerks standard library: + +#ifndef __MSL_CPP__ +# include +# ifndef __MSL_CPP__ +# error This is not the MSL standard library! +# endif +#endif + +#if __MSL_CPP__ >= 0x6000 // Pro 6 +# define BOOST_HAS_HASH +# define BOOST_STD_EXTENSION_NAMESPACE Metrowerks +#endif +#define BOOST_HAS_SLIST + +#if __MSL_CPP__ < 0x6209 +# define BOOST_NO_STD_MESSAGES +#endif + +// check C lib version for +#include + +#if defined(__MSL__) && (__MSL__ >= 0x5000) +# define BOOST_HAS_STDINT_H +# if !defined(__PALMOS_TRAPS__) +# define BOOST_HAS_UNISTD_H +# endif + // boilerplate code: +# include +#endif + +#if defined(_MWMT) || _MSL_THREADSAFE +# define BOOST_HAS_THREADS +#endif + +#ifdef _MSL_NO_EXPLICIT_FUNC_TEMPLATE_ARG +# define BOOST_NO_STD_USE_FACET +# define BOOST_HAS_TWO_ARG_USE_FACET +#endif + + +#define BOOST_STDLIB "Metrowerks Standard Library version " BOOST_STRINGIZE(__MSL_CPP__) + + + + + + + + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/roguewave.hpp b/deprecated/eo/contrib/boost/config/stdlib/roguewave.hpp new file mode 100644 index 000000000..b331f6538 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/roguewave.hpp @@ -0,0 +1,127 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001. +// (C) Copyright David Abrahams 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) + +// See http://www.boost.org for most recent version. + +// Rogue Wave std lib: + +#if !defined(__STD_RWCOMPILER_H__) && !defined(_RWSTD_VER) +# include +# if !defined(__STD_RWCOMPILER_H__) && !defined(_RWSTD_VER) +# error This is not the Rogue Wave standard library +# endif +#endif +// +// figure out a consistent version number: +// +#ifndef _RWSTD_VER +# define BOOST_RWSTD_VER 0x010000 +#elif _RWSTD_VER < 0x010000 +# define BOOST_RWSTD_VER (_RWSTD_VER << 8) +#else +# define BOOST_RWSTD_VER _RWSTD_VER +#endif + +#ifndef _RWSTD_VER +# define BOOST_STDLIB "Rogue Wave standard library version (Unknown version)" +#else +# define BOOST_STDLIB "Rogue Wave standard library version " BOOST_STRINGIZE(_RWSTD_VER) +#endif + +// +// Prior to version 2.2.0 the primary template for std::numeric_limits +// does not have compile time constants, even though specializations of that +// template do: +// +#if BOOST_RWSTD_VER < 0x020200 +# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +#endif + +// Sun CC 5.5 patch 113817-07 adds long long specialization, but does not change the +// library version number (http://sunsolve6.sun.com/search/document.do?assetkey=1-21-113817): +#if BOOST_RWSTD_VER <= 0x020101 && (!defined(__SUNPRO_CC) || (__SUNPRO_CC < 0x550)) +# define BOOST_NO_LONG_LONG_NUMERIC_LIMITS +# endif + +// +// Borland version of numeric_limits lacks __int64 specialisation: +// +#ifdef __BORLANDC__ +# define BOOST_NO_MS_INT64_NUMERIC_LIMITS +#endif + +// +// No std::iterator if it can't figure out default template args: +// +#if defined(_RWSTD_NO_SIMPLE_DEFAULT_TEMPLATES) || defined(RWSTD_NO_SIMPLE_DEFAULT_TEMPLATES) || (BOOST_RWSTD_VER < 0x020000) +# define BOOST_NO_STD_ITERATOR +#endif + +// +// No iterator traits without partial specialization: +// +#if defined(_RWSTD_NO_CLASS_PARTIAL_SPEC) || defined(RWSTD_NO_CLASS_PARTIAL_SPEC) +# define BOOST_NO_STD_ITERATOR_TRAITS +#endif + +// +// Prior to version 2.0, std::auto_ptr was buggy, and there were no +// new-style iostreams, and no conformant std::allocator: +// +#if (BOOST_RWSTD_VER < 0x020000) +# define BOOST_NO_AUTO_PTR +# define BOOST_NO_STRINGSTREAM +# define BOOST_NO_STD_ALLOCATOR +# define BOOST_NO_STD_LOCALE +#endif + +// +// No template iterator constructors without member template support: +// +#if defined(RWSTD_NO_MEMBER_TEMPLATES) || defined(_RWSTD_NO_MEMBER_TEMPLATES) +# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS +#endif + +// +// RW defines _RWSTD_ALLOCATOR if the allocator is conformant and in use +// (the or _HPACC_ part is a hack - the library seems to define _RWSTD_ALLOCATOR +// on HP aCC systems even though the allocator is in fact broken): +// +#if !defined(_RWSTD_ALLOCATOR) || (defined(__HP_aCC) && __HP_aCC <= 33100) +# define BOOST_NO_STD_ALLOCATOR +#endif + +// +// If we have a std::locale, we still may not have std::use_facet: +// +#if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) && !defined(BOOST_NO_STD_LOCALE) +# define BOOST_NO_STD_USE_FACET +# define BOOST_HAS_TWO_ARG_USE_FACET +#endif + +// +// There's no std::distance prior to version 2, or without +// partial specialization support: +// +#if (BOOST_RWSTD_VER < 0x020000) || defined(_RWSTD_NO_CLASS_PARTIAL_SPEC) + #define BOOST_NO_STD_DISTANCE +#endif + +// +// Some versions of the rogue wave library don't have assignable +// OutputIterators: +// +#if BOOST_RWSTD_VER < 0x020100 +# define BOOST_NO_STD_OUTPUT_ITERATOR_ASSIGN +#endif + +// +// Disable BOOST_HAS_LONG_LONG when the library has no support for it. +// +#if !defined(_RWSTD_LONG_LONG) && defined(BOOST_HAS_LONG_LONG) +# undef BOOST_HAS_LONG_LONG +#endif diff --git a/deprecated/eo/contrib/boost/config/stdlib/sgi.hpp b/deprecated/eo/contrib/boost/config/stdlib/sgi.hpp new file mode 100644 index 000000000..67f7a0a4b --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/sgi.hpp @@ -0,0 +1,111 @@ +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001. +// (C) Copyright Jens Maurer 2001 - 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) + +// See http://www.boost.org for most recent version. + +// generic SGI STL: + +#if !defined(__STL_CONFIG_H) +# include +# if !defined(__STL_CONFIG_H) +# error "This is not the SGI STL!" +# endif +#endif + +// +// No std::iterator traits without partial specialisation: +// +#if !defined(__STL_CLASS_PARTIAL_SPECIALIZATION) +# define BOOST_NO_STD_ITERATOR_TRAITS +#endif + +// +// No std::stringstream with gcc < 3 +// +#if defined(__GNUC__) && (__GNUC__ < 3) && \ + ((__GNUC_MINOR__ < 95) || (__GNUC_MINOR__ == 96)) && \ + !defined(__STL_USE_NEW_IOSTREAMS) || \ + defined(__APPLE_CC__) + // Note that we only set this for GNU C++ prior to 2.95 since the + // latest patches for that release do contain a minimal + // If you are running a 2.95 release prior to 2.95.3 then this will need + // setting, but there is no way to detect that automatically (other + // than by running the configure script). + // Also, the unofficial GNU C++ 2.96 included in RedHat 7.1 doesn't + // have . +# define BOOST_NO_STRINGSTREAM +#endif + +// +// Assume no std::locale without own iostreams (this may be an +// incorrect assumption in some cases): +// +#if !defined(__SGI_STL_OWN_IOSTREAMS) && !defined(__STL_USE_NEW_IOSTREAMS) +# define BOOST_NO_STD_LOCALE +#endif + +// +// Original native SGI streams have non-standard std::messages facet: +// +#if defined(__sgi) && (_COMPILER_VERSION <= 650) && !defined(__SGI_STL_OWN_IOSTREAMS) +# define BOOST_NO_STD_LOCALE +#endif + +// +// SGI's new iostreams have missing "const" in messages<>::open +// +#if defined(__sgi) && (_COMPILER_VERSION <= 740) && defined(__STL_USE_NEW_IOSTREAMS) +# define BOOST_NO_STD_MESSAGES +#endif + +// +// No template iterator constructors, or std::allocator +// without member templates: +// +#if !defined(__STL_MEMBER_TEMPLATES) +# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS +# define BOOST_NO_STD_ALLOCATOR +#endif + +// +// We always have SGI style hash_set, hash_map, and slist: +// +#define BOOST_HAS_HASH +#define BOOST_HAS_SLIST + +// +// If this is GNU libstdc++2, then no and no std::wstring: +// +#if (defined(__GNUC__) && (__GNUC__ < 3)) +# include +# if defined(__BASTRING__) +# define BOOST_NO_LIMITS +// Note: will provide compile-time constants +# undef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +# define BOOST_NO_STD_WSTRING +# endif +#endif + +// +// There is no standard iterator unless we have namespace support: +// +#if !defined(__STL_USE_NAMESPACES) +# define BOOST_NO_STD_ITERATOR +#endif + +// +// Intrinsic type_traits support. +// The SGI STL has it's own __type_traits class, which +// has intrinsic compiler support with SGI's compilers. +// Whatever map SGI style type traits to boost equivalents: +// +#define BOOST_HAS_SGI_TYPE_TRAITS + +#define BOOST_STDLIB "SGI standard library" + + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/stlport.hpp b/deprecated/eo/contrib/boost/config/stdlib/stlport.hpp new file mode 100644 index 000000000..4843ea59b --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/stlport.hpp @@ -0,0 +1,201 @@ +// (C) Copyright John Maddock 2001 - 2002. +// (C) Copyright Darin Adler 2001. +// (C) Copyright Jens Maurer 2001. +// 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 for most recent version. + +// STLPort standard library config: + +#if !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION) +# include +# if !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION) +# error "This is not STLPort!" +# endif +#endif + +// +// __STL_STATIC_CONST_INIT_BUG implies BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +// for versions prior to 4.1(beta) +// +#if (defined(__STL_STATIC_CONST_INIT_BUG) || defined(_STLP_STATIC_CONST_INIT_BUG)) && (__SGI_STL_PORT <= 0x400) +# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +#endif + +// +// If STLport thinks that there is no partial specialisation, then there is no +// std::iterator traits: +// +#if !(defined(_STLP_CLASS_PARTIAL_SPECIALIZATION) || defined(__STL_CLASS_PARTIAL_SPECIALIZATION)) +# define BOOST_NO_STD_ITERATOR_TRAITS +#endif + +// +// No new style iostreams on GCC without STLport's iostreams enabled: +// +#if (defined(__GNUC__) && (__GNUC__ < 3)) && !(defined(__SGI_STL_OWN_IOSTREAMS) || defined(_STLP_OWN_IOSTREAMS)) +# define BOOST_NO_STRINGSTREAM +#endif + +// +// No new iostreams implies no std::locale, and no std::stringstream: +// +#if defined(__STL_NO_IOSTREAMS) || defined(__STL_NO_NEW_IOSTREAMS) || defined(_STLP_NO_IOSTREAMS) || defined(_STLP_NO_NEW_IOSTREAMS) +# define BOOST_NO_STD_LOCALE +# define BOOST_NO_STRINGSTREAM +#endif + +// +// If the streams are not native, and we have a "using ::x" compiler bug +// then the io stream facets are not available in namespace std:: +// +#ifdef _STLPORT_VERSION +# if !defined(_STLP_OWN_IOSTREAMS) && defined(_STLP_USE_NAMESPACES) && defined(BOOST_NO_USING_TEMPLATE) && !defined(__BORLANDC__) +# define BOOST_NO_STD_LOCALE +# endif +#else +# if !defined(__SGI_STL_OWN_IOSTREAMS) && defined(__STL_USE_NAMESPACES) && defined(BOOST_NO_USING_TEMPLATE) && !defined(__BORLANDC__) +# define BOOST_NO_STD_LOCALE +# endif +#endif + +// +// Without member template support enabled, their are no template +// iterate constructors, and no std::allocator: +// +#if !(defined(__STL_MEMBER_TEMPLATES) || defined(_STLP_MEMBER_TEMPLATES)) +# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS +# define BOOST_NO_STD_ALLOCATOR +#endif +// +// however we always have at least a partial allocator: +// +#define BOOST_HAS_PARTIAL_STD_ALLOCATOR + +#if !defined(_STLP_MEMBER_TEMPLATE_CLASSES) +# define BOOST_NO_STD_ALLOCATOR +#endif + +#if defined(_STLP_NO_MEMBER_TEMPLATE_KEYWORD) && defined(BOOST_MSVC) && (BOOST_MSVC <= 1300) +# define BOOST_NO_STD_ALLOCATOR +#endif + +// +// If STLport thinks there is no wchar_t at all, then we have to disable +// the support for the relevant specilazations of std:: templates. +// +#if !defined(_STLP_HAS_WCHAR_T) && !defined(_STLP_WCHAR_T_IS_USHORT) +# ifndef BOOST_NO_STD_WSTRING +# define BOOST_NO_STD_WSTRING +# endif +# ifndef BOOST_NO_STD_WSTREAMBUF +# define BOOST_NO_STD_WSTREAMBUF +# endif +#endif + +// +// We always have SGI style hash_set, hash_map, and slist: +// +#define BOOST_HAS_HASH +#define BOOST_HAS_SLIST + +// +// STLport does a good job of importing names into namespace std::, +// but doesn't always get them all, define BOOST_NO_STDC_NAMESPACE, since our +// workaround does not conflict with STLports: +// +// +// Harold Howe says: +// Borland switched to STLport in BCB6. Defining BOOST_NO_STDC_NAMESPACE with +// BCB6 does cause problems. If we detect C++ Builder, then don't define +// BOOST_NO_STDC_NAMESPACE +// +#if !defined(__BORLANDC__) && !defined(__DMC__) +// +// If STLport is using it's own namespace, and the real names are in +// the global namespace, then we duplicate STLport's using declarations +// (by defining BOOST_NO_STDC_NAMESPACE), we do this because STLport doesn't +// necessarily import all the names we need into namespace std:: +// +# if (defined(__STL_IMPORT_VENDOR_CSTD) \ + || defined(__STL_USE_OWN_NAMESPACE) \ + || defined(_STLP_IMPORT_VENDOR_CSTD) \ + || defined(_STLP_USE_OWN_NAMESPACE)) \ + && (defined(__STL_VENDOR_GLOBAL_CSTD) || defined (_STLP_VENDOR_GLOBAL_CSTD)) +# define BOOST_NO_STDC_NAMESPACE +# define BOOST_NO_EXCEPTION_STD_NAMESPACE +# endif +#elif defined(__BORLANDC__) && __BORLANDC__ < 0x560 +// STLport doesn't import std::abs correctly: +#include +namespace std { using ::abs; } +// and strcmp/strcpy don't get imported either ('cos they are macros) +#include +#ifdef strcpy +# undef strcpy +#endif +#ifdef strcmp +# undef strcmp +#endif +#ifdef _STLP_VENDOR_CSTD +namespace std{ using _STLP_VENDOR_CSTD::strcmp; using _STLP_VENDOR_CSTD::strcpy; } +#endif +#endif + +// +// std::use_facet may be non-standard, uses a class instead: +// +#if defined(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) || defined(_STLP_NO_EXPLICIT_FUNCTION_TMPL_ARGS) +# define BOOST_NO_STD_USE_FACET +# define BOOST_HAS_STLP_USE_FACET +#endif + +// +// If STLport thinks there are no wide functions, etc. is not working; but +// only if BOOST_NO_STDC_NAMESPACE is not defined (if it is then we do the import +// into std:: ourselves). +// +#if defined(_STLP_NO_NATIVE_WIDE_FUNCTIONS) && !defined(BOOST_NO_STDC_NAMESPACE) +# define BOOST_NO_CWCHAR +# define BOOST_NO_CWCTYPE +#endif + +// +// If STLport for some reason was configured so that it thinks that wchar_t +// is not an intrinsic type, then we have to disable the support for it as +// well (we would be missing required specializations otherwise). +// +#if !defined( _STLP_HAS_WCHAR_T) || defined(_STLP_WCHAR_T_IS_USHORT) +# undef BOOST_NO_INTRINSIC_WCHAR_T +# define BOOST_NO_INTRINSIC_WCHAR_T +#endif + +// +// Borland ships a version of STLport with C++ Builder 6 that lacks +// hashtables and the like: +// +#if defined(__BORLANDC__) && (__BORLANDC__ == 0x560) +# undef BOOST_HAS_HASH +#endif + +// +// gcc-2.95.3/STLPort does not like the using declarations we use to get ADL with std::min/max +// +#if defined(__GNUC__) && (__GNUC__ < 3) +# include // for std::min and std::max +# define BOOST_USING_STD_MIN() ((void)0) +# define BOOST_USING_STD_MAX() ((void)0) +namespace boost { using std::min; using std::max; } +#endif + +#define BOOST_STDLIB "STLPort standard library version " BOOST_STRINGIZE(__SGI_STL_PORT) + + + + + + + + diff --git a/deprecated/eo/contrib/boost/config/stdlib/vacpp.hpp b/deprecated/eo/contrib/boost/config/stdlib/vacpp.hpp new file mode 100644 index 000000000..8321ee0cc --- /dev/null +++ b/deprecated/eo/contrib/boost/config/stdlib/vacpp.hpp @@ -0,0 +1,18 @@ +// (C) Copyright John Maddock 2001 - 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 for most recent version. + +#if __IBMCPP__ <= 501 +# define BOOST_NO_STD_ALLOCATOR +#endif + +#define BOOST_HAS_MACRO_USE_FACET +#define BOOST_NO_STD_MESSAGES + +#define BOOST_STDLIB "Visual Age default standard library" + + + diff --git a/deprecated/eo/contrib/boost/config/suffix.hpp b/deprecated/eo/contrib/boost/config/suffix.hpp new file mode 100644 index 000000000..d4d9502d4 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/suffix.hpp @@ -0,0 +1,547 @@ +// Boost config.hpp configuration header file ------------------------------// + +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright Bill Kempf 2002. +// (C) Copyright Jens Maurer 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Gennaro Prota 2003. +// (C) Copyright Eric Friedman 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) + +// See http://www.boost.org for most recent version. + +// Boost config.hpp policy and rationale documentation has been moved to +// http://www.boost.org/libs/config +// +// This file is intended to be stable, and relatively unchanging. +// It should contain boilerplate code only - no compiler specific +// code unless it is unavoidable - no changes unless unavoidable. + +#ifndef BOOST_CONFIG_SUFFIX_HPP +#define BOOST_CONFIG_SUFFIX_HPP + +// +// look for long long by looking for the appropriate macros in . +// Note that we use limits.h rather than climits for maximal portability, +// remember that since these just declare a bunch of macros, there should be +// no namespace issues from this. +// +#include +# if !defined(BOOST_HAS_LONG_LONG) \ + && !defined(BOOST_MSVC) && !defined(__BORLANDC__) \ + && (defined(ULLONG_MAX) || defined(ULONG_LONG_MAX) || defined(ULONGLONG_MAX)) +# define BOOST_HAS_LONG_LONG +#endif + +// TODO: Remove the following lines after the 1.33 release because the presence +// of an integral 64 bit type has nothing to do with support for long long. + +#if !defined(BOOST_HAS_LONG_LONG) && !defined(BOOST_NO_INTEGRAL_INT64_T) && !defined(__DECCXX_VER) +# define BOOST_NO_INTEGRAL_INT64_T +#endif + +// GCC 3.x will clean up all of those nasty macro definitions that +// BOOST_NO_CTYPE_FUNCTIONS is intended to help work around, so undefine +// it under GCC 3.x. +#if defined(__GNUC__) && (__GNUC__ >= 3) && defined(BOOST_NO_CTYPE_FUNCTIONS) +# undef BOOST_NO_CTYPE_FUNCTIONS +#endif + + +// +// Assume any extensions are in namespace std:: unless stated otherwise: +// +# ifndef BOOST_STD_EXTENSION_NAMESPACE +# define BOOST_STD_EXTENSION_NAMESPACE std +# endif + +// +// If cv-qualified specializations are not allowed, then neither are cv-void ones: +// +# if defined(BOOST_NO_CV_SPECIALIZATIONS) \ + && !defined(BOOST_NO_CV_VOID_SPECIALIZATIONS) +# define BOOST_NO_CV_VOID_SPECIALIZATIONS +# endif + +// +// If there is no numeric_limits template, then it can't have any compile time +// constants either! +// +# if defined(BOOST_NO_LIMITS) \ + && !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) +# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS +# define BOOST_NO_MS_INT64_NUMERIC_LIMITS +# define BOOST_NO_LONG_LONG_NUMERIC_LIMITS +# endif + +// +// if there is no long long then there is no specialisation +// for numeric_limits either: +// +#if !defined(BOOST_HAS_LONG_LONG) && !defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS) +# define BOOST_NO_LONG_LONG_NUMERIC_LIMITS +#endif + +// +// if there is no __int64 then there is no specialisation +// for numeric_limits<__int64> either: +// +#if !defined(BOOST_HAS_MS_INT64) && !defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS) +# define BOOST_NO_MS_INT64_NUMERIC_LIMITS +#endif + +// +// if member templates are supported then so is the +// VC6 subset of member templates: +// +# if !defined(BOOST_NO_MEMBER_TEMPLATES) \ + && !defined(BOOST_MSVC6_MEMBER_TEMPLATES) +# define BOOST_MSVC6_MEMBER_TEMPLATES +# endif + +// +// Without partial specialization, can't test for partial specialisation bugs: +// +# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ + && !defined(BOOST_BCB_PARTIAL_SPECIALIZATION_BUG) +# define BOOST_BCB_PARTIAL_SPECIALIZATION_BUG +# endif + +// +// Without partial specialization, we can't have array-type partial specialisations: +// +# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ + && !defined(BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS) +# define BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS +# endif + +// +// Without partial specialization, std::iterator_traits can't work: +// +# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ + && !defined(BOOST_NO_STD_ITERATOR_TRAITS) +# define BOOST_NO_STD_ITERATOR_TRAITS +# endif + +// +// Without member template support, we can't have template constructors +// in the standard library either: +// +# if defined(BOOST_NO_MEMBER_TEMPLATES) \ + && !defined(BOOST_MSVC6_MEMBER_TEMPLATES) \ + && !defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS) +# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS +# endif + +// +// Without member template support, we can't have a conforming +// std::allocator template either: +// +# if defined(BOOST_NO_MEMBER_TEMPLATES) \ + && !defined(BOOST_MSVC6_MEMBER_TEMPLATES) \ + && !defined(BOOST_NO_STD_ALLOCATOR) +# define BOOST_NO_STD_ALLOCATOR +# endif + +// +// without ADL support then using declarations will break ADL as well: +// +#if defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL) +# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +#endif + +// +// If we have a standard allocator, then we have a partial one as well: +// +#if !defined(BOOST_NO_STD_ALLOCATOR) +# define BOOST_HAS_PARTIAL_STD_ALLOCATOR +#endif + +// +// We can't have a working std::use_facet if there is no std::locale: +// +# if defined(BOOST_NO_STD_LOCALE) && !defined(BOOST_NO_STD_USE_FACET) +# define BOOST_NO_STD_USE_FACET +# endif + +// +// We can't have a std::messages facet if there is no std::locale: +// +# if defined(BOOST_NO_STD_LOCALE) && !defined(BOOST_NO_STD_MESSAGES) +# define BOOST_NO_STD_MESSAGES +# endif + +// +// We can't have a working std::wstreambuf if there is no std::locale: +// +# if defined(BOOST_NO_STD_LOCALE) && !defined(BOOST_NO_STD_WSTREAMBUF) +# define BOOST_NO_STD_WSTREAMBUF +# endif + +// +// We can't have a if there is no : +// +# if defined(BOOST_NO_CWCHAR) && !defined(BOOST_NO_CWCTYPE) +# define BOOST_NO_CWCTYPE +# endif + +// +// We can't have a swprintf if there is no : +// +# if defined(BOOST_NO_CWCHAR) && !defined(BOOST_NO_SWPRINTF) +# define BOOST_NO_SWPRINTF +# endif + +// +// If Win32 support is turned off, then we must turn off +// threading support also, unless there is some other +// thread API enabled: +// +#if defined(BOOST_DISABLE_WIN32) && defined(_WIN32) \ + && !defined(BOOST_DISABLE_THREADS) && !defined(BOOST_HAS_PTHREADS) +# define BOOST_DISABLE_THREADS +#endif + +// +// Turn on threading support if the compiler thinks that it's in +// multithreaded mode. We put this here because there are only a +// limited number of macros that identify this (if there's any missing +// from here then add to the appropriate compiler section): +// +#if (defined(__MT__) || defined(_MT) || defined(_REENTRANT) \ + || defined(_PTHREADS)) && !defined(BOOST_HAS_THREADS) +# define BOOST_HAS_THREADS +#endif + +// +// Turn threading support off if BOOST_DISABLE_THREADS is defined: +// +#if defined(BOOST_DISABLE_THREADS) && defined(BOOST_HAS_THREADS) +# undef BOOST_HAS_THREADS +#endif + +// +// Turn threading support off if we don't recognise the threading API: +// +#if defined(BOOST_HAS_THREADS) && !defined(BOOST_HAS_PTHREADS)\ + && !defined(BOOST_HAS_WINTHREADS) && !defined(BOOST_HAS_BETHREADS)\ + && !defined(BOOST_HAS_MPTASKS) +# undef BOOST_HAS_THREADS +#endif + +// +// Turn threading detail macros off if we don't (want to) use threading +// +#ifndef BOOST_HAS_THREADS +# undef BOOST_HAS_PTHREADS +# undef BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +# undef BOOST_HAS_WINTHREADS +# undef BOOST_HAS_BETHREADS +# undef BOOST_HAS_MPTASKS +#endif + +// +// If the compiler claims to be C99 conformant, then it had better +// have a : +// +# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) +# define BOOST_HAS_STDINT_H +# endif + +// +// Define BOOST_NO_SLIST and BOOST_NO_HASH if required. +// Note that this is for backwards compatibility only. +// +# ifndef BOOST_HAS_SLIST +# define BOOST_NO_SLIST +# endif + +# ifndef BOOST_HAS_HASH +# define BOOST_NO_HASH +# endif + +// BOOST_HAS_ABI_HEADERS +// This macro gets set if we have headers that fix the ABI, +// and prevent ODR violations when linking to external libraries: +#if defined(BOOST_ABI_PREFIX) && defined(BOOST_ABI_SUFFIX) && !defined(BOOST_HAS_ABI_HEADERS) +# define BOOST_HAS_ABI_HEADERS +#endif + +#if defined(BOOST_HAS_ABI_HEADERS) && defined(BOOST_DISABLE_ABI_HEADERS) +# undef BOOST_HAS_ABI_HEADERS +#endif + +// BOOST_NO_STDC_NAMESPACE workaround --------------------------------------// +// Because std::size_t usage is so common, even in boost headers which do not +// otherwise use the C library, the workaround is included here so +// that ugly workaround code need not appear in many other boost headers. +// NOTE WELL: This is a workaround for non-conforming compilers; +// must still be #included in the usual places so that inclusion +// works as expected with standard conforming compilers. The resulting +// double inclusion of is harmless. + +# ifdef BOOST_NO_STDC_NAMESPACE +# include + namespace std { using ::ptrdiff_t; using ::size_t; } +# endif + +// Workaround for the unfortunate min/max macros defined by some platform headers + +#define BOOST_PREVENT_MACRO_SUBSTITUTION + +#ifndef BOOST_USING_STD_MIN +# define BOOST_USING_STD_MIN() using std::min +#endif + +#ifndef BOOST_USING_STD_MAX +# define BOOST_USING_STD_MAX() using std::max +#endif + +// BOOST_NO_STD_MIN_MAX workaround -----------------------------------------// + +# ifdef BOOST_NO_STD_MIN_MAX + +namespace std { + template + inline const _Tp& min BOOST_PREVENT_MACRO_SUBSTITUTION (const _Tp& __a, const _Tp& __b) { + return __b < __a ? __b : __a; + } + template + inline const _Tp& max BOOST_PREVENT_MACRO_SUBSTITUTION (const _Tp& __a, const _Tp& __b) { + return __a < __b ? __b : __a; + } +} + +# endif + +// BOOST_STATIC_CONSTANT workaround --------------------------------------- // +// On compilers which don't allow in-class initialization of static integral +// constant members, we must use enums as a workaround if we want the constants +// to be available at compile-time. This macro gives us a convenient way to +// declare such constants. + +# ifdef BOOST_NO_INCLASS_MEMBER_INITIALIZATION +# define BOOST_STATIC_CONSTANT(type, assignment) enum { assignment } +# else +# define BOOST_STATIC_CONSTANT(type, assignment) static const type assignment +# endif + +// BOOST_USE_FACET / HAS_FACET workaround ----------------------------------// +// When the standard library does not have a conforming std::use_facet there +// are various workarounds available, but they differ from library to library. +// The same problem occurs with has_facet. +// These macros provide a consistent way to access a locale's facets. +// Usage: +// replace +// std::use_facet(loc); +// with +// BOOST_USE_FACET(Type, loc); +// Note do not add a std:: prefix to the front of BOOST_USE_FACET! +// Use for BOOST_HAS_FACET is analagous. + +#if defined(BOOST_NO_STD_USE_FACET) +# ifdef BOOST_HAS_TWO_ARG_USE_FACET +# define BOOST_USE_FACET(Type, loc) std::use_facet(loc, static_cast(0)) +# define BOOST_HAS_FACET(Type, loc) std::has_facet(loc, static_cast(0)) +# elif defined(BOOST_HAS_MACRO_USE_FACET) +# define BOOST_USE_FACET(Type, loc) std::_USE(loc, Type) +# define BOOST_HAS_FACET(Type, loc) std::_HAS(loc, Type) +# elif defined(BOOST_HAS_STLP_USE_FACET) +# define BOOST_USE_FACET(Type, loc) (*std::_Use_facet(loc)) +# define BOOST_HAS_FACET(Type, loc) std::has_facet< Type >(loc) +# endif +#else +# define BOOST_USE_FACET(Type, loc) std::use_facet< Type >(loc) +# define BOOST_HAS_FACET(Type, loc) std::has_facet< Type >(loc) +#endif + +// BOOST_NESTED_TEMPLATE workaround ------------------------------------------// +// Member templates are supported by some compilers even though they can't use +// the A::template member syntax, as a workaround replace: +// +// typedef typename A::template rebind binder; +// +// with: +// +// typedef typename A::BOOST_NESTED_TEMPLATE rebind binder; + +#ifndef BOOST_NO_MEMBER_TEMPLATE_KEYWORD +# define BOOST_NESTED_TEMPLATE template +#else +# define BOOST_NESTED_TEMPLATE +#endif + +// BOOST_UNREACHABLE_RETURN(x) workaround -------------------------------------// +// Normally evaluates to nothing, unless BOOST_NO_UNREACHABLE_RETURN_DETECTION +// is defined, in which case it evaluates to return x; Use when you have a return +// statement that can never be reached. + +#ifdef BOOST_NO_UNREACHABLE_RETURN_DETECTION +# define BOOST_UNREACHABLE_RETURN(x) return x; +#else +# define BOOST_UNREACHABLE_RETURN(x) +#endif + +// BOOST_DEDUCED_TYPENAME workaround ------------------------------------------// +// +// Some compilers don't support the use of `typename' for dependent +// types in deduced contexts, e.g. +// +// template void f(T, typename T::type); +// ^^^^^^^^ +// Replace these declarations with: +// +// template void f(T, BOOST_DEDUCED_TYPENAME T::type); + +#ifndef BOOST_NO_DEDUCED_TYPENAME +# define BOOST_DEDUCED_TYPENAME typename +#else +# define BOOST_DEDUCED_TYPENAME +#endif + +// long long workaround ------------------------------------------// +// On gcc (and maybe other compilers?) long long is alway supported +// but it's use may generate either warnings (with -ansi), or errors +// (with -pedantic -ansi) unless it's use is prefixed by __extension__ +// +#if defined(BOOST_HAS_LONG_LONG) +namespace boost{ +# ifdef __GNUC__ + __extension__ typedef long long long_long_type; + __extension__ typedef unsigned long long ulong_long_type; +# else + typedef long long long_long_type; + typedef unsigned long long ulong_long_type; +# endif +} +#endif + +// BOOST_[APPEND_]EXPLICIT_TEMPLATE_[NON_]TYPE macros --------------------------// +// +// Some compilers have problems with function templates whose +// template parameters don't appear in the function parameter +// list (basically they just link one instantiation of the +// template in the final executable). These macros provide a +// uniform way to cope with the problem with no effects on the +// calling syntax. + +// Example: +// +// #include +// #include +// #include +// +// template +// void f() { std::cout << n << ' '; } +// +// template +// void g() { std::cout << typeid(T).name() << ' '; } +// +// int main() { +// f<1>(); +// f<2>(); +// +// g(); +// g(); +// } +// +// With VC++ 6.0 the output is: +// +// 2 2 double double +// +// To fix it, write +// +// template +// void f(BOOST_EXPLICIT_TEMPLATE_NON_TYPE(int, n)) { ... } +// +// template +// void g(BOOST_EXPLICIT_TEMPLATE_TYPE(T)) { ... } +// + + +#if defined BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS + +# include "boost/type.hpp" +# include "boost/non_type.hpp" + +# define BOOST_EXPLICIT_TEMPLATE_TYPE(t) boost::type* = 0 +# define BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) boost::type* +# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v) boost::non_type* = 0 +# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) boost::non_type* + +# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(t) \ + , BOOST_EXPLICIT_TEMPLATE_TYPE(t) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) \ + , BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) \ + , BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) \ + , BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) + +#else + +// no workaround needed: expand to nothing + +# define BOOST_EXPLICIT_TEMPLATE_TYPE(t) +# define BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) +# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v) +# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) + +# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(t) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) + + +#endif // defined BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS + + +// ---------------------------------------------------------------------------// + +// +// Helper macro BOOST_STRINGIZE: +// Converts the parameter X to a string after macro replacement +// on X has been performed. +// +#define BOOST_STRINGIZE(X) BOOST_DO_STRINGIZE(X) +#define BOOST_DO_STRINGIZE(X) #X + +// +// Helper macro BOOST_JOIN: +// The following piece of macro magic joins the two +// arguments together, even when one of the arguments is +// itself a macro (see 16.3.1 in C++ standard). The key +// is that macro expansion of macro arguments does not +// occur in BOOST_DO_JOIN2 but does in BOOST_DO_JOIN. +// +#define BOOST_JOIN( X, Y ) BOOST_DO_JOIN( X, Y ) +#define BOOST_DO_JOIN( X, Y ) BOOST_DO_JOIN2(X,Y) +#define BOOST_DO_JOIN2( X, Y ) X##Y + +// +// Set some default values for compiler/library/platform names. +// These are for debugging config setup only: +// +# ifndef BOOST_COMPILER +# define BOOST_COMPILER "Unknown ISO C++ Compiler" +# endif +# ifndef BOOST_STDLIB +# define BOOST_STDLIB "Unknown ISO standard library" +# endif +# ifndef BOOST_PLATFORM +# if defined(unix) || defined(__unix) || defined(_XOPEN_SOURCE) \ + || defined(_POSIX_SOURCE) +# define BOOST_PLATFORM "Generic Unix" +# else +# define BOOST_PLATFORM "Unknown" +# endif +# endif + +#endif + + + diff --git a/deprecated/eo/contrib/boost/config/user.hpp b/deprecated/eo/contrib/boost/config/user.hpp new file mode 100644 index 000000000..5a4a9d477 --- /dev/null +++ b/deprecated/eo/contrib/boost/config/user.hpp @@ -0,0 +1,124 @@ +// boost/config/user.hpp ---------------------------------------------------// + +// (C) Copyright John Maddock 2001. +// 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) + +// Do not check in modified versions of this file, +// This file may be customized by the end user, but not by boost. + +// +// Use this file to define a site and compiler specific +// configuration policy: +// + +// define this to locate a compiler config file: +// #define BOOST_COMPILER_CONFIG + +// define this to locate a stdlib config file: +// #define BOOST_STDLIB_CONFIG + +// define this to locate a platform config file: +// #define BOOST_PLATFORM_CONFIG + +// define this to disable compiler config, +// use if your compiler config has nothing to set: +// #define BOOST_NO_COMPILER_CONFIG + +// define this to disable stdlib config, +// use if your stdlib config has nothing to set: +// #define BOOST_NO_STDLIB_CONFIG + +// define this to disable platform config, +// use if your platform config has nothing to set: +// #define BOOST_NO_PLATFORM_CONFIG + +// define this to disable all config options, +// excluding the user config. Use if your +// setup is fully ISO compliant, and has no +// useful extensions, or for autoconf generated +// setups: +// #define BOOST_NO_CONFIG + +// define this to make the config "optimistic" +// about unknown compiler versions. Normally +// unknown compiler versions are assumed to have +// all the defects of the last known version, however +// setting this flag, causes the config to assume +// that unknown compiler versions are fully conformant +// with the standard: +// #define BOOST_STRICT_CONFIG + +// define this to cause the config to halt compilation +// with an #error if it encounters anything unknown -- +// either an unknown compiler version or an unknown +// compiler/platform/library: +// #define BOOST_ASSERT_CONFIG + + +// define if you want to disable threading support, even +// when available: +// #define BOOST_DISABLE_THREADS + +// define when you want to disable Win32 specific features +// even when available: +// #define BOOST_DISABLE_WIN32 + +// BOOST_DISABLE_ABI_HEADERS: Stops boost headers from including any +// prefix/suffix headers that normally control things like struct +// packing and alignment. +// #define BOOST_DISABLE_ABI_HEADERS + +// BOOST_ABI_PREFIX: A prefix header to include in place of whatever +// boost.config would normally select, any replacement should set up +// struct packing and alignment options as required. +// #define BOOST_ABI_PREFIX my-header-name + +// BOOST_ABI_SUFFIX: A suffix header to include in place of whatever +// boost.config would normally select, any replacement should undo +// the effects of the prefix header. +// #define BOOST_ABI_SUFFIX my-header-name + +// BOOST_ALL_DYN_LINK: Forces all libraries that have separate source, +// to be linked as dll's rather than static libraries on Microsoft Windows +// (this macro is used to turn on __declspec(dllimport) modifiers, so that +// the compiler knows which symbols to look for in a dll rather than in a +// static library). Note that there may be some libraries that can only +// be statically linked (Boost.Test for example) and others which may only +// be dynamically linked (Boost.Threads for example), in these cases this +// macro has no effect. +// #define BOOST_ALL_DYN_LINK + +// BOOST_WHATEVER_DYN_LINK: Forces library "whatever" to be linked as a dll +// rather than a static library on Microsoft Windows: replace the WHATEVER +// part of the macro name with the name of the library that you want to +// dynamically link to, for example use BOOST_DATE_TIME_DYN_LINK or +// BOOST_REGEX_DYN_LINK etc (this macro is used to turn on __declspec(dllimport) +// modifiers, so that the compiler knows which symbols to look for in a dll +// rather than in a static library). +// Note that there may be some libraries that can only be statically linked +// (Boost.Test for example) and others which may only be dynamically linked +// (Boost.Threads for example), in these cases this macro is unsupported. +// #define BOOST_WHATEVER_DYN_LINK + +// BOOST_ALL_NO_LIB: Tells the config system not to automatically select +// which libraries to link against. +// Normally if a compiler supports #pragma lib, then the correct library +// build variant will be automatically selected and linked against, +// simply by the act of including one of that library's headers. +// This macro turns that feature off. +// #define BOOST_ALL_NO_LIB + +// BOOST_WHATEVER_NO_LIB: Tells the config system not to automatically +// select which library to link against for library "whatever", +// replace WHATEVER in the macro name with the name of the library; +// for example BOOST_DATE_TIME_NO_LIB or BOOST_REGEX_NO_LIB. +// Normally if a compiler supports #pragma lib, then the correct library +// build variant will be automatically selected and linked against, simply +// by the act of including one of that library's headers. This macro turns +// that feature off. +// #define BOOST_WHATEVER_NO_LIB + + + diff --git a/deprecated/eo/contrib/boost/limits.hpp b/deprecated/eo/contrib/boost/limits.hpp new file mode 100644 index 000000000..856072085 --- /dev/null +++ b/deprecated/eo/contrib/boost/limits.hpp @@ -0,0 +1,142 @@ +// (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) +// +// use this header as a workaround for missing + +// See http://www.boost.org/libs/utility/limits.html for documentation. + +#ifndef BOOST_LIMITS +#define BOOST_LIMITS + +#include + +#ifdef BOOST_NO_LIMITS +# include +#else +# include +#endif + +#if (defined(BOOST_HAS_LONG_LONG) && defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS)) \ + || (defined(BOOST_HAS_MS_INT64) && defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS)) +// Add missing specializations for numeric_limits: +#ifdef BOOST_HAS_MS_INT64 +# define BOOST_LLT __int64 +# define BOOST_ULLT unsigned __int64 +#else +# define BOOST_LLT ::boost::long_long_type +# define BOOST_ULLT ::boost::ulong_long_type +#endif + +namespace std +{ + template<> + class numeric_limits + { + public: + + BOOST_STATIC_CONSTANT(bool, is_specialized = true); +#ifdef BOOST_HAS_MS_INT64 + static BOOST_LLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return 0x8000000000000000i64; } + static BOOST_LLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return 0x7FFFFFFFFFFFFFFFi64; } +#elif defined(LLONG_MAX) + static BOOST_LLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return LLONG_MIN; } + static BOOST_LLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return LLONG_MAX; } +#elif defined(LONGLONG_MAX) + static BOOST_LLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return LONGLONG_MIN; } + static BOOST_LLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return LONGLONG_MAX; } +#else + static BOOST_LLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return 1LL << (sizeof(BOOST_LLT) * CHAR_BIT - 1); } + static BOOST_LLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return ~(min)(); } +#endif + BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT -1); + BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT) - 1) * 301L / 1000); + BOOST_STATIC_CONSTANT(bool, is_signed = true); + BOOST_STATIC_CONSTANT(bool, is_integer = true); + BOOST_STATIC_CONSTANT(bool, is_exact = true); + BOOST_STATIC_CONSTANT(int, radix = 2); + static BOOST_LLT epsilon() throw() { return 0; }; + static BOOST_LLT round_error() throw() { return 0; }; + + BOOST_STATIC_CONSTANT(int, min_exponent = 0); + BOOST_STATIC_CONSTANT(int, min_exponent10 = 0); + BOOST_STATIC_CONSTANT(int, max_exponent = 0); + BOOST_STATIC_CONSTANT(int, max_exponent10 = 0); + + BOOST_STATIC_CONSTANT(bool, has_infinity = false); + BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false); + BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false); + BOOST_STATIC_CONSTANT(bool, has_denorm = false); + BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false); + static BOOST_LLT infinity() throw() { return 0; }; + static BOOST_LLT quiet_NaN() throw() { return 0; }; + static BOOST_LLT signaling_NaN() throw() { return 0; }; + static BOOST_LLT denorm_min() throw() { return 0; }; + + BOOST_STATIC_CONSTANT(bool, is_iec559 = false); + BOOST_STATIC_CONSTANT(bool, is_bounded = false); + BOOST_STATIC_CONSTANT(bool, is_modulo = false); + + 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 + { + public: + + BOOST_STATIC_CONSTANT(bool, is_specialized = true); +#ifdef BOOST_HAS_MS_INT64 + static BOOST_ULLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return 0ui64; } + static BOOST_ULLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return 0xFFFFFFFFFFFFFFFFui64; } +#elif defined(ULLONG_MAX) && defined(ULLONG_MIN) + static BOOST_ULLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return ULLONG_MIN; } + static BOOST_ULLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return ULLONG_MAX; } +#elif defined(ULONGLONG_MAX) && defined(ULONGLONG_MIN) + static BOOST_ULLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return ULONGLONG_MIN; } + static BOOST_ULLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return ULONGLONG_MAX; } +#else + static BOOST_ULLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return 0uLL; } + static BOOST_ULLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return ~0uLL; } +#endif + BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT); + BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT)) * 301L / 1000); + BOOST_STATIC_CONSTANT(bool, is_signed = false); + BOOST_STATIC_CONSTANT(bool, is_integer = true); + BOOST_STATIC_CONSTANT(bool, is_exact = true); + BOOST_STATIC_CONSTANT(int, radix = 2); + static BOOST_ULLT epsilon() throw() { return 0; }; + static BOOST_ULLT round_error() throw() { return 0; }; + + BOOST_STATIC_CONSTANT(int, min_exponent = 0); + BOOST_STATIC_CONSTANT(int, min_exponent10 = 0); + BOOST_STATIC_CONSTANT(int, max_exponent = 0); + BOOST_STATIC_CONSTANT(int, max_exponent10 = 0); + + BOOST_STATIC_CONSTANT(bool, has_infinity = false); + BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false); + BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false); + BOOST_STATIC_CONSTANT(bool, has_denorm = false); + BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false); + static BOOST_ULLT infinity() throw() { return 0; }; + static BOOST_ULLT quiet_NaN() throw() { return 0; }; + static BOOST_ULLT signaling_NaN() throw() { return 0; }; + static BOOST_ULLT denorm_min() throw() { return 0; }; + + BOOST_STATIC_CONSTANT(bool, is_iec559 = false); + BOOST_STATIC_CONSTANT(bool, is_bounded = false); + BOOST_STATIC_CONSTANT(bool, is_modulo = false); + + 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 diff --git a/deprecated/eo/contrib/boost/numeric/interval.hpp b/deprecated/eo/contrib/boost/numeric/interval.hpp new file mode 100644 index 000000000..e6f976df0 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval.hpp @@ -0,0 +1,32 @@ +/* Boost interval.hpp header file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_HPP +#define BOOST_NUMERIC_INTERVAL_HPP + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#endif // BOOST_NUMERIC_INTERVAL_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/arith.hpp b/deprecated/eo/contrib/boost/numeric/interval/arith.hpp new file mode 100644 index 000000000..64a8e97ee --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/arith.hpp @@ -0,0 +1,305 @@ +/* Boost interval/arith.hpp template implementation file + * + * Copyright 2000 Jens Maurer + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_ARITH_HPP +#define BOOST_NUMERIC_INTERVAL_ARITH_HPP + +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace numeric { + +/* + * Basic arithmetic operators + */ + +template inline +const interval& operator+(const interval& x) +{ + return x; +} + +template inline +interval operator-(const interval& x) +{ + if (interval_lib::detail::test_input(x)) + return interval::empty(); + return interval(-x.upper(), -x.lower(), true); +} + +template inline +interval& interval::operator+=(const interval& r) +{ + if (interval_lib::detail::test_input(*this, r)) + set_empty(); + else { + typename Policies::rounding rnd; + set(rnd.add_down(low, r.low), rnd.add_up(up, r.up)); + } + return *this; +} + +template inline +interval& interval::operator+=(const T& r) +{ + if (interval_lib::detail::test_input(*this, r)) + set_empty(); + else { + typename Policies::rounding rnd; + set(rnd.add_down(low, r), rnd.add_up(up, r)); + } + return *this; +} + +template inline +interval& interval::operator-=(const interval& r) +{ + if (interval_lib::detail::test_input(*this, r)) + set_empty(); + else { + typename Policies::rounding rnd; + set(rnd.sub_down(low, r.up), rnd.sub_up(up, r.low)); + } + return *this; +} + +template inline +interval& interval::operator-=(const T& r) +{ + if (interval_lib::detail::test_input(*this, r)) + set_empty(); + else { + typename Policies::rounding rnd; + set(rnd.sub_down(low, r), rnd.sub_up(up, r)); + } + return *this; +} + +template inline +interval& interval::operator*=(const interval& r) +{ + return *this = *this * r; +} + +template inline +interval& interval::operator*=(const T& r) +{ + return *this = r * *this; +} + +template inline +interval& interval::operator/=(const interval& r) +{ + return *this = *this / r; +} + +template inline +interval& interval::operator/=(const T& r) +{ + return *this = *this / r; +} + +template inline +interval operator+(const interval& x, + const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + return interval(rnd.add_down(x.lower(), y.lower()), + rnd.add_up (x.upper(), y.upper()), true); +} + +template inline +interval operator+(const T& x, const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + return interval(rnd.add_down(x, y.lower()), + rnd.add_up (x, y.upper()), true); +} + +template inline +interval operator+(const interval& x, const T& y) +{ return y + x; } + +template inline +interval operator-(const interval& x, + const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + return interval(rnd.sub_down(x.lower(), y.upper()), + rnd.sub_up (x.upper(), y.lower()), true); +} + +template inline +interval operator-(const T& x, const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + return interval(rnd.sub_down(x, y.upper()), + rnd.sub_up (x, y.lower()), true); +} + +template inline +interval operator-(const interval& x, const T& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + return interval(rnd.sub_down(x.lower(), y), + rnd.sub_up (x.upper(), y), true); +} + +template inline +interval operator*(const interval& x, + const interval& y) +{ + BOOST_USING_STD_MIN(); + BOOST_USING_STD_MAX(); + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + typename Policies::rounding rnd; + const T& xl = x.lower(); + const T& xu = x.upper(); + const T& yl = y.lower(); + const T& yu = y.upper(); + + if (interval_lib::user::is_neg(xl)) + if (interval_lib::user::is_pos(xu)) + if (interval_lib::user::is_neg(yl)) + if (interval_lib::user::is_pos(yu)) // M * M + return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(rnd.mul_down(xl, yu), rnd.mul_down(xu, yl)), + max BOOST_PREVENT_MACRO_SUBSTITUTION(rnd.mul_up (xl, yl), rnd.mul_up (xu, yu)), true); + else // M * N + return I(rnd.mul_down(xu, yl), rnd.mul_up(xl, yl), true); + else + if (interval_lib::user::is_pos(yu)) // M * P + return I(rnd.mul_down(xl, yu), rnd.mul_up(xu, yu), true); + else // M * Z + return I(static_cast(0), static_cast(0), true); + else + if (interval_lib::user::is_neg(yl)) + if (interval_lib::user::is_pos(yu)) // N * M + return I(rnd.mul_down(xl, yu), rnd.mul_up(xl, yl), true); + else // N * N + return I(rnd.mul_down(xu, yu), rnd.mul_up(xl, yl), true); + else + if (interval_lib::user::is_pos(yu)) // N * P + return I(rnd.mul_down(xl, yu), rnd.mul_up(xu, yl), true); + else // N * Z + return I(static_cast(0), static_cast(0), true); + else + if (interval_lib::user::is_pos(xu)) + if (interval_lib::user::is_neg(yl)) + if (interval_lib::user::is_pos(yu)) // P * M + return I(rnd.mul_down(xu, yl), rnd.mul_up(xu, yu), true); + else // P * N + return I(rnd.mul_down(xu, yl), rnd.mul_up(xl, yu), true); + else + if (interval_lib::user::is_pos(yu)) // P * P + return I(rnd.mul_down(xl, yl), rnd.mul_up(xu, yu), true); + else // P * Z + return I(static_cast(0), static_cast(0), true); + else // Z * ? + return I(static_cast(0), static_cast(0), true); +} + +template inline +interval operator*(const T& x, const interval& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + typename Policies::rounding rnd; + const T& yl = y.lower(); + const T& yu = y.upper(); + // x is supposed not to be infinite + if (interval_lib::user::is_neg(x)) + return I(rnd.mul_down(x, yu), rnd.mul_up(x, yl), true); + else if (interval_lib::user::is_zero(x)) + return I(static_cast(0), static_cast(0), true); + else + return I(rnd.mul_down(x, yl), rnd.mul_up(x, yu), true); +} + +template inline +interval operator*(const interval& x, const T& y) +{ return y * x; } + +template inline +interval operator/(const interval& x, + const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + if (in_zero(y)) + if (!interval_lib::user::is_zero(y.lower())) + if (!interval_lib::user::is_zero(y.upper())) + return interval_lib::detail::div_zero(x); + else + return interval_lib::detail::div_negative(x, y.lower()); + else + if (!interval_lib::user::is_zero(y.upper())) + return interval_lib::detail::div_positive(x, y.upper()); + else + return interval::empty(); + else + return interval_lib::detail::div_non_zero(x, y); +} + +template inline +interval operator/(const T& x, const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + if (in_zero(y)) + if (!interval_lib::user::is_zero(y.lower())) + if (!interval_lib::user::is_zero(y.upper())) + return interval_lib::detail::div_zero(x); + else + return interval_lib::detail::div_negative(x, y.lower()); + else + if (!interval_lib::user::is_zero(y.upper())) + return interval_lib::detail::div_positive(x, y.upper()); + else + return interval::empty(); + else + return interval_lib::detail::div_non_zero(x, y); +} + +template inline +interval operator/(const interval& x, const T& y) +{ + if (interval_lib::detail::test_input(x, y) || interval_lib::user::is_zero(y)) + return interval::empty(); + typename Policies::rounding rnd; + const T& xl = x.lower(); + const T& xu = x.upper(); + if (interval_lib::user::is_neg(y)) + return interval(rnd.div_down(xu, y), rnd.div_up(xl, y), true); + else + return interval(rnd.div_down(xl, y), rnd.div_up(xu, y), true); +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_ARITH_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/arith2.hpp b/deprecated/eo/contrib/boost/numeric/interval/arith2.hpp new file mode 100644 index 000000000..274a68119 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/arith2.hpp @@ -0,0 +1,212 @@ +/* Boost interval/arith2.hpp template implementation file + * + * This header provides some auxiliary arithmetic + * functions: fmod, sqrt, square, pov, inverse and + * a multi-interval division. + * + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_ARITH2_HPP +#define BOOST_NUMERIC_INTERVAL_ARITH2_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace numeric { + +template inline +interval fmod(const interval& x, + const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + typedef typename interval_lib::unprotect >::type I; + T const &yb = interval_lib::user::is_neg(x.lower()) ? y.lower() : y.upper(); + T n = rnd.int_down(rnd.div_down(x.lower(), yb)); + return (const I&)x - n * (const I&)y; +} + +template inline +interval fmod(const interval& x, const T& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + typedef typename interval_lib::unprotect >::type I; + T n = rnd.int_down(rnd.div_down(x.lower(), y)); + return (const I&)x - n * I(y); +} + +template inline +interval fmod(const T& x, const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + typename Policies::rounding rnd; + typedef typename interval_lib::unprotect >::type I; + T const &yb = interval_lib::user::is_neg(x) ? y.lower() : y.upper(); + T n = rnd.int_down(rnd.div_down(x, yb)); + return x - n * (const I&)y; +} + +namespace interval_lib { + +template inline +interval division_part1(const interval& x, + const interval& y, bool& b) +{ + typedef interval I; + b = false; + if (detail::test_input(x, y)) + return I::empty(); + if (in_zero(y)) + if (!user::is_zero(y.lower())) + if (!user::is_zero(y.upper())) + return detail::div_zero_part1(x, y, b); + else + return detail::div_negative(x, y.lower()); + else + if (!user::is_zero(y.upper())) + return detail::div_positive(x, y.upper()); + else + return I::empty(); + else + return detail::div_non_zero(x, y); +} + +template inline +interval division_part2(const interval& x, + const interval& y, bool b = true) +{ + if (!b) return interval::empty(); + return detail::div_zero_part2(x, y); +} + +template inline +interval multiplicative_inverse(const interval& x) +{ + typedef interval I; + if (detail::test_input(x)) + return I::empty(); + T one = static_cast(1); + typename Policies::rounding rnd; + if (in_zero(x)) { + typedef typename Policies::checking checking; + if (!user::is_zero(x.lower())) + if (!user::is_zero(x.upper())) + return I::whole(); + else + return I(checking::neg_inf(), rnd.div_up(one, x.lower()), true); + else + if (!user::is_zero(x.upper())) + return I(rnd.div_down(one, x.upper()), checking::pos_inf(), true); + else + return I::empty(); + } else + return I(rnd.div_down(one, x.upper()), rnd.div_up(one, x.lower()), true); +} + +namespace detail { + +template inline +T pow_aux(const T& x_, int pwr, Rounding& rnd) // x and pwr are positive +{ + T x = x_; + T y = (pwr & 1) ? x_ : static_cast(1); + pwr >>= 1; + while (pwr > 0) { + x = rnd.mul_up(x, x); + if (pwr & 1) y = rnd.mul_up(x, y); + pwr >>= 1; + } + return y; +} + +} // namespace detail +} // namespace interval_lib + +template inline +interval pow(const interval& x, int pwr) +{ + BOOST_USING_STD_MAX(); + using interval_lib::detail::pow_aux; + typedef interval I; + + if (interval_lib::detail::test_input(x)) + return I::empty(); + + if (pwr == 0) + if (interval_lib::user::is_zero(x.lower()) + && interval_lib::user::is_zero(x.upper())) + return I::empty(); + else + return I(static_cast(1)); + else if (pwr < 0) + return interval_lib::multiplicative_inverse(pow(x, -pwr)); + + typename Policies::rounding rnd; + + if (interval_lib::user::is_neg(x.upper())) { // [-2,-1] + T yl = pow_aux(-x.upper(), pwr, rnd); + T yu = pow_aux(-x.lower(), pwr, rnd); + if (pwr & 1) // [-2,-1]^1 + return I(-yu, -yl, true); + else // [-2,-1]^2 + return I(yl, yu, true); + } else if (interval_lib::user::is_neg(x.lower())) { // [-1,1] + if (pwr & 1) { // [-1,1]^1 + return I(-pow_aux(-x.lower(), pwr, rnd), pow_aux(x.upper(), pwr, rnd), true); + } else { // [-1,1]^2 + return I(static_cast(0), pow_aux(max BOOST_PREVENT_MACRO_SUBSTITUTION(-x.lower(), x.upper()), pwr, rnd), true); + } + } else { // [1,2] + return I(pow_aux(x.lower(), pwr, rnd), pow_aux(x.upper(), pwr, rnd), true); + } +} + +template inline +interval sqrt(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x) || interval_lib::user::is_neg(x.upper())) + return I::empty(); + typename Policies::rounding rnd; + T l = !interval_lib::user::is_pos(x.lower()) ? static_cast(0) : rnd.sqrt_down(x.lower()); + return I(l, rnd.sqrt_up(x.upper()), true); +} + +template inline +interval square(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + const T& xl = x.lower(); + const T& xu = x.upper(); + if (interval_lib::user::is_neg(xu)) + return I(rnd.mul_down(xu, xu), rnd.mul_up(xl, xl), true); + else if (interval_lib::user::is_pos(x.lower())) + return I(rnd.mul_down(xl, xl), rnd.mul_up(xu, xu), true); + else + return I(static_cast(0), (-xl > xu ? rnd.mul_up(xl, xl) : rnd.mul_up(xu, xu)), true); +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_ARITH2_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/arith3.hpp b/deprecated/eo/contrib/boost/numeric/interval/arith3.hpp new file mode 100644 index 000000000..518e6182f --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/arith3.hpp @@ -0,0 +1,69 @@ +/* Boost interval/arith3.hpp template implementation file + * + * This headers provides arithmetical functions + * which compute an interval given some base + * numbers. The resulting interval encloses the + * real result of the arithmetic operation. + * + * Copyright 2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_ARITH3_HPP +#define BOOST_NUMERIC_INTERVAL_ARITH3_HPP + +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { + +template inline +I add(const typename I::base_type& x, const typename I::base_type& y) +{ + typedef typename I::traits_type Policies; + if (detail::test_input(x, y)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.add_down(x, y), rnd.add_up(x, y), true); +} + +template inline +I sub(const typename I::base_type& x, const typename I::base_type& y) +{ + typedef typename I::traits_type Policies; + if (detail::test_input(x, y)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.sub_down(x, y), rnd.sub_up(x, y), true); +} + +template inline +I mul(const typename I::base_type& x, const typename I::base_type& y) +{ + typedef typename I::traits_type Policies; + if (detail::test_input(x, y)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.mul_down(x, y), rnd.mul_up(x, y), true); +} + +template inline +I div(const typename I::base_type& x, const typename I::base_type& y) +{ + typedef typename I::traits_type Policies; + if (detail::test_input(x, y) || user::is_zero(y)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.div_down(x, y), rnd.div_up(x, y), true); +} + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_ARITH3_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/checking.hpp b/deprecated/eo/contrib/boost/numeric/interval/checking.hpp new file mode 100644 index 000000000..2db486a0b --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/checking.hpp @@ -0,0 +1,130 @@ +/* Boost interval/checking.hpp template implementation file + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_CHECKING_HPP +#define BOOST_NUMERIC_INTERVAL_CHECKING_HPP + +#include +#include +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { + +struct exception_create_empty +{ + void operator()() + { + throw std::runtime_error("boost::interval: empty interval created"); + } +}; + +struct exception_invalid_number +{ + void operator()() + { + throw std::invalid_argument("boost::interval: invalid number"); + } +}; + +template +struct checking_base +{ + static T pos_inf() + { + assert(std::numeric_limits::has_infinity); + return std::numeric_limits::infinity(); + } + static T neg_inf() + { + assert(std::numeric_limits::has_infinity); + return -std::numeric_limits::infinity(); + } + static T nan() + { + assert(std::numeric_limits::has_quiet_NaN); + return std::numeric_limits::quiet_NaN(); + } + static bool is_nan(const T& x) + { + return std::numeric_limits::has_quiet_NaN && (x != x); + } + static T empty_lower() + { + return (std::numeric_limits::has_quiet_NaN ? + std::numeric_limits::quiet_NaN() : static_cast(1)); + } + static T empty_upper() + { + return (std::numeric_limits::has_quiet_NaN ? + std::numeric_limits::quiet_NaN() : static_cast(0)); + } + static bool is_empty(const T& l, const T& u) + { + return !(l <= u); // safety for partial orders + } +}; + +template, + class Exception = exception_create_empty> +struct checking_no_empty: Checking +{ + static T nan() + { + assert(false); + return Checking::nan(); + } + static T empty_lower() + { + Exception()(); + return Checking::empty_lower(); + } + static T empty_upper() + { + Exception()(); + return Checking::empty_upper(); + } + static bool is_empty(const T&, const T&) + { + return false; + } +}; + +template > +struct checking_no_nan: Checking +{ + static bool is_nan(const T&) + { + return false; + } +}; + +template, + class Exception = exception_invalid_number> +struct checking_catch_nan: Checking +{ + static bool is_nan(const T& x) + { + if (Checking::is_nan(x)) Exception()(); + return false; + } +}; + +template +struct checking_strict: + checking_no_nan > +{}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_CHECKING_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare.hpp new file mode 100644 index 000000000..f21753e71 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare.hpp @@ -0,0 +1,19 @@ +/* Boost interval/compare.hpp template implementation file + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_HPP + +#include +#include +#include +#include +#include + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare/certain.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare/certain.hpp new file mode 100644 index 000000000..9232d5cd8 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare/certain.hpp @@ -0,0 +1,113 @@ +/* Boost interval/compare/certain.hpp template implementation file + * + * Copyright 2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_CERTAIN_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_CERTAIN_HPP + +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace compare { +namespace certain { + +template inline +bool operator<(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() < y.lower(); +} + +template inline +bool operator<(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() < y; +} + +template inline +bool operator<=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() <= y.lower(); +} + +template inline +bool operator<=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() <= y; +} + +template inline +bool operator>(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() > y.upper(); +} + +template inline +bool operator>(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() > y; +} + +template inline +bool operator>=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() >= y.upper(); +} + +template inline +bool operator>=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() >= y; +} + +template inline +bool operator==(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() == y.lower() && x.lower() == y.upper(); +} + +template inline +bool operator==(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() == y && x.lower() == y; +} + +template inline +bool operator!=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() < y.lower() || x.lower() > y.upper(); +} + +template inline +bool operator!=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() < y || x.lower() > y; +} + +} // namespace certain +} // namespace compare +} // namespace interval_lib +} // namespace numeric +} // namespace boost + + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_CERTAIN_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare/explicit.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare/explicit.hpp new file mode 100644 index 000000000..8c68be891 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare/explicit.hpp @@ -0,0 +1,248 @@ +/* Boost interval/compare/explicit.hpp template implementation file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_EXPLICIT_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_EXPLICIT_HPP + +#include + +namespace boost { +namespace numeric { +namespace interval_lib { + +/* + * Certainly... operations + */ + +template inline +bool cerlt(const interval& x, const interval& y) +{ + return x.upper() < y.lower(); +} + +template inline +bool cerlt(const interval& x, const T& y) +{ + return x.upper() < y; +} + +template inline +bool cerlt(const T& x, const interval& y) +{ + return x < y.lower(); +} + +template inline +bool cerle(const interval& x, const interval& y) +{ + return x.upper() <= y.lower(); +} + +template inline +bool cerle(const interval& x, const T& y) +{ + return x.upper() <= y; +} + +template inline +bool cerle(const T& x, const interval& y) +{ + return x <= y.lower(); +} + +template inline +bool cergt(const interval& x, const interval& y) +{ + return x.lower() > y.upper(); +} + +template inline +bool cergt(const interval& x, const T& y) +{ + return x.lower() > y; +} + +template inline +bool cergt(const T& x, const interval& y) +{ + return x > y.upper(); +} + +template inline +bool cerge(const interval& x, const interval& y) +{ + return x.lower() >= y.upper(); +} + +template inline +bool cerge(const interval& x, const T& y) +{ + return x.lower() >= y; +} + +template inline +bool cerge(const T& x, const interval& y) +{ + return x >= y.upper(); +} + +template inline +bool cereq(const interval& x, const interval& y) +{ + return x.lower() == y.upper() && y.lower() == x.upper(); +} + +template inline +bool cereq(const interval& x, const T& y) +{ + return x.lower() == y && x.upper() == y; +} + +template inline +bool cereq(const T& x, const interval& y) +{ + return x == y.lower() && x == y.upper(); +} + +template inline +bool cerne(const interval& x, const interval& y) +{ + return x.upper() < y.lower() || y.upper() < x.lower(); +} + +template inline +bool cerne(const interval& x, const T& y) +{ + return x.upper() < y || y < x.lower(); +} + +template inline +bool cerne(const T& x, const interval& y) +{ + return x < y.lower() || y.upper() < x; +} + +/* + * Possibly... comparisons + */ + +template inline +bool poslt(const interval& x, const interval& y) +{ + return x.lower() < y.upper(); +} + +template inline +bool poslt(const interval& x, const T& y) +{ + return x.lower() < y; +} + +template inline +bool poslt(const T& x, const interval& y) +{ + return x < y.upper(); +} + +template inline +bool posle(const interval& x, const interval& y) +{ + return x.lower() <= y.upper(); +} + +template inline +bool posle(const interval& x, const T& y) +{ + return x.lower() <= y; +} + +template inline +bool posle(const T& x, const interval& y) +{ + return x <= y.upper(); +} + +template inline +bool posgt(const interval& x, const interval& y) +{ + return x.upper() > y.lower(); +} + +template inline +bool posgt(const interval& x, const T& y) +{ + return x.upper() > y; +} + +template inline +bool posgt(const T& x, const interval & y) +{ + return x > y.lower(); +} + +template inline +bool posge(const interval& x, const interval& y) +{ + return x.upper() >= y.lower(); +} + +template inline +bool posge(const interval& x, const T& y) +{ + return x.upper() >= y; +} + +template inline +bool posge(const T& x, const interval& y) +{ + return x >= y.lower(); +} + +template inline +bool poseq(const interval& x, const interval& y) +{ + return x.upper() >= y.lower() && y.upper() >= x.lower(); +} + +template inline +bool poseq(const interval& x, const T& y) +{ + return x.upper() >= y && y >= x.lower(); +} + +template inline +bool poseq(const T& x, const interval& y) +{ + return x >= y.lower() && y.upper() >= x; +} + +template inline +bool posne(const interval& x, const interval& y) +{ + return x.upper() != y.lower() || y.upper() != x.lower(); +} + +template inline +bool posne(const interval& x, const T& y) +{ + return x.upper() != y || y != x.lower(); +} + +template inline +bool posne(const T& x, const interval& y) +{ + return x != y.lower() || y.upper() != x; +} + +} // namespace interval_lib +} // namespace numeric +} //namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_EXPLICIT_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare/lexicographic.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare/lexicographic.hpp new file mode 100644 index 000000000..03f6036d2 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare/lexicographic.hpp @@ -0,0 +1,122 @@ +/* Boost interval/compare/lexicographic.hpp template implementation file + * + * Copyright 2002-2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_LEXICOGRAPHIC_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_LEXICOGRAPHIC_HPP + +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace compare { +namespace lexicographic { + +template inline +bool operator<(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + const T& xl = x.lower(); + const T& yl = y.lower(); + return xl < yl || (xl == yl && x.upper() < y.upper()); +} + +template inline +bool operator<(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() < y; +} + +template inline +bool operator<=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + const T& xl = x.lower(); + const T& yl = y.lower(); + return xl < yl || (xl == yl && x.upper() <= y.upper()); +} + +template inline +bool operator<=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + const T& xl = x.lower(); + return xl < y || (xl == y && x.upper() <= y); +} + +template inline +bool operator>(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + const T& xl = x.lower(); + const T& yl = y.lower(); + return xl > yl || (xl == yl && x.upper() > y.upper()); +} + +template inline +bool operator>(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + const T& xl = x.lower(); + return xl > y || (xl == y && x.upper() > y); +} + +template inline +bool operator>=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + const T& xl = x.lower(); + const T& yl = y.lower(); + return xl > yl || (xl == yl && x.upper() >= y.upper()); +} + +template inline +bool operator>=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() >= y; +} + +template inline +bool operator==(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() == y.lower() && x.upper() == y.upper(); +} + +template inline +bool operator==(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() == y && x.upper() == y; +} + +template inline +bool operator!=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() != y.lower() || x.upper() != y.upper(); +} + +template inline +bool operator!=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() != y || x.upper() != y; +} + +} // namespace lexicographic +} // namespace compare +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_LEXICOGRAPHIC_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare/possible.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare/possible.hpp new file mode 100644 index 000000000..59bec31b9 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare/possible.hpp @@ -0,0 +1,113 @@ +/* Boost interval/compare/possible.hpp template implementation file + * + * Copyright 2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_POSSIBLE_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_POSSIBLE_HPP + +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace compare { +namespace possible { + +template inline +bool operator<(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() < y.upper(); +} + +template inline +bool operator<(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() < y; +} + +template inline +bool operator<=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() <= y.upper(); +} + +template inline +bool operator<=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() <= y; +} + +template inline +bool operator>(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() > y.lower(); +} + +template inline +bool operator>(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() > y; +} + +template inline +bool operator>=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() >= y.lower(); +} + +template inline +bool operator>=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.upper() >= y; +} + +template inline +bool operator==(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() <= y.upper() && x.upper() >= y.lower(); +} + +template inline +bool operator==(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() <= y && x.upper() >= y; +} + +template inline +bool operator!=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() != y.upper() || x.upper() != y.lower(); +} + +template inline +bool operator!=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + return x.lower() != y || x.upper() != y; +} + +} // namespace possible +} // namespace compare +} // namespace interval_lib +} // namespace numeric +} // namespace boost + + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_POSSIBLE_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare/set.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare/set.hpp new file mode 100644 index 000000000..aa4f1716b --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare/set.hpp @@ -0,0 +1,101 @@ +/* Boost interval/compare/set.hpp template implementation file + * + * Copyright 2002-2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP + +#include +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace compare { +namespace set { + +template inline +bool operator<(const interval& x, const interval& y) +{ + return proper_subset(x, y); +} + +template inline +bool operator<(const interval& x, const T& y) +{ + throw comparison_error(); +} + +template inline +bool operator<=(const interval& x, const interval& y) +{ + return subset(x, y); +} + +template inline +bool operator<=(const interval& x, const T& y) +{ + throw comparison_error(); +} + +template inline +bool operator>(const interval& x, const interval& y) +{ + return proper_subset(y, x); +} + +template inline +bool operator>(const interval& x, const T& y) +{ + throw comparison_error(); +} + +template inline +bool operator>=(const interval& x, const interval& y) +{ + return subset(y, x); +} + +template inline +bool operator>=(const interval& x, const T& y) +{ + throw comparison_error(); +} + +template inline +bool operator==(const interval& x, const interval& y) +{ + return equal(y, x); +} + +template inline +bool operator==(const interval& x, const T& y) +{ + throw comparison_error(); +} + +template inline +bool operator!=(const interval& x, const interval& y) +{ + return !equal(y, x); +} + +template inline +bool operator!=(const interval& x, const T& y) +{ + throw comparison_error(); +} + +} // namespace set +} // namespace compare +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_SET_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/compare/tribool.hpp b/deprecated/eo/contrib/boost/numeric/interval/compare/tribool.hpp new file mode 100644 index 000000000..6e4a83e27 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/compare/tribool.hpp @@ -0,0 +1,138 @@ +/* Boost interval/compare/tribool.hpp template implementation file + * + * Copyright 2002-2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_TRIBOOL_HPP +#define BOOST_NUMERIC_INTERVAL_COMPARE_TRIBOOL_HPP + +#include +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace compare { +namespace tribool { + +template inline +logic::tribool operator<(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() < y.lower()) return true; + if (x.lower() >= y.upper()) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator<(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() < y) return true; + if (x.lower() >= y) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator<=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() <= y.lower()) return true; + if (x.lower() > y.upper()) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator<=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() <= y) return true; + if (x.lower() > y) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator>(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.lower() > y.upper()) return true; + if (x.upper() <= y.lower()) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator>(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.lower() > y) return true; + if (x.upper() <= y) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator>=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.lower() >= y.upper()) return true; + if (x.upper() < y.lower()) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator>=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.lower() >= y) return true; + if (x.upper() < y) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator==(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() == y.lower() && x.lower() == y.upper()) return true; + if (x.upper() < y.lower() || x.lower() > y.upper()) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator==(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() == y && x.lower() == y) return true; + if (x.upper() < y || x.lower() > y) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator!=(const interval& x, const interval& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() < y.lower() || x.lower() > y.upper()) return true; + if (x.upper() == y.lower() && x.lower() == y.upper()) return false; + return logic::indeterminate; +} + +template inline +logic::tribool operator!=(const interval& x, const T& y) +{ + if (detail::test_input(x, y)) throw comparison_error(); + if (x.upper() < y || x.lower() > y) return true; + if (x.upper() == y && x.lower() == y) return false; + return logic::indeterminate; +} + +} // namespace tribool +} // namespace compare +} // namespace interval_lib +} // namespace numeric +} // namespace boost + + +#endif // BOOST_NUMERIC_INTERVAL_COMPARE_TRIBOOL_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/constants.hpp b/deprecated/eo/contrib/boost/numeric/interval/constants.hpp new file mode 100644 index 000000000..a3a42efec --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/constants.hpp @@ -0,0 +1,85 @@ +/* Boost interval/constants.hpp template implementation file + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_CONSTANTS_HPP +#define BOOST_NUMERIC_INTERVAL_CONSTANTS_HPP + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace constants { + +// These constants should be exactly computed. +// Decimal representations wouldn't do it since the standard doesn't +// specify the rounding (even nearest) that should be used. + +static const float pi_f_l = 13176794.0f/(1<<22); +static const float pi_f_u = 13176795.0f/(1<<22); +static const double pi_d_l = (3373259426.0 + 273688.0 / (1<<21)) / (1<<30); +static const double pi_d_u = (3373259426.0 + 273689.0 / (1<<21)) / (1<<30); + +template inline T pi_lower() { return 3; } +template inline T pi_upper() { return 4; } +template inline T pi_half_lower() { return 1; } +template inline T pi_half_upper() { return 2; } +template inline T pi_twice_lower() { return 6; } +template inline T pi_twice_upper() { return 7; } + +template<> inline float pi_lower() { return pi_f_l; } +template<> inline float pi_upper() { return pi_f_u; } +template<> inline float pi_half_lower() { return pi_f_l / 2; } +template<> inline float pi_half_upper() { return pi_f_u / 2; } +template<> inline float pi_twice_lower() { return pi_f_l * 2; } +template<> inline float pi_twice_upper() { return pi_f_u * 2; } + +template<> inline double pi_lower() { return pi_d_l; } +template<> inline double pi_upper() { return pi_d_u; } +template<> inline double pi_half_lower() { return pi_d_l / 2; } +template<> inline double pi_half_upper() { return pi_d_u / 2; } +template<> inline double pi_twice_lower() { return pi_d_l * 2; } +template<> inline double pi_twice_upper() { return pi_d_u * 2; } + +template<> inline long double pi_lower() { return pi_d_l; } +template<> inline long double pi_upper() { return pi_d_u; } +template<> inline long double pi_half_lower() { return pi_d_l / 2; } +template<> inline long double pi_half_upper() { return pi_d_u / 2; } +template<> inline long double pi_twice_lower() { return pi_d_l * 2; } +template<> inline long double pi_twice_upper() { return pi_d_u * 2; } + +} // namespace constants + +template inline +I pi() +{ + typedef typename I::base_type T; + return I(constants::pi_lower(), + constants::pi_upper(), true); +} + +template inline +I pi_half() +{ + typedef typename I::base_type T; + return I(constants::pi_half_lower(), + constants::pi_half_upper(), true); +} + +template inline +I pi_twice() +{ + typedef typename I::base_type T; + return I(constants::pi_twice_lower(), + constants::pi_twice_upper(), true); +} + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_CONSTANTS_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/bcc_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/bcc_rounding_control.hpp new file mode 100644 index 000000000..e3aaf046c --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/bcc_rounding_control.hpp @@ -0,0 +1,57 @@ +/* Boost interval/detail/bcc_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_BCC_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_BCC_ROUNDING_CONTROL_HPP + +#ifndef __BORLANDC__ +# error This header is only intended for Borland C++. +#endif + +#ifndef _M_IX86 +# error This header only works on x86 CPUs. +#endif + +#include // Borland C++ rounding control + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +#ifndef BOOST_NUMERIC_INTERVAL_KEEP_EXCEPTIONS_FOR_BCC +extern "C" { unsigned int _RTLENTRY _fm_init(void); } + +struct borland_workaround { + borland_workaround() { _fm_init(); } +}; + +static borland_workaround borland_workaround_exec; +#endif // BOOST_NUMERIC_INTERVAL_KEEP_EXCEPTIONS_FOR_BCC + +__inline double rint(double) +{ __emit__(0xD9); __emit__(0xFC); /* asm FRNDINT */ } + +struct x86_rounding +{ + typedef unsigned int rounding_mode; + static void get_rounding_mode(rounding_mode& mode) + { mode = _control87(0, 0); } + static void set_rounding_mode(const rounding_mode mode) + { _control87(mode, 0xffff); } + static double to_int(const double& x) { return rint(x); } +}; + +} // namespace detail +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_BCC_ROUNDING_CONTROL_HPP */ diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/bugs.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/bugs.hpp new file mode 100644 index 000000000..2058b9aee --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/bugs.hpp @@ -0,0 +1,79 @@ +/* Boost interval/detail/bugs.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_BUGS +#define BOOST_NUMERIC_INTERVAL_DETAIL_BUGS + +#include + +#if defined(__GLIBC__) && (defined(__USE_MISC) || defined(__USE_XOPEN_EXTENDED) || defined(__USE_ISOC99)) && !defined(__ICC) +# define BOOST_HAS_INV_HYPERBOLIC +#endif + +#ifdef BOOST_NO_STDC_NAMESPACE +# define BOOST_NUMERIC_INTERVAL_using_math(a) using ::a +# ifdef BOOST_HAS_INV_HYPERBOLIC +# define BOOST_NUMERIC_INTERVAL_using_ahyp(a) using ::a +# endif +#else +# define BOOST_NUMERIC_INTERVAL_using_math(a) using std::a +# if defined(BOOST_HAS_INV_HYPERBOLIC) +# if defined(__GLIBCPP__) || defined(__GLIBCXX__) +# define BOOST_NUMERIC_INTERVAL_using_ahyp(a) using ::a +# else +# define BOOST_NUMERIC_INTERVAL_using_ahyp(a) using std::a +# endif +# endif +#endif + +#if defined(__COMO__) || defined(BOOST_INTEL) +# define BOOST_NUMERIC_INTERVAL_using_max(a) using std::a +#elif defined(BOOST_NO_STDC_NAMESPACE) +# define BOOST_NUMERIC_INTERVAL_using_max(a) using ::a +#else +# define BOOST_NUMERIC_INTERVAL_using_max(a) using std::a +#endif + +#ifndef BOOST_NUMERIC_INTERVAL_using_ahyp +# define BOOST_NUMERIC_INTERVAL_using_ahyp(a) +#endif + +#if defined(__GNUC__) && (__GNUC__ <= 2) +// cf PR c++/1981 for a description of the bug +#include +#include +namespace boost { +namespace numeric { + using std::min; + using std::max; + using std::sqrt; + using std::exp; + using std::log; + using std::cos; + using std::tan; + using std::asin; + using std::acos; + using std::atan; + using std::ceil; + using std::floor; + using std::sinh; + using std::cosh; + using std::tanh; +# undef BOOST_NUMERIC_INTERVAL_using_max +# undef BOOST_NUMERIC_INTERVAL_using_math +# define BOOST_NUMERIC_INTERVAL_using_max(a) +# define BOOST_NUMERIC_INTERVAL_using_math(a) +# undef BOOST_NUMERIC_INTERVAL_using_ahyp +# define BOOST_NUMERIC_INTERVAL_using_ahyp(a) +} // namespace numeric +} // namespace boost +#endif + +#endif // BOOST_NUMERIC_INTERVAL_DETAIL_BUGS diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/c99_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/c99_rounding_control.hpp new file mode 100644 index 000000000..181d28666 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/c99_rounding_control.hpp @@ -0,0 +1,47 @@ +/* Boost interval/detail/c99_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_C99_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_C99_ROUNDING_CONTROL_HPP + +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +struct c99_rounding_control: c99_rounding +{ + template + static T force_rounding(const T& r) { volatile T r_ = r; return r_; } +}; + +} // namespace detail + +template<> +struct rounding_control: + detail::c99_rounding_control { }; + +template<> +struct rounding_control: + detail::c99_rounding_control { }; + +template<> +struct rounding_control: + detail::c99_rounding_control { }; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE + +#endif // BOOST_NUMERIC_INTERVAL_DETAIL_C99_ROUNDING_CONTROL_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/c99sub_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/c99sub_rounding_control.hpp new file mode 100644 index 000000000..571c51fcc --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/c99sub_rounding_control.hpp @@ -0,0 +1,43 @@ +/* Boost interval/detail/c99sub_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_C99SUB_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_C99SUB_ROUNDING_CONTROL_HPP + +#include // ISO C 99 rounding mode control + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +extern "C" { double rint(double); } + +struct c99_rounding +{ + typedef int rounding_mode; + + static void set_rounding_mode(const rounding_mode mode) { fesetround(mode); } + static void get_rounding_mode(rounding_mode &mode) { mode = fegetround(); } + static void downward() { set_rounding_mode(FE_DOWNWARD); } + static void upward() { set_rounding_mode(FE_UPWARD); } + static void to_nearest() { set_rounding_mode(FE_TONEAREST); } + static void toward_zero() { set_rounding_mode(FE_TOWARDZERO); } + + template + static T to_int(const T& r) { return rint(r); } +}; + +} // namespace detail +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_DETAIL_C99SUB_ROUBDING_CONTROL_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/division.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/division.hpp new file mode 100644 index 000000000..24fb025ad --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/division.hpp @@ -0,0 +1,194 @@ +/* Boost interval/detail/division.hpp file + * + * Copyright 2003 Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_DIVISION_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_DIVISION_HPP + +#include +#include +#include +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +template inline +interval div_non_zero(const interval& x, + const interval& y) +{ + // assert(!in_zero(y)); + typename Policies::rounding rnd; + typedef interval I; + const T& xl = x.lower(); + const T& xu = x.upper(); + const T& yl = y.lower(); + const T& yu = y.upper(); + if (::boost::numeric::interval_lib::user::is_neg(xu)) + if (::boost::numeric::interval_lib::user::is_neg(yu)) + return I(rnd.div_down(xu, yl), rnd.div_up(xl, yu), true); + else + return I(rnd.div_down(xl, yl), rnd.div_up(xu, yu), true); + else if (::boost::numeric::interval_lib::user::is_neg(xl)) + if (::boost::numeric::interval_lib::user::is_neg(yu)) + return I(rnd.div_down(xu, yu), rnd.div_up(xl, yu), true); + else + return I(rnd.div_down(xl, yl), rnd.div_up(xu, yl), true); + else + if (::boost::numeric::interval_lib::user::is_neg(yu)) + return I(rnd.div_down(xu, yu), rnd.div_up(xl, yl), true); + else + return I(rnd.div_down(xl, yu), rnd.div_up(xu, yl), true); +} + +template inline +interval div_non_zero(const T& x, const interval& y) +{ + // assert(!in_zero(y)); + typename Policies::rounding rnd; + typedef interval I; + const T& yl = y.lower(); + const T& yu = y.upper(); + if (::boost::numeric::interval_lib::user::is_neg(x)) + return I(rnd.div_down(x, yl), rnd.div_up(x, yu), true); + else + return I(rnd.div_down(x, yu), rnd.div_up(x, yl), true); +} + +template inline +interval div_positive(const interval& x, const T& yu) +{ + // assert(::boost::numeric::interval_lib::user::is_pos(yu)); + if (::boost::numeric::interval_lib::user::is_zero(x.lower()) && + ::boost::numeric::interval_lib::user::is_zero(x.upper())) + return x; + typename Policies::rounding rnd; + typedef interval I; + const T& xl = x.lower(); + const T& xu = x.upper(); + typedef typename Policies::checking checking; + if (::boost::numeric::interval_lib::user::is_neg(xu)) + return I(checking::neg_inf(), rnd.div_up(xu, yu), true); + else if (::boost::numeric::interval_lib::user::is_neg(xl)) + return I(checking::neg_inf(), checking::pos_inf(), true); + else + return I(rnd.div_down(xl, yu), checking::pos_inf(), true); +} + +template inline +interval div_positive(const T& x, const T& yu) +{ + // assert(::boost::numeric::interval_lib::user::is_pos(yu)); + typedef interval I; + if (::boost::numeric::interval_lib::user::is_zero(x)) + return I(static_cast(0), static_cast(0), true); + typename Policies::rounding rnd; + typedef typename Policies::checking checking; + if (::boost::numeric::interval_lib::user::is_neg(x)) + return I(checking::neg_inf(), rnd.div_up(x, yu), true); + else + return I(rnd.div_down(x, yu), checking::pos_inf(), true); +} + +template inline +interval div_negative(const interval& x, const T& yl) +{ + // assert(::boost::numeric::interval_lib::user::is_neg(yl)); + if (::boost::numeric::interval_lib::user::is_zero(x.lower()) && + ::boost::numeric::interval_lib::user::is_zero(x.upper())) + return x; + typename Policies::rounding rnd; + typedef interval I; + const T& xl = x.lower(); + const T& xu = x.upper(); + typedef typename Policies::checking checking; + if (::boost::numeric::interval_lib::user::is_neg(xu)) + return I(rnd.div_down(xu, yl), checking::pos_inf(), true); + else if (::boost::numeric::interval_lib::user::is_neg(xl)) + return I(checking::neg_inf(), checking::pos_inf(), true); + else + return I(checking::neg_inf(), rnd.div_up(xl, yl), true); +} + +template inline +interval div_negative(const T& x, const T& yl) +{ + // assert(::boost::numeric::interval_lib::user::is_neg(yl)); + typedef interval I; + if (::boost::numeric::interval_lib::user::is_zero(x)) + return I(static_cast(0), static_cast(0), true); + typename Policies::rounding rnd; + typedef typename Policies::checking checking; + if (::boost::numeric::interval_lib::user::is_neg(x)) + return I(rnd.div_down(x, yl), checking::pos_inf(), true); + else + return I(checking::neg_inf(), rnd.div_up(x, yl), true); +} + +template inline +interval div_zero(const interval& x) +{ + if (::boost::numeric::interval_lib::user::is_zero(x.lower()) && + ::boost::numeric::interval_lib::user::is_zero(x.upper())) + return x; + else return interval::whole(); +} + +template inline +interval div_zero(const T& x) +{ + if (::boost::numeric::interval_lib::user::is_zero(x)) + return interval(static_cast(0), static_cast(0), true); + else return interval::whole(); +} + +template inline +interval div_zero_part1(const interval& x, + const interval& y, bool& b) +{ + // assert(::boost::numeric::interval_lib::user::is_neg(y.lower()) && ::boost::numeric::interval_lib::user::is_pos(y.upper())); + if (::boost::numeric::interval_lib::user::is_zero(x.lower()) && ::boost::numeric::interval_lib::user::is_zero(x.upper())) + { b = false; return x; } + typename Policies::rounding rnd; + typedef interval I; + const T& xl = x.lower(); + const T& xu = x.upper(); + const T& yl = y.lower(); + const T& yu = y.upper(); + typedef typename Policies::checking checking; + if (::boost::numeric::interval_lib::user::is_neg(xu)) + { b = true; return I(checking::neg_inf(), rnd.div_up(xu, yu), true); } + else if (::boost::numeric::interval_lib::user::is_neg(xl)) + { b = false; return I(checking::neg_inf(), checking::pos_inf(), true); } + else + { b = true; return I(checking::neg_inf(), rnd.div_up(xl, yl), true); } +} + +template inline +interval div_zero_part2(const interval& x, + const interval& y) +{ + // assert(::boost::numeric::interval_lib::user::is_neg(y.lower()) && ::boost::numeric::interval_lib::user::is_pos(y.upper()) && (div_zero_part1(x, y, b), b)); + typename Policies::rounding rnd; + typedef interval I; + typedef typename Policies::checking checking; + if (::boost::numeric::interval_lib::user::is_neg(x.upper())) + return I(rnd.div_down(x.upper(), y.lower()), checking::pos_inf(), true); + else + return I(rnd.div_down(x.lower(), y.upper()), checking::pos_inf(), true); +} + +} // namespace detail +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_DETAIL_DIVISION_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/interval_prototype.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/interval_prototype.hpp new file mode 100644 index 000000000..ac9029b70 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/interval_prototype.hpp @@ -0,0 +1,41 @@ +/* Boost interval/detail/interval_prototype.hpp file + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_INTERVAL_PROTOTYPE_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_INTERVAL_PROTOTYPE_HPP + +namespace boost { +namespace numeric { + +namespace interval_lib { + +template struct rounded_math; +template struct checking_strict; +class comparison_error; +template struct policies; + +/* + * default policies class + */ + +template +struct default_policies +{ + typedef policies, checking_strict > type; +}; + +} // namespace interval_lib + +template::type > +class interval; + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_DETAIL_INTERVAL_PROTOTYPE_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/msvc_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/msvc_rounding_control.hpp new file mode 100644 index 000000000..2068c934c --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/msvc_rounding_control.hpp @@ -0,0 +1,88 @@ +/* Boost interval/detail/msvc_rounding_control.hpp file + * + * Copyright 2000 Maarten Keijzer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_MSVC_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_MSVC_ROUNDING_CONTROL_HPP + +#ifndef _MSC_VER +# error This header is only intended for MSVC, but might work for Borland as well +#endif + +#include // MSVC rounding control + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +extern "C" { double rint(double); } + +struct x86_rounding +{ + static unsigned int hard2msvc(unsigned short m) { + unsigned int n = 0; + if (m & 0x01) n |= _EM_INVALID; + if (m & 0x02) n |= _EM_DENORMAL; + if (m & 0x04) n |= _EM_ZERODIVIDE; + if (m & 0x08) n |= _EM_OVERFLOW; + if (m & 0x10) n |= _EM_UNDERFLOW; + if (m & 0x20) n |= _EM_INEXACT; + switch (m & 0x300) { + case 0x000: n |= _PC_24; break; + case 0x200: n |= _PC_53; break; + case 0x300: n |= _PC_64; break; + } + switch (m & 0xC00) { + case 0x000: n |= _RC_NEAR; break; + case 0x400: n |= _RC_DOWN; break; + case 0x800: n |= _RC_UP; break; + case 0xC00: n |= _RC_CHOP; break; + } + if (m & 0x1000) n |= _IC_AFFINE; // only useful on 287 + return n; + } + + static unsigned short msvc2hard(unsigned int n) { + unsigned short m = 0; + if (n & _EM_INVALID) m |= 0x01; + if (n & _EM_DENORMAL) m |= 0x02; + if (n & _EM_ZERODIVIDE) m |= 0x04; + if (n & _EM_OVERFLOW) m |= 0x08; + if (n & _EM_UNDERFLOW) m |= 0x10; + if (n & _EM_INEXACT) m |= 0x20; + switch (n & _MCW_RC) { + case _RC_NEAR: m |= 0x000; break; + case _RC_DOWN: m |= 0x400; break; + case _RC_UP: m |= 0x800; break; + case _RC_CHOP: m |= 0xC00; break; + } + switch (n & _MCW_PC) { + case _PC_24: m |= 0x000; break; + case _PC_53: m |= 0x200; break; + case _PC_64: m |= 0x300; break; + } + if ((n & _MCW_IC) == _IC_AFFINE) m |= 0x1000; + return m; + } + + typedef unsigned short rounding_mode; + static void get_rounding_mode(rounding_mode& mode) + { mode = msvc2hard(_control87(0, 0)); } + static void set_rounding_mode(const rounding_mode mode) + { _control87(hard2msvc(mode), _MCW_EM | _MCW_RC | _MCW_PC | _MCW_IC); } + static double to_int(const double& x) { return rint(x); } +}; + +} // namespace detail +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_MSVC_ROUNDING_CONTROL_HPP */ diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/ppc_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/ppc_rounding_control.hpp new file mode 100644 index 000000000..400522a75 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/ppc_rounding_control.hpp @@ -0,0 +1,95 @@ +/* Boost interval/detail/ppc_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * Copyright 2005 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_PPC_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_PPC_ROUNDING_CONTROL_HPP + +#if !defined(powerpc) && !defined(__powerpc__) && !defined(__ppc__) +#error This header only works on PPC CPUs. +#endif + +#if defined(__GNUC__ ) || (__IBMCPP__ >= 700) + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +typedef union { + ::boost::long_long_type imode; + double dmode; +} rounding_mode_struct; + +static const rounding_mode_struct mode_upward = { 0xFFF8000000000002LL }; +static const rounding_mode_struct mode_downward = { 0xFFF8000000000003LL }; +static const rounding_mode_struct mode_to_nearest = { 0xFFF8000000000001LL }; +static const rounding_mode_struct mode_toward_zero = { 0xFFF8000000000000LL }; + +struct ppc_rounding_control +{ + typedef double rounding_mode; + + static void set_rounding_mode(const rounding_mode mode) + { __asm__ __volatile__ ("mtfsf 255,%0" : : "f"(mode)); } + + static void get_rounding_mode(rounding_mode& mode) + { __asm__ __volatile__ ("mffs %0" : "=f"(mode)); } + + static void downward() { set_rounding_mode(mode_downward.dmode); } + static void upward() { set_rounding_mode(mode_upward.dmode); } + static void to_nearest() { set_rounding_mode(mode_to_nearest.dmode); } + static void toward_zero() { set_rounding_mode(mode_toward_zero.dmode); } +}; + +} // namespace detail + +extern "C" { + float rintf(float); + double rint(double); +} + +template<> +struct rounding_control: + detail::ppc_rounding_control +{ + static float force_rounding(const float r) + { + float tmp; + __asm__ __volatile__ ("frsp %0, %1" : "=f" (tmp) : "f" (r)); + return tmp; + } + static float to_int(const float& x) { return rintf(x); } +}; + +template<> +struct rounding_control: + detail::ppc_rounding_control +{ + static const double & force_rounding(const double& r) { return r; } + static double to_int(const double& r) { return rint(r); } +}; + +template<> +struct rounding_control: + detail::ppc_rounding_control +{ + static const long double & force_rounding(const long double& r) { return r; } + static long double to_int(const long double& r) { return rint(r); } +}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE +#endif + +#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_PPC_ROUNDING_CONTROL_HPP */ diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/sparc_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/sparc_rounding_control.hpp new file mode 100644 index 000000000..6ba5baf03 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/sparc_rounding_control.hpp @@ -0,0 +1,112 @@ +/* Boost interval/detail/sparc_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + * + * The basic code in this file was kindly provided by Jeremy Siek. + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_SPARC_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_SPARC_ROUNDING_CONTROL_HPP + +#if !defined(sparc) && !defined(__sparc__) +# error This header is only intended for SPARC CPUs. +#endif + +#ifdef __SUNPRO_CC +# include +#endif + + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +struct sparc_rounding_control +{ + typedef unsigned int rounding_mode; + + static void set_rounding_mode(const rounding_mode& mode) + { +# if defined(__GNUC__) + __asm__ __volatile__("ld %0, %%fsr" : : "m"(mode)); +# elif defined (__SUNPRO_CC) + fpsetround(fp_rnd(mode)); +# elif defined(__KCC) + asm("sethi %hi(mode), %o1"); + asm("ld [%o1+%lo(mode)], %fsr"); +# else +# error Unsupported compiler for Sparc rounding control. +# endif + } + + static void get_rounding_mode(rounding_mode& mode) + { +# if defined(__GNUC__) + __asm__ __volatile__("st %%fsr, %0" : "=m"(mode)); +# elif defined (__SUNPRO_CC) + mode = fpgetround(); +# elif defined(__KCC) +# error KCC on Sun SPARC get_round_mode: please fix me + asm("st %fsr, [mode]"); +# else +# error Unsupported compiler for Sparc rounding control. +# endif + } + +#if defined(__SUNPRO_CC) + static void downward() { set_rounding_mode(FP_RM); } + static void upward() { set_rounding_mode(FP_RP); } + static void to_nearest() { set_rounding_mode(FP_RN); } + static void toward_zero() { set_rounding_mode(FP_RZ); } +#else + static void downward() { set_rounding_mode(0xc0000000); } + static void upward() { set_rounding_mode(0x80000000); } + static void to_nearest() { set_rounding_mode(0x00000000); } + static void toward_zero() { set_rounding_mode(0x40000000); } +#endif +}; + +} // namespace detail + +extern "C" { + float rintf(float); + double rint(double); +} + +template<> +struct rounding_control: + detail::sparc_rounding_control +{ + static const float& force_rounding(const float& x) { return x; } + static float to_int(const float& x) { return rintf(x); } +}; + +template<> +struct rounding_control: + detail::sparc_rounding_control +{ + static const double& force_rounding(const double& x) { return x; } + static double to_int(const double& x) { return rint(x); } +}; + +template<> +struct rounding_control: + detail::sparc_rounding_control +{ + static const long double& force_rounding(const long double& x) { return x; } + static long double to_int(const long double& x) { return rint(x); } +}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE + +#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_SPARC_ROUNDING_CONTROL_HPP */ diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/test_input.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/test_input.hpp new file mode 100644 index 000000000..58695fec3 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/test_input.hpp @@ -0,0 +1,76 @@ +/* Boost interval/detail/test_input.hpp file + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_TEST_INPUT_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_TEST_INPUT_HPP + +#include + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace user { + +template inline +bool is_zero(T const &v) { return v == static_cast(0); } + +template inline +bool is_neg (T const &v) { return v < static_cast(0); } + +template inline +bool is_pos (T const &v) { return v > static_cast(0); } + +} // namespace user + +namespace detail { + +template inline +bool test_input(const interval& x) { + typedef typename Policies::checking checking; + return checking::is_empty(x.lower(), x.upper()); +} + +template inline +bool test_input(const interval& x, const interval& y) { + typedef typename Policies1::checking checking1; + typedef typename Policies2::checking checking2; + return checking1::is_empty(x.lower(), x.upper()) || + checking2::is_empty(y.lower(), y.upper()); +} + +template inline +bool test_input(const T& x, const interval& y) { + typedef typename Policies::checking checking; + return checking::is_nan(x) || checking::is_empty(y.lower(), y.upper()); +} + +template inline +bool test_input(const interval& x, const T& y) { + typedef typename Policies::checking checking; + return checking::is_empty(x.lower(), x.upper()) || checking::is_nan(y); +} + +template inline +bool test_input(const T& x) { + typedef typename Policies::checking checking; + return checking::is_nan(x); +} + +template inline +bool test_input(const T& x, const T& y) { + typedef typename Policies::checking checking; + return checking::is_nan(x) || checking::is_nan(y); +} + +} // namespace detail +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_DETAIL_TEST_INPUT_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/x86_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/x86_rounding_control.hpp new file mode 100644 index 000000000..3eebdbac5 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/x86_rounding_control.hpp @@ -0,0 +1,108 @@ +/* Boost interval/detail/x86_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_X86_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_X86_ROUNDING_CONTROL_HPP + +#ifdef __GNUC__ +# include +#elif defined(__BORLANDC__) +# include +#elif defined(_MSC_VER) +# include +#elif defined(__MWERKS__) || defined(__ICC) +# define BOOST_NUMERIC_INTERVAL_USE_C99_SUBSYSTEM +# include +#else +# error Unsupported C++ compiler. +#endif + +namespace boost { +namespace numeric { +namespace interval_lib { + +namespace detail { + +#ifdef BOOST_NUMERIC_INTERVAL_USE_C99_SUBSYSTEM +typedef c99_rounding x86_rounding_control; +#undef BOOST_NUMERIC_INTERVAL_USE_C99_SUBSYSTEM +#else +struct fpu_rounding_modes +{ + unsigned short to_nearest; + unsigned short downward; + unsigned short upward; + unsigned short toward_zero; +}; + +// exceptions masked, extended precision +// hardware default is 0x037f (0x1000 only has a meaning on 287) +static const fpu_rounding_modes rnd_mode = { 0x137f, 0x177f, 0x1b7f, 0x1f7f }; + +struct x86_rounding_control: x86_rounding +{ + static void to_nearest() { set_rounding_mode(rnd_mode.to_nearest); } + static void downward() { set_rounding_mode(rnd_mode.downward); } + static void upward() { set_rounding_mode(rnd_mode.upward); } + static void toward_zero() { set_rounding_mode(rnd_mode.toward_zero); } +}; +#endif // BOOST_NUMERIC_INTERVAL_USE_C99_SUBSYSTEM + +} // namespace detail + +template<> +struct rounding_control: detail::x86_rounding_control +{ + static float force_rounding(const float& r) + { volatile float r_ = r; return r_; } +}; + +template<> +struct rounding_control: detail::x86_rounding_control +{ + /*static double force_rounding(double r) + { asm volatile ("" : "+m"(r) : ); return r; }*/ + static double force_rounding(const double& r) + { volatile double r_ = r; return r_; } +}; + +namespace detail { + +template +struct x86_rounding_control_long_double; + +template<> +struct x86_rounding_control_long_double: x86_rounding_control +{ + static long double force_rounding(long double const &r) + { volatile long double r_ = r; return r_; } +}; + +template<> +struct x86_rounding_control_long_double: x86_rounding_control +{ + static long double const &force_rounding(long double const &r) + { return r; } +}; + +} // namespace detail + +template<> +struct rounding_control: + detail::x86_rounding_control_long_double< (sizeof(long double) >= 10) > +{}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE + +#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_X86_ROUNDING_CONTROL_HPP */ diff --git a/deprecated/eo/contrib/boost/numeric/interval/detail/x86gcc_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/detail/x86gcc_rounding_control.hpp new file mode 100644 index 000000000..079d681df --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/detail/x86gcc_rounding_control.hpp @@ -0,0 +1,51 @@ +/* Boost interval/detail/x86gcc_rounding_control.hpp file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_DETAIL_X86GCC_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_DETAIL_X86GCC_ROUNDING_CONTROL_HPP + +#ifndef __GNUC__ +# error This header only works with GNU CC. +#endif + +#ifndef __i386__ +# error This header only works on x86 CPUs. +#endif + +namespace boost { +namespace numeric { +namespace interval_lib { +namespace detail { + +struct x86_rounding +{ + typedef unsigned short rounding_mode; + + static void set_rounding_mode(const rounding_mode& mode) + { __asm__ __volatile__ ("fldcw %0" : : "m"(mode)); } + + static void get_rounding_mode(rounding_mode& mode) + { __asm__ __volatile__ ("fnstcw %0" : "=m"(mode)); } + + template + static T to_int(T r) + { + T r_; + __asm__ ("frndint" : "=&t"(r_) : "0"(r)); + return r_; + } +}; + +} // namespace detail +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_X86GCC_ROUNDING_CONTROL_HPP */ diff --git a/deprecated/eo/contrib/boost/numeric/interval/ext/integer.hpp b/deprecated/eo/contrib/boost/numeric/interval/ext/integer.hpp new file mode 100644 index 000000000..628a343ac --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/ext/integer.hpp @@ -0,0 +1,70 @@ +/* Boost interval/ext/integer.hpp template implementation file + * + * Copyright 2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_EXT_INTEGER_HPP +#define BOOST_NUMERIC_INTERVAL_EXT_INTEGER_HPP + +#include +#include + +namespace boost { +namespace numeric { + +template inline +interval operator+ (const interval& x, int y) +{ + return x + static_cast(y); +} + +template inline +interval operator+ (int x, const interval& y) +{ + return static_cast(x) + y; +} + +template inline +interval operator- (const interval& x, int y) +{ + return x - static_cast(y); +} + +template inline +interval operator- (int x, const interval& y) +{ + return static_cast(x) - y; +} + +template inline +interval operator* (const interval& x, int y) +{ + return x * static_cast(y); +} + +template inline +interval operator* (int x, const interval& y) +{ + return static_cast(x) * y; +} + +template inline +interval operator/ (const interval& x, int y) +{ + return x / static_cast(y); +} + +template inline +interval operator/ (int x, const interval& y) +{ + return static_cast(x) / y; +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_EXT_INTEGER_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/ext/x86_fast_rounding_control.hpp b/deprecated/eo/contrib/boost/numeric/interval/ext/x86_fast_rounding_control.hpp new file mode 100644 index 000000000..7f89a4e54 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/ext/x86_fast_rounding_control.hpp @@ -0,0 +1,70 @@ +/* Boost interval/detail/x86gcc_rounding_control.hpp file + * + * This header provides a rounding control policy + * that avoids flushing results to memory. In + * order for this optimization to be reliable, it + * should be used only when no underflow or + * overflow would happen without it. Indeed, only + * values in range are correctly rounded. + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_EXT_X86_FAST_ROUNDING_CONTROL_HPP +#define BOOST_NUMERIC_INTERVAL_EXT_X86_FAST_ROUNDING_CONTROL_HPP + +namespace boost { +namespace numeric { +namespace interval_lib { + +namespace detail { + +// exceptions masked, expected precision (the mask is 0x0300) +static const fpu_rounding_modes rnd_mode_f = { 0x107f, 0x147f, 0x187f, 0x1c7f }; +static const fpu_rounding_modes rnd_mode_d = { 0x127f, 0x167f, 0x1a7f, 0x1e7f }; +static const fpu_rounding_modes rnd_mode_l = { 0x137f, 0x177f, 0x1b7f, 0x1f7f }; + +} // namespace detail + +template +struct x86_fast_rounding_control; + +template<> +struct x86_fast_rounding_control: detail::x86_rounding +{ + static void to_nearest() { set_rounding_mode(detail::rnd_mode_f.to_nearest); } + static void downward() { set_rounding_mode(detail::rnd_mode_f.downward); } + static void upward() { set_rounding_mode(detail::rnd_mode_f.upward); } + static void toward_zero() { set_rounding_mode(detail::rnd_mode_f.toward_zero); } + static const float& force_rounding(const float& r) { return r; } +}; + +template<> +struct x86_fast_rounding_control: detail::x86_rounding +{ + static void to_nearest() { set_rounding_mode(detail::rnd_mode_d.to_nearest); } + static void downward() { set_rounding_mode(detail::rnd_mode_d.downward); } + static void upward() { set_rounding_mode(detail::rnd_mode_d.upward); } + static void toward_zero() { set_rounding_mode(detail::rnd_mode_d.toward_zero); } + static const double& force_rounding(const double& r) { return r; } +}; + +template<> +struct x86_fast_rounding_control: detail::x86_rounding +{ + static void to_nearest() { set_rounding_mode(detail::rnd_mode_l.to_nearest); } + static void downward() { set_rounding_mode(detail::rnd_mode_l.downward); } + static void upward() { set_rounding_mode(detail::rnd_mode_l.upward); } + static void toward_zero() { set_rounding_mode(detail::rnd_mode_l.toward_zero); } + static const long double& force_rounding(const long double& r) { return r; } +}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_EXT_X86_FAST_ROUNDING_CONTROL_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/hw_rounding.hpp b/deprecated/eo/contrib/boost/numeric/interval/hw_rounding.hpp new file mode 100644 index 000000000..ed225d405 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/hw_rounding.hpp @@ -0,0 +1,64 @@ +/* Boost interval/hw_rounding.hpp template implementation file + * + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * Copyright 2005 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_HW_ROUNDING_HPP +#define BOOST_NUMERIC_INTERVAL_HW_ROUNDING_HPP + +#include +#include + +#define BOOST_NUMERIC_INTERVAL_NO_HARDWARE + +// define appropriate specialization of rounding_control for built-in types +#if defined(__i386__) || defined(_M_IX86) || defined(__BORLANDC__) +# include +#elif defined(powerpc) || defined(__powerpc__) || defined(__ppc__) +# include +#elif defined(sparc) || defined(__sparc__) +# include +#endif + +#if defined(BOOST_NUMERIC_INTERVAL_NO_HARDWARE) && (defined(__USE_ISOC99) || defined(__MSL__)) +# include +#endif + +#if defined(BOOST_NUMERIC_INTERVAL_NO_HARDWARE) +# undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE +# error Boost.Numeric.Interval: Please specify rounding control mechanism. +#endif + +namespace boost { +namespace numeric { +namespace interval_lib { + +/* + * Three specializations of rounded_math + */ + +template<> +struct rounded_math + : save_state > +{}; + +template<> +struct rounded_math + : save_state > +{}; + +template<> +struct rounded_math + : save_state > +{}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_HW_ROUNDING_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/interval.hpp b/deprecated/eo/contrib/boost/numeric/interval/interval.hpp new file mode 100644 index 000000000..0b2d0eec6 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/interval.hpp @@ -0,0 +1,450 @@ +/* Boost interval/interval.hpp header file + * + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_INTERVAL_HPP +#define BOOST_NUMERIC_INTERVAL_INTERVAL_HPP + +#include +#include +#include + +namespace boost { +namespace numeric { + +namespace interval_lib { + +class comparison_error + : public std::runtime_error +{ +public: + comparison_error() + : std::runtime_error("boost::interval: uncertain comparison") + { } +}; + +} // namespace interval_lib + +/* + * interval class + */ + +template +class interval +{ +private: + struct interval_holder; + struct number_holder; +public: + typedef T base_type; + typedef Policies traits_type; + + T const &lower() const; + T const &upper() const; + + interval(); + interval(T const &v); + template interval(T1 const &v); + interval(T const &l, T const &u); + template interval(T1 const &l, T2 const &u); + interval(interval const &r); + template interval(interval const &r); + template interval(interval const &r); + + interval &operator=(T const &v); + template interval &operator=(T1 const &v); + interval &operator=(interval const &r); + template interval &operator=(interval const &r); + template interval &operator=(interval const &r); + + void assign(const T& l, const T& u); + + static interval empty(); + static interval whole(); + static interval hull(const T& x, const T& y); + + interval& operator+= (const T& r); + interval& operator+= (const interval& r); + interval& operator-= (const T& r); + interval& operator-= (const interval& r); + interval& operator*= (const T& r); + interval& operator*= (const interval& r); + interval& operator/= (const T& r); + interval& operator/= (const interval& r); + + bool operator< (const interval_holder& r) const; + bool operator> (const interval_holder& r) const; + bool operator<= (const interval_holder& r) const; + bool operator>= (const interval_holder& r) const; + bool operator== (const interval_holder& r) const; + bool operator!= (const interval_holder& r) const; + + bool operator< (const number_holder& r) const; + bool operator> (const number_holder& r) const; + bool operator<= (const number_holder& r) const; + bool operator>= (const number_holder& r) const; + bool operator== (const number_holder& r) const; + bool operator!= (const number_holder& r) const; + + // the following is for internal use only, it is not a published interface + // nevertheless, it's public because friends don't always work correctly. + interval(const T& l, const T& u, bool): low(l), up(u) {} + void set_empty(); + void set_whole(); + void set(const T& l, const T& u); + +private: + struct interval_holder { + template + interval_holder(const interval& r) + : low(r.lower()), up(r.upper()) + { + typedef typename Policies2::checking checking2; + if (checking2::is_empty(low, up)) + throw interval_lib::comparison_error(); + } + + const T& low; + const T& up; + }; + + struct number_holder { + number_holder(const T& r) : val(r) + { + typedef typename Policies::checking checking; + if (checking::is_nan(r)) + throw interval_lib::comparison_error(); + } + + const T& val; + }; + + typedef typename Policies::checking checking; + typedef typename Policies::rounding rounding; + + T low; + T up; +}; + +template inline +interval::interval(): + low(static_cast(0)), up(static_cast(0)) +{} + +template inline +interval::interval(T const &v): low(v), up(v) +{ + if (checking::is_nan(v)) set_empty(); +} + +template template inline +interval::interval(T1 const &v) +{ + if (checking::is_nan(v)) set_empty(); + else { + rounding rnd; + low = rnd.conv_down(v); + up = rnd.conv_up (v); + } +} + +template template inline +interval::interval(T1 const &l, T2 const &u) +{ + if (checking::is_nan(l) || checking::is_nan(u) || !(l <= u)) set_empty(); + else { + rounding rnd; + low = rnd.conv_down(l); + up = rnd.conv_up (u); + } +} + +template inline +interval::interval(T const &l, T const &u): low(l), up(u) +{ + if (checking::is_nan(l) || checking::is_nan(u) || !(l <= u)) + set_empty(); +} + + +template inline +interval::interval(interval const &r): low(r.lower()), up(r.upper()) +{} + +template template inline +interval::interval(interval const &r): low(r.lower()), up(r.upper()) +{ + typedef typename Policies1::checking checking1; + if (checking1::is_empty(r.lower(), r.upper())) set_empty(); +} + +template template inline +interval::interval(interval const &r) +{ + typedef typename Policies1::checking checking1; + if (checking1::is_empty(r.lower(), r.upper())) set_empty(); + else { + rounding rnd; + low = rnd.conv_down(r.lower()); + up = rnd.conv_up (r.upper()); + } +} + +template inline +interval &interval::operator=(T const &v) +{ + if (checking::is_nan(v)) set_empty(); + else low = up = v; + return *this; +} + +template template inline +interval &interval::operator=(T1 const &v) +{ + if (checking::is_nan(v)) set_empty(); + else { + rounding rnd; + low = rnd.conv_down(v); + up = rnd.conv_up (v); + } + return *this; +} + +template inline +interval &interval::operator=(interval const &r) +{ + low = r.lower(); + up = r.upper(); + return *this; +} + +template template inline +interval &interval::operator=(interval const &r) +{ + typedef typename Policies1::checking checking1; + if (checking1::is_empty(r.lower(), r.upper())) set_empty(); + else { + low = r.lower(); + up = r.upper(); + } + return *this; +} + +template template inline +interval &interval::operator=(interval const &r) +{ + typedef typename Policies1::checking checking1; + if (checking1::is_empty(r.lower(), r.upper())) set_empty(); + else { + rounding rnd; + low = rnd.conv_down(r.lower()); + up = rnd.conv_up (r.upper()); + } + return *this; +} + +template inline +void interval::assign(const T& l, const T& u) +{ + if (checking::is_nan(l) || checking::is_nan(u) || !(l <= u)) + set_empty(); + else set(l, u); +} + +template inline +void interval::set(const T& l, const T& u) +{ + low = l; + up = u; +} + +template inline +void interval::set_empty() +{ + low = checking::empty_lower(); + up = checking::empty_upper(); +} + +template inline +void interval::set_whole() +{ + low = checking::neg_inf(); + up = checking::pos_inf(); +} + +template inline +interval interval::hull(const T& x, const T& y) +{ + bool bad_x = checking::is_nan(x); + bool bad_y = checking::is_nan(y); + if (bad_x) + if (bad_y) return interval::empty(); + else return interval(y, y, true); + else + if (bad_y) return interval(x, x, true); + if (x <= y) return interval(x, y, true); + else return interval(y, x, true); +} + +template inline +interval interval::empty() +{ + return interval(checking::empty_lower(), + checking::empty_upper(), true); +} + +template inline +interval interval::whole() +{ + return interval(checking::neg_inf(), checking::pos_inf(), true); +} + +template inline +const T& interval::lower() const +{ + return low; +} + +template inline +const T& interval::upper() const +{ + return up; +} + +/* + * interval/interval comparisons + */ + +template inline +bool interval::operator< (const interval_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up < r.low) return true; + else if (low >= r.up) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator> (const interval_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (low > r.up) return true; + else if (up <= r.low) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator<= (const interval_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up <= r.low) return true; + else if (low > r.up) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator>= (const interval_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (low >= r.up) return true; + else if (up < r.low) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator== (const interval_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up == r.low && low == r.up) return true; + else if (up < r.low || low > r.up) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator!= (const interval_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up < r.low || low > r.up) return true; + else if (up == r.low && low == r.up) return false; + } + throw interval_lib::comparison_error(); +} + +/* + * interval/number comparisons + */ + +template inline +bool interval::operator< (const number_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up < r.val) return true; + else if (low >= r.val) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator> (const number_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (low > r.val) return true; + else if (up <= r.val) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator<= (const number_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up <= r.val) return true; + else if (low > r.val) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator>= (const number_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (low >= r.val) return true; + else if (up < r.val) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator== (const number_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up == r.val && low == r.val) return true; + else if (up < r.val || low > r.val) return false; + } + throw interval_lib::comparison_error(); +} + +template inline +bool interval::operator!= (const number_holder& r) const +{ + if (!checking::is_empty(low, up)) { + if (up < r.val || low > r.val) return true; + else if (up == r.val && low == r.val) return false; + } + throw interval_lib::comparison_error(); +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_INTERVAL_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/io.hpp b/deprecated/eo/contrib/boost/numeric/interval/io.hpp new file mode 100644 index 000000000..dc4179e52 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/io.hpp @@ -0,0 +1,41 @@ +/* Boost interval/io.hpp header file + * + * This file is only meant to provide a quick + * implementation of the output operator. It is + * provided for test programs that aren't even + * interested in the precision of the results. + * A real progam should define its own operators + * and never include this header. + * + * Copyright 2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_IO_HPP +#define BOOST_NUMERIC_INTERVAL_IO_HPP + +#include +#include +#include + +namespace boost { +namespace numeric { + +template +std::basic_ostream &operator<< + (std::basic_ostream &stream, + interval const &value) +{ + if (empty(value)) + return stream << "[]"; + else + return stream << '[' << lower(value) << ',' << upper(value) << ']'; +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_IO_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/limits.hpp b/deprecated/eo/contrib/boost/numeric/interval/limits.hpp new file mode 100644 index 000000000..d691ccee2 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/limits.hpp @@ -0,0 +1,51 @@ +/* Boost interval/limits.hpp template implementation file + * + * Copyright 2000 Jens Maurer + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_LIMITS_HPP +#define BOOST_NUMERIC_INTERVAL_LIMITS_HPP + +#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION + +#include +#include +#include + +namespace std { + +template +class numeric_limits > + : public numeric_limits +{ +private: + typedef boost::numeric::interval I; + typedef numeric_limits bl; +public: + static I min BOOST_PREVENT_MACRO_SUBSTITUTION () throw() { return I((bl::min)(), (bl::min)()); } + static I max BOOST_PREVENT_MACRO_SUBSTITUTION () throw() { return I((bl::max)(), (bl::max)()); } + static I epsilon() throw() { return I(bl::epsilon(), bl::epsilon()); } + + BOOST_STATIC_CONSTANT(float_round_style, round_style = round_indeterminate); + BOOST_STATIC_CONSTANT(bool, is_iec559 = false); + + static I infinity () throw() { return I::whole(); } + static I quiet_NaN() throw() { return I::empty(); } + static I signaling_NaN() throw() + { return I(bl::signaling_NaN(), bl::signaling_Nan()); } + static I denorm_min() throw() + { return I(bl::denorm_min(), bl::denorm_min()); } +private: + static I round_error(); // hide this on purpose, not yet implemented +}; + +} // namespace std + +#endif + +#endif // BOOST_NUMERIC_INTERVAL_LIMITS_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/policies.hpp b/deprecated/eo/contrib/boost/numeric/interval/policies.hpp new file mode 100644 index 000000000..70ad220d9 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/policies.hpp @@ -0,0 +1,75 @@ +/* Boost interval/policies.hpp template implementation file + * + * Copyright 2003 Guillaume Melquiond + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_POLICIES_HPP +#define BOOST_NUMERIC_INTERVAL_POLICIES_HPP + +#include + +namespace boost { +namespace numeric { +namespace interval_lib { + +/* + * policies class + */ + +template +struct policies +{ + typedef Rounding rounding; + typedef Checking checking; +}; + +/* + * policies switching classes + */ + +template +class change_rounding +{ + typedef typename OldInterval::base_type T; + typedef typename OldInterval::traits_type p; + typedef typename p::checking checking; +public: + typedef interval > type; +}; + +template +class change_checking +{ + typedef typename OldInterval::base_type T; + typedef typename OldInterval::traits_type p; + typedef typename p::rounding rounding; +public: + typedef interval > type; +}; + +/* + * Protect / unprotect: control whether the rounding mode is set/reset + * at each operation, rather than once and for all. + */ + +template +class unprotect +{ + typedef typename OldInterval::base_type T; + typedef typename OldInterval::traits_type p; + typedef typename p::rounding r; + typedef typename r::unprotected_rounding newRounding; +public: + typedef typename change_rounding::type type; +}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + + +#endif // BOOST_NUMERIC_INTERVAL_POLICIES_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/rounded_arith.hpp b/deprecated/eo/contrib/boost/numeric/interval/rounded_arith.hpp new file mode 100644 index 000000000..6ce5c7f7e --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/rounded_arith.hpp @@ -0,0 +1,120 @@ +/* Boost interval/rounded_arith.hpp template implementation file + * + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_ROUNDED_ARITH_HPP +#define BOOST_NUMERIC_INTERVAL_ROUNDED_ARITH_HPP + +#include +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { + +/* + * Three classes of rounding: exact, std, opp + * See documentation for details. + */ + +template +struct rounded_arith_exact: Rounding { + void init() { } + template T conv_down(U const &v) { return v; } + template T conv_up (U const &v) { return v; } + T add_down (const T& x, const T& y) { return x + y; } + T add_up (const T& x, const T& y) { return x + y; } + T sub_down (const T& x, const T& y) { return x - y; } + T sub_up (const T& x, const T& y) { return x - y; } + T mul_down (const T& x, const T& y) { return x * y; } + T mul_up (const T& x, const T& y) { return x * y; } + T div_down (const T& x, const T& y) { return x / y; } + T div_up (const T& x, const T& y) { return x / y; } + T median (const T& x, const T& y) { return (x + y) / 2; } + T sqrt_down(const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(sqrt); return sqrt(x); } + T sqrt_up (const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(sqrt); return sqrt(x); } + T int_down (const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(floor); return floor(x); } + T int_up (const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(ceil); return ceil(x); } +}; + +template +struct rounded_arith_std: Rounding { +# define BOOST_DN(EXPR) this->downward(); return this->force_rounding(EXPR) +# define BOOST_NR(EXPR) this->to_nearest(); return this->force_rounding(EXPR) +# define BOOST_UP(EXPR) this->upward(); return this->force_rounding(EXPR) + void init() { } + template T conv_down(U const &v) { BOOST_DN(v); } + template T conv_up (U const &v) { BOOST_UP(v); } + T add_down(const T& x, const T& y) { BOOST_DN(x + y); } + T sub_down(const T& x, const T& y) { BOOST_DN(x - y); } + T mul_down(const T& x, const T& y) { BOOST_DN(x * y); } + T div_down(const T& x, const T& y) { BOOST_DN(x / y); } + T add_up (const T& x, const T& y) { BOOST_UP(x + y); } + T sub_up (const T& x, const T& y) { BOOST_UP(x - y); } + T mul_up (const T& x, const T& y) { BOOST_UP(x * y); } + T div_up (const T& x, const T& y) { BOOST_UP(x / y); } + T median(const T& x, const T& y) { BOOST_NR((x + y) / 2); } + T sqrt_down(const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(sqrt); BOOST_DN(sqrt(x)); } + T sqrt_up (const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(sqrt); BOOST_UP(sqrt(x)); } + T int_down(const T& x) { this->downward(); return to_int(x); } + T int_up (const T& x) { this->upward(); return to_int(x); } +# undef BOOST_DN +# undef BOOST_NR +# undef BOOST_UP +}; + +template +struct rounded_arith_opp: Rounding { + void init() { this->upward(); } +# define BOOST_DN(EXPR) \ + this->downward(); \ + T r = this->force_rounding(EXPR); \ + this->upward(); \ + return r +# define BOOST_NR(EXPR) \ + this->to_nearest(); \ + T r = this->force_rounding(EXPR); \ + this->upward(); \ + return r +# define BOOST_UP(EXPR) return this->force_rounding(EXPR) +# define BOOST_UP_NEG(EXPR) return -this->force_rounding(EXPR) + template T conv_down(U const &v) { BOOST_UP_NEG(-v); } + template T conv_up (U const &v) { BOOST_UP(v); } + T add_down(const T& x, const T& y) { BOOST_UP_NEG((-x) - y); } + T sub_down(const T& x, const T& y) { BOOST_UP_NEG(y - x); } + T mul_down(const T& x, const T& y) { BOOST_UP_NEG(x * (-y)); } + T div_down(const T& x, const T& y) { BOOST_UP_NEG(x / (-y)); } + T add_up (const T& x, const T& y) { BOOST_UP(x + y); } + T sub_up (const T& x, const T& y) { BOOST_UP(x - y); } + T mul_up (const T& x, const T& y) { BOOST_UP(x * y); } + T div_up (const T& x, const T& y) { BOOST_UP(x / y); } + T median (const T& x, const T& y) { BOOST_NR((x + y) / 2); } + T sqrt_down(const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(sqrt); BOOST_DN(sqrt(x)); } + T sqrt_up (const T& x) + { BOOST_NUMERIC_INTERVAL_using_math(sqrt); BOOST_UP(sqrt(x)); } + T int_down(const T& x) { return -to_int(-x); } + T int_up (const T& x) { return to_int(x); } +# undef BOOST_DN +# undef BOOST_NR +# undef BOOST_UP +# undef BOOST_UP_NEG +}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_ROUNDED_ARITH_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/rounded_transc.hpp b/deprecated/eo/contrib/boost/numeric/interval/rounded_transc.hpp new file mode 100644 index 000000000..e1704f5f2 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/rounded_transc.hpp @@ -0,0 +1,140 @@ +/* Boost interval/rounded_transc.hpp template implementation file + * + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_ROUNDED_TRANSC_HPP +#define BOOST_NUMERIC_INTERVAL_ROUNDED_TRANSC_HPP + +#include +#include +#include + +namespace boost { +namespace numeric { +namespace interval_lib { + +template +struct rounded_transc_exact: Rounding +{ +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) { BOOST_NUMERIC_INTERVAL_using_math(f); return f(x); } \ + T f##_up (const T& x) { BOOST_NUMERIC_INTERVAL_using_math(f); return f(x); } + BOOST_NUMERIC_INTERVAL_new_func(exp) + BOOST_NUMERIC_INTERVAL_new_func(log) + BOOST_NUMERIC_INTERVAL_new_func(sin) + BOOST_NUMERIC_INTERVAL_new_func(cos) + BOOST_NUMERIC_INTERVAL_new_func(tan) + BOOST_NUMERIC_INTERVAL_new_func(asin) + BOOST_NUMERIC_INTERVAL_new_func(acos) + BOOST_NUMERIC_INTERVAL_new_func(atan) + BOOST_NUMERIC_INTERVAL_new_func(sinh) + BOOST_NUMERIC_INTERVAL_new_func(cosh) + BOOST_NUMERIC_INTERVAL_new_func(tanh) +# undef BOOST_NUMERIC_INTERVAL_new_func +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) { BOOST_NUMERIC_INTERVAL_using_ahyp(f); return f(x); } \ + T f##_up (const T& x) { BOOST_NUMERIC_INTERVAL_using_ahyp(f); return f(x); } + BOOST_NUMERIC_INTERVAL_new_func(asinh) + BOOST_NUMERIC_INTERVAL_new_func(acosh) + BOOST_NUMERIC_INTERVAL_new_func(atanh) +# undef BOOST_NUMERIC_INTERVAL_new_func +}; + +template +struct rounded_transc_std: Rounding +{ +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_math(f); \ + this->downward(); return this->force_rounding(f(x)); } \ + T f##_up (const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_math(f); \ + this->upward(); return this->force_rounding(f(x)); } + BOOST_NUMERIC_INTERVAL_new_func(exp) + BOOST_NUMERIC_INTERVAL_new_func(log) + BOOST_NUMERIC_INTERVAL_new_func(sin) + BOOST_NUMERIC_INTERVAL_new_func(cos) + BOOST_NUMERIC_INTERVAL_new_func(tan) + BOOST_NUMERIC_INTERVAL_new_func(asin) + BOOST_NUMERIC_INTERVAL_new_func(acos) + BOOST_NUMERIC_INTERVAL_new_func(atan) + BOOST_NUMERIC_INTERVAL_new_func(sinh) + BOOST_NUMERIC_INTERVAL_new_func(cosh) + BOOST_NUMERIC_INTERVAL_new_func(tanh) +# undef BOOST_NUMERIC_INTERVAL_new_func +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_ahyp(f); \ + this->downward(); return this->force_rounding(f(x)); } \ + T f##_up (const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_ahyp(f); \ + this->upward(); return this->force_rounding(f(x)); } + BOOST_NUMERIC_INTERVAL_new_func(asinh) + BOOST_NUMERIC_INTERVAL_new_func(acosh) + BOOST_NUMERIC_INTERVAL_new_func(atanh) +# undef BOOST_NUMERIC_INTERVAL_new_func +}; + +template +struct rounded_transc_opp: Rounding +{ +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_math(f); \ + this->downward(); T y = this->force_rounding(f(x)); \ + this->upward(); return y; } \ + T f##_up (const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_math(f); \ + return this->force_rounding(f(x)); } + BOOST_NUMERIC_INTERVAL_new_func(exp) + BOOST_NUMERIC_INTERVAL_new_func(log) + BOOST_NUMERIC_INTERVAL_new_func(cos) + BOOST_NUMERIC_INTERVAL_new_func(acos) + BOOST_NUMERIC_INTERVAL_new_func(cosh) +# undef BOOST_NUMERIC_INTERVAL_new_func +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_math(f); \ + return -this->force_rounding(-f(x)); } \ + T f##_up (const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_math(f); \ + return this->force_rounding(f(x)); } + BOOST_NUMERIC_INTERVAL_new_func(sin) + BOOST_NUMERIC_INTERVAL_new_func(tan) + BOOST_NUMERIC_INTERVAL_new_func(asin) + BOOST_NUMERIC_INTERVAL_new_func(atan) + BOOST_NUMERIC_INTERVAL_new_func(sinh) + BOOST_NUMERIC_INTERVAL_new_func(tanh) +# undef BOOST_NUMERIC_INTERVAL_new_func +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_ahyp(f); \ + this->downward(); T y = this->force_rounding(f(x)); \ + this->upward(); return y; } \ + T f##_up (const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_ahyp(f); \ + return this->force_rounding(f(x)); } + BOOST_NUMERIC_INTERVAL_new_func(asinh) + BOOST_NUMERIC_INTERVAL_new_func(atanh) +# undef BOOST_NUMERIC_INTERVAL_new_func +# define BOOST_NUMERIC_INTERVAL_new_func(f) \ + T f##_down(const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_ahyp(f); \ + return -this->force_rounding(-f(x)); } \ + T f##_up (const T& x) \ + { BOOST_NUMERIC_INTERVAL_using_ahyp(f); \ + return this->force_rounding(f(x)); } + BOOST_NUMERIC_INTERVAL_new_func(acosh) +# undef BOOST_NUMERIC_INTERVAL_new_func +}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_ROUNDED_TRANSC_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/rounding.hpp b/deprecated/eo/contrib/boost/numeric/interval/rounding.hpp new file mode 100644 index 000000000..f69e2e4b5 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/rounding.hpp @@ -0,0 +1,101 @@ +/* Boost interval/rounding.hpp template implementation file + * + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_ROUNDING_HPP +#define BOOST_NUMERIC_INTERVAL_ROUNDING_HPP + +namespace boost { +namespace numeric { +namespace interval_lib { + +/* + * Default rounding_control class (does nothing) + */ + +template +struct rounding_control +{ + typedef int rounding_mode; + static void get_rounding_mode(rounding_mode&) {} + static void set_rounding_mode(rounding_mode) {} + static void upward() {} + static void downward() {} + static void to_nearest() {} + static const T& to_int(const T& x) { return x; } + static const T& force_rounding(const T& x) { return x; } +}; + +/* + * A few rounding control classes (exact/std/opp: see documentation) + * rounded_arith_* control the rounding of the arithmetic operators + * rounded_transc_* control the rounding of the transcendental functions + */ + +template > +struct rounded_arith_exact; + +template > +struct rounded_arith_std; + +template > +struct rounded_arith_opp; + +template +struct rounded_transc_dummy; + +template > +struct rounded_transc_exact; + +template > +struct rounded_transc_std; + +template > +struct rounded_transc_opp; + +/* + * State-saving classes: allow to set and reset rounding control + */ + +namespace detail { + +template +struct save_state_unprotected: Rounding +{ + typedef save_state_unprotected unprotected_rounding; +}; + +} // namespace detail + +template +struct save_state: Rounding +{ + typename Rounding::rounding_mode mode; + save_state() { + this->get_rounding_mode(mode); + this->init(); + } + ~save_state() { this->set_rounding_mode(mode); } + typedef detail::save_state_unprotected unprotected_rounding; +}; + +template +struct save_state_nothing: Rounding +{ + typedef save_state_nothing unprotected_rounding; +}; + +template +struct rounded_math: save_state_nothing > +{}; + +} // namespace interval_lib +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_ROUNDING_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/transc.hpp b/deprecated/eo/contrib/boost/numeric/interval/transc.hpp new file mode 100644 index 000000000..88aebd6b3 --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/transc.hpp @@ -0,0 +1,232 @@ +/* Boost interval/transc.hpp template implementation file + * + * Copyright 2000 Jens Maurer + * Copyright 2002 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_TRANSC_HPP +#define BOOST_NUMERIC_INTERVAL_TRANSC_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace numeric { + +template inline +interval exp(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.exp_down(x.lower()), rnd.exp_up(x.upper()), true); +} + +template inline +interval log(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x) || + !interval_lib::user::is_pos(x.upper())) + return I::empty(); + typename Policies::rounding rnd; + typedef typename Policies::checking checking; + T l = !interval_lib::user::is_pos(x.lower()) + ? checking::neg_inf() : rnd.log_down(x.lower()); + return I(l, rnd.log_up(x.upper()), true); +} + +template inline +interval cos(const interval& x) +{ + if (interval_lib::detail::test_input(x)) + return interval::empty(); + typename Policies::rounding rnd; + typedef interval I; + typedef typename interval_lib::unprotect::type R; + + // get lower bound within [0, pi] + const R pi2 = interval_lib::pi_twice(); + R tmp = fmod((const R&)x, pi2); + if (width(tmp) >= pi2.lower()) + return I(static_cast(-1), static_cast(1), true); // we are covering a full period + if (tmp.lower() >= interval_lib::constants::pi_upper()) + return -cos(tmp - interval_lib::pi()); + T l = tmp.lower(); + T u = tmp.upper(); + + BOOST_USING_STD_MIN(); + // separate into monotone subintervals + if (u <= interval_lib::constants::pi_lower()) + return I(rnd.cos_down(u), rnd.cos_up(l), true); + else if (u <= pi2.lower()) + return I(static_cast(-1), rnd.cos_up(min BOOST_PREVENT_MACRO_SUBSTITUTION(rnd.sub_down(pi2.lower(), u), l)), true); + else + return I(static_cast(-1), static_cast(1), true); +} + +template inline +interval sin(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + typedef typename interval_lib::unprotect::type R; + I r = cos((const R&)x - interval_lib::pi_half()); + (void)&rnd; + return r; +} + +template inline +interval tan(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + typedef typename interval_lib::unprotect::type R; + + // get lower bound within [-pi/2, pi/2] + const R pi = interval_lib::pi(); + R tmp = fmod((const R&)x, pi); + const T pi_half_d = interval_lib::constants::pi_half_lower(); + if (tmp.lower() >= pi_half_d) + tmp -= pi; + if (tmp.lower() <= -pi_half_d || tmp.upper() >= pi_half_d) + return I::whole(); + return I(rnd.tan_down(tmp.lower()), rnd.tan_up(tmp.upper()), true); +} + +template inline +interval asin(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x) + || x.upper() < static_cast(-1) || x.lower() > static_cast(1)) + return I::empty(); + typename Policies::rounding rnd; + T l = (x.lower() <= static_cast(-1)) + ? -interval_lib::constants::pi_half_upper() + : rnd.asin_down(x.lower()); + T u = (x.upper() >= static_cast(1) ) + ? interval_lib::constants::pi_half_upper() + : rnd.asin_up (x.upper()); + return I(l, u, true); +} + +template inline +interval acos(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x) + || x.upper() < static_cast(-1) || x.lower() > static_cast(1)) + return I::empty(); + typename Policies::rounding rnd; + T l = (x.upper() >= static_cast(1) ) + ? static_cast(0) + : rnd.acos_down(x.upper()); + T u = (x.lower() <= static_cast(-1)) + ? interval_lib::constants::pi_upper() + : rnd.acos_up (x.lower()); + return I(l, u, true); +} + +template inline +interval atan(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.atan_down(x.lower()), rnd.atan_up(x.upper()), true); +} + +template inline +interval sinh(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.sinh_down(x.lower()), rnd.sinh_up(x.upper()), true); +} + +template inline +interval cosh(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + if (interval_lib::user::is_neg(x.upper())) + return I(rnd.cosh_down(x.upper()), rnd.cosh_up(x.lower()), true); + else if (!interval_lib::user::is_neg(x.lower())) + return I(rnd.cosh_down(x.lower()), rnd.cosh_up(x.upper()), true); + else + return I(static_cast(0), rnd.cosh_up(-x.lower() > x.upper() ? x.lower() : x.upper()), true); +} + +template inline +interval tanh(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.tanh_down(x.lower()), rnd.tanh_up(x.upper()), true); +} + +template inline +interval asinh(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + typename Policies::rounding rnd; + return I(rnd.asinh_down(x.lower()), rnd.asinh_up(x.upper()), true); +} + +template inline +interval acosh(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x) || x.upper() < static_cast(1)) + return I::empty(); + typename Policies::rounding rnd; + T l = x.lower() <= static_cast(1) ? static_cast(0) : rnd.acosh_down(x.lower()); + return I(l, rnd.acosh_up(x.upper()), true); +} + +template inline +interval atanh(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x) + || x.upper() < static_cast(-1) || x.lower() > static_cast(1)) + return I::empty(); + typename Policies::rounding rnd; + typedef typename Policies::checking checking; + T l = (x.lower() <= static_cast(-1)) + ? checking::neg_inf() : rnd.atanh_down(x.lower()); + T u = (x.upper() >= static_cast(1) ) + ? checking::pos_inf() : rnd.atanh_up (x.upper()); + return I(l, u, true); +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_TRANSC_HPP diff --git a/deprecated/eo/contrib/boost/numeric/interval/utility.hpp b/deprecated/eo/contrib/boost/numeric/interval/utility.hpp new file mode 100644 index 000000000..d24d84d7a --- /dev/null +++ b/deprecated/eo/contrib/boost/numeric/interval/utility.hpp @@ -0,0 +1,331 @@ +/* Boost interval/utility.hpp template implementation file + * + * Copyright 2000 Jens Maurer + * Copyright 2002-2003 Herv Brnnimann, Guillaume Melquiond, Sylvain Pion + * + * 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) + */ + +#ifndef BOOST_NUMERIC_INTERVAL_UTILITY_HPP +#define BOOST_NUMERIC_INTERVAL_UTILITY_HPP + +#include +#include +#include +#include +#include +#include + +/* + * Implementation of simple functions + */ + +namespace boost { +namespace numeric { + +/* + * Utility Functions + */ + +template inline +const T& lower(const interval& x) +{ + return x.lower(); +} + +template inline +const T& upper(const interval& x) +{ + return x.upper(); +} + +template inline +T checked_lower(const interval& x) +{ + if (empty(x)) { + typedef typename Policies::checking checking; + return checking::nan(); + } + return x.lower(); +} + +template inline +T checked_upper(const interval& x) +{ + if (empty(x)) { + typedef typename Policies::checking checking; + return checking::nan(); + } + return x.upper(); +} + +template inline +T width(const interval& x) +{ + if (interval_lib::detail::test_input(x)) return static_cast(0); + typename Policies::rounding rnd; + return rnd.sub_up(x.upper(), x.lower()); +} + +template inline +T median(const interval& x) +{ + if (interval_lib::detail::test_input(x)) { + typedef typename Policies::checking checking; + return checking::nan(); + } + typename Policies::rounding rnd; + return rnd.median(x.lower(), x.upper()); +} + +template inline +interval widen(const interval& x, const T& v) +{ + if (interval_lib::detail::test_input(x)) + return interval::empty(); + typename Policies::rounding rnd; + return interval(rnd.sub_down(x.lower(), v), + rnd.add_up (x.upper(), v), true); +} + +/* + * Set-like operations + */ + +template inline +bool empty(const interval& x) +{ + return interval_lib::detail::test_input(x); +} + +template inline +bool in_zero(const interval& x) +{ + if (interval_lib::detail::test_input(x)) return false; + return (!interval_lib::user::is_pos(x.lower())) && + (!interval_lib::user::is_neg(x.upper())); +} + +template inline +bool in(const T& x, const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) return false; + return y.lower() <= x && x <= y.upper(); +} + +template inline +bool subset(const interval& x, + const interval& y) +{ + if (empty(x)) return true; + return !empty(y) && y.lower() <= x.lower() && x.upper() <= y.upper(); +} + +template inline +bool proper_subset(const interval& x, + const interval& y) +{ + if (empty(y)) return false; + if (empty(x)) return true; + return y.lower() <= x.lower() && x.upper() <= y.upper() && + (y.lower() != x.lower() || x.upper() != y.upper()); +} + +template inline +bool overlap(const interval& x, + const interval& y) +{ + if (interval_lib::detail::test_input(x, y)) return false; + return x.lower() <= y.lower() && y.lower() <= x.upper() || + y.lower() <= x.lower() && x.lower() <= y.upper(); +} + +template inline +bool singleton(const interval& x) +{ + return !empty(x) && x.lower() == x.upper(); +} + +template inline +bool equal(const interval& x, const interval& y) +{ + if (empty(x)) return empty(y); + return !empty(y) && x.lower() == y.lower() && x.upper() == y.upper(); +} + +template inline +interval intersect(const interval& x, + const interval& y) +{ + BOOST_USING_STD_MIN(); + BOOST_USING_STD_MAX(); + if (interval_lib::detail::test_input(x, y)) + return interval::empty(); + const T& l = max BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()); + const T& u = min BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()); + if (l <= u) return interval(l, u, true); + else return interval::empty(); +} + +template inline +interval hull(const interval& x, + const interval& y) +{ + BOOST_USING_STD_MIN(); + BOOST_USING_STD_MAX(); + bool bad_x = interval_lib::detail::test_input(x); + bool bad_y = interval_lib::detail::test_input(y); + if (bad_x) + if (bad_y) return interval::empty(); + else return y; + else + if (bad_y) return x; + return interval(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()), + max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()), true); +} + +template inline +interval hull(const interval& x, const T& y) +{ + BOOST_USING_STD_MIN(); + BOOST_USING_STD_MAX(); + bool bad_x = interval_lib::detail::test_input(x); + bool bad_y = interval_lib::detail::test_input(y); + if (bad_y) + if (bad_x) return interval::empty(); + else return x; + else + if (bad_x) return interval(y, y, true); + return interval(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y), + max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y), true); +} + +template inline +interval hull(const T& x, const interval& y) +{ + BOOST_USING_STD_MIN(); + BOOST_USING_STD_MAX(); + bool bad_x = interval_lib::detail::test_input(x); + bool bad_y = interval_lib::detail::test_input(y); + if (bad_x) + if (bad_y) return interval::empty(); + else return y; + else + if (bad_y) return interval(x, x, true); + return interval(min BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.lower()), + max BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.upper()), true); +} + +template inline +interval hull(const T& x, const T& y) +{ + return interval::hull(x, y); +} + +template inline +std::pair, interval > +bisect(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return std::pair(I::empty(), I::empty()); + const T m = median(x); + return std::pair(I(x.lower(), m, true), I(m, x.upper(), true)); +} + +/* + * Elementary functions + */ + +template inline +T norm(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) { + typedef typename Policies::checking checking; + return checking::nan(); + } + BOOST_USING_STD_MAX(); + return max BOOST_PREVENT_MACRO_SUBSTITUTION(-x.lower(), x.upper()); +} + +template inline +interval abs(const interval& x) +{ + typedef interval I; + if (interval_lib::detail::test_input(x)) + return I::empty(); + if (!interval_lib::user::is_neg(x.lower())) return x; + if (!interval_lib::user::is_pos(x.upper())) return -x; + BOOST_USING_STD_MAX(); + return I(static_cast(0), max BOOST_PREVENT_MACRO_SUBSTITUTION(-x.lower(), x.upper()), true); +} + +template inline +interval max BOOST_PREVENT_MACRO_SUBSTITUTION (const interval& x, + const interval& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + BOOST_USING_STD_MAX(); + return I(max BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()), max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()), true); +} + +template inline +interval max BOOST_PREVENT_MACRO_SUBSTITUTION (const interval& x, const T& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + BOOST_USING_STD_MAX(); + return I(max BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y), max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y), true); +} + +template inline +interval max BOOST_PREVENT_MACRO_SUBSTITUTION (const T& x, const interval& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + BOOST_USING_STD_MAX(); + return I(max BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.lower()), max BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.upper()), true); +} + +template inline +interval min BOOST_PREVENT_MACRO_SUBSTITUTION (const interval& x, + const interval& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + BOOST_USING_STD_MIN(); + return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()), min BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()), true); +} + +template inline +interval min BOOST_PREVENT_MACRO_SUBSTITUTION (const interval& x, const T& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + BOOST_USING_STD_MIN(); + return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y), min BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y), true); +} + +template inline +interval min BOOST_PREVENT_MACRO_SUBSTITUTION (const T& x, const interval& y) +{ + typedef interval I; + if (interval_lib::detail::test_input(x, y)) + return I::empty(); + BOOST_USING_STD_MIN(); + return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.lower()), min BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.upper()), true); +} + +} // namespace numeric +} // namespace boost + +#endif // BOOST_NUMERIC_INTERVAL_UTILITY_HPP diff --git a/deprecated/eo/contrib/eo-pso-22062007.bz2 b/deprecated/eo/contrib/eo-pso-22062007.bz2 new file mode 100755 index 000000000..a266198fe Binary files /dev/null and b/deprecated/eo/contrib/eo-pso-22062007.bz2 differ diff --git a/deprecated/eo/contrib/eoAged.h b/deprecated/eo/contrib/eoAged.h new file mode 100644 index 000000000..0fa525ae8 --- /dev/null +++ b/deprecated/eo/contrib/eoAged.h @@ -0,0 +1,108 @@ +// eoAged.h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAge.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOAGED_H +#define EOAGED_H + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // para std::string + +using namespace std; + +//----------------------------------------------------------------------------- +// eoAge +//----------------------------------------------------------------------------- + +/** eoAge is a template class that adds an age to an object.\\ +Requisites for template instantiation are that the object must admit a default ctor +and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, +printOn, readFrom. +@see eoObject +*/ +template +class eoAged: public Object +{ + public: + /// Main ctor from an already built Object. + eoAged( const Object& _o): Object( _o ), age(0) {}; + + /// Copy constructor. + eoAged( const eoAged& _a): Object( _a ), age( _a.age ) {}; + + /// Virtual dtor. They are needed in virtual class hierarchies + virtual ~eoAged() {}; + + + ///returns the age of the object + unsigned long Age() const {return age;} + + /// Increments age + const eoAged& operator ++ () { age++; return *this;} + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ +//@{ + /** Return the class id. This should be redefined in each class; but + it's got code as an example of implementation. Only "leaf" classes + can be non-virtual. + */ + virtual std::string className() const { return std::string("eoAged")+Object::className(); }; + + /** + * Read object. + * @param _is A istream. + * @throw runtime_exception If a valid object can't be read. + */ + virtual void readFrom(istream& _is) { + Object::readFrom( _is ); + _is >> age; + } + + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const{ + Object::printOn( _os ); + _os << age; + } +//@} + + private: + + /** Default Constructor. \\ + Its private so that it is not used anywhere; the right way of using this object + is to create an Object and passing it to an aged by means of the copy ctor; that way + its turned into an Aged object*/ + eoAged(): Object(), age(0) {}; + + unsigned long age; +}; + +#endif EOAGE_H diff --git a/deprecated/eo/contrib/eoDrawable.h b/deprecated/eo/contrib/eoDrawable.h new file mode 100644 index 000000000..a614042f0 --- /dev/null +++ b/deprecated/eo/contrib/eoDrawable.h @@ -0,0 +1,64 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoDrawable.h +// (c) GeNeura Team, 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EODRAWABLE_H +#define EODRAWABLE_H + +//----------------------------------------------------------------------------- + +using namespace std; + +//----------------------------------------------------------------------------- +// eoDrawable +//----------------------------------------------------------------------------- + +/** eoDrawable is a template class that adds a drawing interface to an object. +Requisites for template instantiation are that the object must admit a default ctor +and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, +eoDrawables can be drawn on any two-dimensional surface; it can be added to any +object with above characteristics. +@see eoObject +*/ +template +class eoDrawable +{ + public: + /// Main ctor from an already built Object. + eoDrawable( const Object& _o): Object( _o ){}; + + /// Copy constructor. + eoDrawable( const eoDrawable& _d): Object( _d ){}; + + /// Virtual dtor. They are needed in virtual class hierarchies + virtual ~eoDrawable() {}; + + + /**Draws the object. It must be redefined in any subclass, its 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/deprecated/eo/contrib/mathsym/COPYING b/deprecated/eo/contrib/mathsym/COPYING new file mode 100644 index 000000000..d60c31a97 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our 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 + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/deprecated/eo/contrib/mathsym/GNUmakefile b/deprecated/eo/contrib/mathsym/GNUmakefile new file mode 100644 index 000000000..3bd5c7795 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/GNUmakefile @@ -0,0 +1,101 @@ +COMPILEFLAGS=-Wno-deprecated -g -Wall -mpreferred-stack-boundary=2 -falign-functions=0#-DINTERVAL_DEBUG +OPTFLAGS= #-O3 -DNDEBUG + +PROFILE_FLAGS=#-pg +LDFLAGS=#-a + +INCLUDES=-I. -Isym -Ifun -Igen -Ieval -Iregression -I../../src -Ieo_interface -I.. + +CPPFLAGS=$(COMPILEFLAGS) $(OPTFLAGS) $(INCLUDES) $(PROFILE_FLAGS) -D__I386__ -DSIZEOF_UNSIGNED_LONG=4 +EXTLIBS=tcc/libtcc.a tcc/libtcc1.a ../../src/libeo.a ../../src/utils/libeoutils.a + +LIBS=${EXTLIBS} -ldl + +SYMLIB=libsym.a + +VPATH=sym fun gen eval regression eo_interface + +CXXSOURCES=FunDef.cpp Sym.cpp SymImpl.cpp SymOps.cpp sym_compile.cpp TreeBuilder.cpp LanguageTable.cpp\ + Dataset.cpp ErrorMeasure.cpp Scaling.cpp TargetInfo.cpp BoundsCheck.cpp util.cpp NodeSelector.cpp\ + eoSymCrossover.cpp sym_operations.cpp eoSymMutate.cpp eoSymLambdaMutate.cpp MultiFunction.cpp + +TESTPROGRAMS=test/test_compile test/testeo test/test_simplify test/test_diff test/test_lambda test/test_mf test/test_interval + +OBJS= $(CXXSOURCES:.cpp=.o) c_compile.o + +all: tcc/ symreg + +include $(CXXSOURCES:.cpp=.d) symreg.d + +clean: + rm *.o *.d $(TESTPROGRAMS) $(SYMLIB) symreg test/*.o || true + +distclean: clean + rm -rf tcc + +symreg: libsym.a symreg.o $(EXTLIBS) + $(CXX) -o symreg symreg.o libsym.a $(LIBS) $(PROFILE_FLAGS) ${LDFLAGS} + +libsym.a: $(OBJS) + rm libsym.a; ar cq $(SYMLIB) $(OBJS) + +check: $(TESTPROGRAMS) + test/test_compile && test/test_interval && test/testeo && test/test_simplify && test/test_diff && test/test_lambda && echo "all tests succeeded" + +test/test_compile: test/test_compile.o ${SYMLIB} + $(CXX) -o test/test_compile test/test_compile.o $(SYMLIB) ${LIBS} + +test/testeo: test/testeo.o ${SYMLIB} + $(CXX) -o test/testeo test/testeo.o $(SYMLIB) ${LIBS} + +test/test_simplify: test/test_simplify.o $(SYMLIB) + $(CXX) -o test/test_simplify test/test_simplify.o $(SYMLIB) ${LIBS} + +test/test_diff: test/test_diff.o $(SYMLIB) + $(CXX) -o test/test_diff test/test_diff.o $(SYMLIB) ${LIBS} + +test/test_lambda: test/test_lambda.o $(SYMLIB) + $(CXX) -o test/test_lambda test/test_lambda.o $(SYMLIB) ${LIBS} + +test/test_mf: test/test_mf.o $(SYMLIB) + $(CXX) -o test/test_mf test/test_mf.o $(SYMLIB) ${LIBS} + +test/test_interval: test/test_interval.o + $(CXX) -o test/test_interval test/test_interval.o $(SYMLIB) ${LIBS} + + +# eo +../../src/libeo.a: + make -C ../../src libeo.a + +../../src/utils/libeoutils.a: + make -C ../../src/utils libeoutils.a + +# tiny cc +tcc/: tcc.tar.gz + tar xvfz tcc.tar.gz && cd tcc && ./configure && make + +tcc/Makefile: tcc/ + cd tcc && ./configure + +tcc/libtcc.a: tcc/Makefile + make -Ctcc + +tcc/libtcc1.a: tcc/Makefile + make -Ctcc + +#rules +c_compile.o: eval/c_compile.c + $(CC) -c eval/c_compile.c -I./tcc $(COMPILEFLAGS) $(OPTFLAGS) + +%.o:%.cpp + $(CXX) -o $@ -c $< $(CPPFLAGS) $(INCLUDE) + +%.d: %.cpp + $(SHELL) -ec '$(CXX) -M $(CPPFLAGS) $< | sed "s/$*.o/& $@/g" > $@ ' + + +%.d: %.c + $(SHELL) -ec '$(CXX) -M $(CPPFLAGS) $< | sed "s/$*.o/& $@/g" > $@ ' + + diff --git a/deprecated/eo/contrib/mathsym/README b/deprecated/eo/contrib/mathsym/README new file mode 100644 index 000000000..4660c8fd7 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/README @@ -0,0 +1,198 @@ + +This is not yet another gp system (nyagp). For one, it is not general. +It does one thing, find mathematical functions, and tries to do that well. + +So, if you're trying to steer ants on various New Mexico trails, or build your +own tiny block world, you're in the wrong place. However, if you're interested +in finding mathematical functions either through direct application on data or +running it through a simulator, you might find what you're looking for here. + +=== Representation (sym/ + gen/) ======== + +Mathsym has a few interesting characteristics. First and foremost is the +basic representation. It uses trees, but these trees are stored in a +reference counted hashtable. This means that every distinct subtree that is alive +is stored once and only once. +The reference counting mechanism takes care of memory management. + +The idea of using a hashtable (for offline analysis) comes from Walter Tackett, in his +1994 dissertation. The current system is just a real-time implementation of this +idea, adding the reference counting for ease of use. + +The hashtable brings overhead. It's still pretty fast, but a string based representation +would run circles around it. However, by virtue of it storing every subtree only once, it +is fairly tight on memory. This helps tremendously when confronted with excessively growing populations, bloat. +The hashtable implementation can not stop bloat, but does make it more manageable. In a typical +GP run, the number of distinct subtrees is only 10-20% of the total number of subtrees. + +Other advantages of the hashtable are in the ability to examine the run more thoroughly. It is easy +to check how many subtrees are present in the system, and for each subtree you can check the reference +count. + +The basic tree is called a Sym. A Sym is simply a tree, and has children, accessible through args(). +A Sym simply contains an iterator (== decorated pointer) to an entry in the hashtable. +Every time you create a Sym, it is either looked up in the hashtable or added to the hashtable. +A Sym has several members: size, depth, args, etc. One interesting member is the refcount(). +This returns the reference count of the Sym in the hashtable, and thus returns the number +of distinct contexts in which the Sym is used. + +Another nice thing of these hashtable Syms is that a check for equality reduces to a pointer comparison. + +The Sym nodes are identified by a simple token, of type token_t (usually an unsigned int). It +is completely generic and could conceivably be adapted to steer ants. The rest of the library +is however targeted at mathematical functions purely. + +sym/Sym.h is the file to look into for the functionality provided by Sym. The sym/ directory +is where the source files are stored that are relevant for the generic Sym functionality. The +'gen/' directory contains some generic functionality to build and traverse trees, independent of +the function and terminal set. + +The file sym/README.cpp documents the use of the sym library for general GP use. + +=== Function Set (fun/) === + +The standard GP function set of binary functions: addition, multiplication, subtraction and +division is NOT supported. + +What is however supported are the functions of: + +summation: arbitrary arity, arity zero meaning 0.0. Arity 2 is standard addition +product: arbitrary arity, arity zero meaning 1.0. Arity 2 is standard multiplication +inversion: 1.0 / x. Only arity 1 +unary minus: -x. Only arity 1 + +Plus a whole bunch of other functions (see "fun/FunDef.h") + +The reason for this is the observation (actually from a friend of mine, thanks Luuk), +that this set of functions is complete and slightly more orthogonal than a binary set. + +The directory 'fun' contains the functionality for the function and terminal set, together +with ERC's etc. fun/FunDef.cpp contains the definition of the functionality. Stuff can be +added here, but best to contact me if you miss particular functions. + +With the sym and the function set in place, some fairly nice overloading is possible. A quick tour: + +To create a variable that reads the first value from the inputs, do: + +Sym var = SymVar(0); + +To create a constant of value 0.4432, do + +Sym cnst = SymConst(0.4432); + +The constants are also stored uniquely so that: + +Sym cnst2 = SymConst(0.4432) + +will lead to: + +cnst == cnst2 + +to be true (this happens without value compare, they point to the same element in the hashtable) + +To add two values, do + +Sym sym = var + const; + +This will create a tree with three nodes. Other operators are overloaded similarily. + +=== Evaluation (eval/) === + +The second important thing is evaluation. Although Syms can be evaluated through an interpreter, +this is not the fastest way to go about with it. The standard way of evaluating a Sym is to +first *compile* it to a function, and then run it in your favourite environment. Compilation +is done through the use of the excellent tinycc compiler, which is blazingly fast and produces +pretty good functions. + +Compilation comes in several flavours: compile a single function and retrieve a pointer to a function +of signature: + +double func(const double* x); + +where x is the input array. Another option is to compile a bunch of functions in one go, and retrieve an array +of such function pointers. The Syms are simply printed and compiled. An example: + +double func(const double* x) { return x*x + x * 1./x; } + +The batch version proceeds significantly more quickly than calling compile every time. The function pointers +can be given to a simulation for extremely quick evaluation. + +A third option is to compile a complete population in one go, and return a single pointer of signature + +void func(const double* x, double* y); + +Where 'y' is the (preallocated) output array. This allows to evaluate a complete population in one function +call, storing the results in 'y'. It uses the hashtable to store every calculation only once. An example +for the two function x*x + x*1./x and x + sin(x*x) is: + +void func(const double* x, double* y) { + double a0 = x; + double a1 = a0 * a0; + double a2 = 1.0; + double a3 = a2 / a0; + double a4 = a2 * a3; + y[0] = a4; + double a5 = sin(a1); + double a6 = a0 + a5; + y[1] = a6; +} + +This is the fastest way to evaluate even humongous populations quickly. You might be surprised at +the amount of code re-use in a GP population. + +The three compilation functions can be found in eval/sym_compile.h + +A limiting factor in tinycc is that the struct TCCState that is used to hold the compilation context, +is not really self-contained. This unfortunately means that with every call to 'compile' ALL previous +pointers that have been produced become unsafe for use. I'm still looking at ways to circumvent this. + +To work with mathsym, a few small changes in tccelf.c were necessary, check README.TCC for details. + +=== Interval Arithmetic (eval/) === + +GP is pretty good at finding mathematical expressions that are numerically unsound. Take for instance +the function '1 / x'. This is well defined only when x is strictly positive, but will lead to problems +when x equals 0. The standard answer is to define some pseudo-arithmetical function called 'protected +division' that will return some value (usually 1) when a division by zero occurs. This leads to a number +of protected functions (sqrt, log, tan, etc.) which all need to be protected. Interpreting results from +GP using such functions is in general hard. + +Interval arithmetic (through another excellent library boost/numeric/interval) is used to calculate +if particular functions can conceivably produce problems. This completely annihilates the use for Koza-style +protected operators and is a more safe and sound method. For interval arithmetic to function, the bounds +on the input variables need to be known. As for every function we can calculate a guarenteed, +though not necessarily tight, output interval given the input intervals, we can check arbitrary functions +for possible problems. If, for example for division, the input interval contains 0, we know that a division +by zero is theoretically possible. It's then best to throw away the entire function. + +Interval Arithmetic is accessible through the class IntervalBoundsCheck (eval/BoundsCheck.h) + +=== More generic support (gen/) === + +The gen subdirectory contains some general utility classes for defining function sets and for +creating trees. The idea is that these functions are generic and only append on the sym/ part +of the library. Unfortunately, the language table currently needs an ERC function, a default +implementation is hidden inside fun/FunDef.cpp. Will fix at some point. + +gen/LanguageTable.cpp -> defines the functions/terminals that can be used +gen/TreeBuilder.cpp -> can create trees based on a LanguageTable + +=== Data and Errors (regression/) === + +The above classes are generic and apply for any type of problem where a mathematical function can be +used to steer some process, run a simulation, whatever. First check the intervals, then compile the +Sym(s) to a (set of) function pointer(s), and use the pointers in some way to evaluate for fitness. +One particular type of problem for which support is built in is 'symbolic regression'. This type of +problem involves finding an mathematical input/output relationship based on some data. + +To enable this, regression/ introduces the class Dataset to contain the data and ErrorMeasure to calculate +error. Currently supported: mean squared error, mean absolute error and mean squared error scaled (proportional +to correlation squared). They use some helper classes such as Scaling and TargetInfo. + +=== EO interface (eo_interface/) === + +Contains the classes to make it all work with EO. Check the root application 'symreg' for ways to use this + + + + diff --git a/deprecated/eo/contrib/mathsym/README.TCC b/deprecated/eo/contrib/mathsym/README.TCC new file mode 100644 index 000000000..8441c232f --- /dev/null +++ b/deprecated/eo/contrib/mathsym/README.TCC @@ -0,0 +1,5 @@ + +To refrain tcc from searching for libtcc1.a in the path, uncomment +out the lines looking for that in 'tccelf.c'. Search for libtcc1 and uncomment +these two lines. All should be well. + diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSym.h b/deprecated/eo/contrib/mathsym/eo_interface/eoSym.h new file mode 100644 index 000000000..98579308a --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSym.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef EOSYM_H_ +#define EOSYM_H_ + +#include +#include +#include + + +template +class EoSym : public EO, public Sym { + + public: + + void set(const Sym& sym) { + EO::invalidate(); + static_cast(this)->operator=(sym); + } + + Sym& get() { return static_cast(*this); }; + Sym get() const { return static_cast(*this); }; + + virtual void printOn(std::ostream& os) const; + virtual void readFrom(std::istream& is); +}; + + +template +void EoSym::printOn(std::ostream& os) const { + EO::printOn(os); + os << ' '; + write_raw(os, *this); +} + +template +void EoSym::readFrom(std::istream& is) { + EO::readFrom(is); + read_raw(is, *this); +} + +template +inline std::ostream& operator<<(std::ostream& os, const EoSym& f) { f.printOn(os); return os; } +template +inline std::istream& operator>>(std::istream& is, EoSym& f) { f.readFrom(is); return is; } + + +#endif + + diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymCrossover.cpp b/deprecated/eo/contrib/mathsym/eo_interface/eoSymCrossover.cpp new file mode 100644 index 000000000..983983794 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymCrossover.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 + +#include +#include +#include + +using namespace std; + +bool subtree_quad(Sym& a, Sym& b, NodeSelector& select) { + NodeSelector::NodeSelection sel_a = select.select_node(a); + NodeSelector::NodeSelection sel_b = select.select_node(b); + + Sym aprime = insert_subtree(a, sel_a.idx(), sel_b.subtree() ); + Sym bprime = insert_subtree(b, sel_b.idx(), sel_a.subtree() ); + + a = aprime; + b = bprime; + return true; +} + +bool subtree_bin(Sym& a, const Sym& b, NodeSelector& select) { + NodeSelector::NodeSelection sel_a = select.select_node(a); + NodeSelector::NodeSelection sel_b = select.select_node(b); + + a = insert_subtree(a, sel_a.idx(), sel_b.subtree()); + + return true; +} + +Sym homologous_binimpl(Sym a, Sym b) { + + if(a == b) { return a; } // no point + + bool use_a = rng.random(2); + + token_t head = (use_a? a : b).token(); + SymVec args = use_a?a.args() : b.args(); + + const SymVec& a_args = a.args(); + const SymVec& b_args = b.args(); + unsigned mn = std::min(a_args.size(), b_args.size()); + + bool changed = !use_a; + + for (unsigned i = 0; i < mn; ++i) { + args[i] = homologous_binimpl(a_args[i], b_args[i]); + if (args[i] != a_args[i]) { + changed = true; + } + } + + return changed? Sym(head, args) : a; +} + +bool homologous_bin(Sym& a, const Sym& b) { + if (a==b) return false; + Sym org = a; + a = homologous_binimpl(a,b); + return org != a; +} + +void set_size_levels(Sym sym, vector& l, vector& s, unsigned level = 1) { + l.push_back(level); + s.push_back(sym.size()); + + for (unsigned i = 0; i < sym.args().size(); ++i) { + set_size_levels(sym.args()[i], l, s, level+1); + } +} + + +bool size_level_xover(Sym& a, const Sym& b) { + + Sym org = a; + + vector levela; + vector sizesa; + vector levelb; + vector sizesb; + + set_size_levels(a, levela, sizesa); + set_size_levels(b, levelb, sizesb); + + unsigned p0; + unsigned p1; + + for (unsigned tries = 0;; ++tries) { + p0 = rng.random(a.size()); + p1 = rng.random(b.size()); + + if (tries < 5 && (sizesa[p0] != sizesb[p1] && levela[p0] != levelb[p1])) { + continue; + } + + break; + } + + a = insert_subtree(a, p0, get_subtree(b, p1)); + + return org != a; + +} + + diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymCrossover.h b/deprecated/eo/contrib/mathsym/eo_interface/eoSymCrossover.h new file mode 100644 index 000000000..5e95ab3d9 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymCrossover.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef EOSYMCROSSOVER_H +#define EOSYMCROSSOVER_H + +class NodeSelector; +class Sym; + +#include + +extern bool subtree_quad(Sym& a, Sym& b, NodeSelector& select); +template +class eoQuadSubtreeCrossover : public eoQuadOp { + NodeSelector& node_selector; + + public: + eoQuadSubtreeCrossover(NodeSelector& _node_selector) : node_selector(_node_selector) {} + + bool operator()(EoType& a, EoType& b) { return subtree_quad(a,b, node_selector); } +}; + + +extern bool subtree_bin(Sym& a, const Sym& b, NodeSelector& select); +template +class eoBinSubtreeCrossover : public eoBinOp { + NodeSelector& node_selector; + + public : + + eoBinSubtreeCrossover(NodeSelector& _node_selector) : node_selector(_node_selector) {} + + bool operator()(EoType& a, const EoType& b) { return subtree_bin(a, b, node_selector); } +}; + +/** Yet another homologous crossover, afaik not particularly + * defined in the literature + */ +extern bool homologous_bin(Sym& a, const Sym& b); +template +class eoBinHomologousCrossover : public eoBinOp { + public: + bool operator()(EoType& a, const EoType& b) { + return homologous_bin(a,b); + } +}; + + +extern bool size_level_xover(Sym& a, const Sym& b); +template +class eoSizeLevelCrossover : public eoBinOp { + public: + bool operator()(EoType& a, const EoType& b) { + return size_level_xover(a,b); + } +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymEval.h b/deprecated/eo/contrib/mathsym/eo_interface/eoSymEval.h new file mode 100644 index 000000000..9eb5f15c2 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymEval.h @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SYMEVAL_H +#define SYMEVAL_H + +#include +#include +#include +#include + +#include + +template +class eoSymPopEval : public eoPopEvalFunc { + + BoundsCheck& check; + ErrorMeasure& measure; + unsigned size_cap; + + public: + + eoSymPopEval(BoundsCheck& _check, ErrorMeasure& _measure, unsigned _size_cap) : + check(_check), measure(_measure), size_cap(_size_cap) {} + + /** apparently this thing works on two populations, + * + * In any case, currently only implemented the population wide + * evaluation version, as that one is much faster. This because the + * compile going on behind the scenes is much faster when done in one + * go (and using subtree similarity) then when done on a case by case + * basis. + */ + void operator()(eoPop& p1, eoPop& p2) { + + std::vector unevaluated; + std::vector tmppop; + + for (unsigned i = 0; i < p1.size(); ++i) { + if (p1[i].invalid()) { + + if (expand_all(p1[i]).size() < size_cap && check.in_bounds(p1[i])) { + unevaluated.push_back(i); + tmppop.push_back( static_cast(p1[i]) ); + } else { + p1[i].fitness( measure.worst_performance() ); + } + } + } + + for (unsigned i = 0; i < p2.size(); ++i) { + if (p2[i].invalid()) { + + if (expand_all(p2[i]).size() < size_cap && check.in_bounds(p2[i])) { + + unevaluated.push_back(p1.size() + i); + tmppop.push_back( static_cast(p2[i]) ); + + } else { + p2[i].fitness( measure.worst_performance() ); // pretty bad error + } + } + } + + std::vector result = measure.calc_error(tmppop); + + for (unsigned i = 0; i < result.size(); ++i) { + unsigned idx = unevaluated[i]; + + if (idx < p1.size()) { + p1[idx].fitness(result[i].error); + } else { + idx -= p1.size(); + p2[idx].fitness(result[i].error); + } + } + } + +}; + + +#endif diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymInit.h b/deprecated/eo/contrib/mathsym/eo_interface/eoSymInit.h new file mode 100644 index 000000000..1f6318ed0 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymInit.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef EOSYMINIT_H +#define EOSYMINIT_H + +#include +#include + +/** Default initializer, Koza style */ +template +class eoSymInit : public eoInit { + + TreeBuilder& builder; + + double own_grow_prob; + unsigned own_max_depth; + + + double& grow_prob; + unsigned& max_depth; + + public: + + /** By default build ramped half and half with max depth 6 */ + eoSymInit(TreeBuilder& _builder) + : builder(_builder), + own_grow_prob(0.5), + own_max_depth(6), + grow_prob(own_grow_prob), + max_depth(own_max_depth) + {} + + /** Control the grow_prob and max_depth externally */ + eoSymInit(TreeBuilder& _builder, double& _grow_prob, unsigned& _max_depth) + : builder(_builder), + grow_prob(_grow_prob), + max_depth(_max_depth) + {} + + /** build the tree */ + void operator()(EoType& tree) { + int depth_to_use = rng.random(max_depth-2) + 2; // two levels minimum + builder.build_tree(tree, depth_to_use, rng.flip(grow_prob)); + } + +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymLambdaMutate.cpp b/deprecated/eo/contrib/mathsym/eo_interface/eoSymLambdaMutate.cpp new file mode 100644 index 000000000..e7eeecf58 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymLambdaMutate.cpp @@ -0,0 +1,29 @@ +#include +#include "FunDef.h" +#include "NodeSelector.h" + +Sym compress(Sym sym, NodeSelector& sel) { + + return ::compress(sym); + + NodeSelector::NodeSelection s = sel.select_node(sym); + + Sym f = SymLambda( s.subtree()); + + if (f == s.subtree()) { return sym; } + + return insert_subtree(sym, s.idx(), f); +} + +extern Sym expand(Sym sym, NodeSelector& sel) { + + return ::expand_all(sym); + + NodeSelector::NodeSelection s = sel.select_node(sym); + + Sym f = SymUnlambda( s.subtree()); + + if (f == s.subtree()) { return sym; } + + return insert_subtree(sym, s.idx(), f); +} diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymLambdaMutate.h b/deprecated/eo/contrib/mathsym/eo_interface/eoSymLambdaMutate.h new file mode 100644 index 000000000..d29111521 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymLambdaMutate.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SYMLAMBDAMUTATE_H +#define SYMLAMBDAMUTATE_H + +#include + +class NodeSelector; +class Sym; +extern Sym compress(Sym, NodeSelector&); +extern Sym expand(Sym, NodeSelector&); + + +template +class eoSymLambdaMutate : public eoMonOp { + NodeSelector& selector; + public : + eoSymLambdaMutate(NodeSelector& s) : selector(s) {} + + bool operator()(EoType& tomutate) { + if (rng.flip()) { + tomutate.set( expand(tomutate, selector)); + } else { + tomutate.set( compress(tomutate, selector)); + } + return true; + } + +}; + + +#endif diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymMutate.cpp b/deprecated/eo/contrib/mathsym/eo_interface/eoSymMutate.cpp new file mode 100644 index 000000000..55c786707 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymMutate.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 +#include + +using namespace std; + +std::pair do_mutate(Sym sym, double p, const LanguageTable& table) { + + bool changed = false; + SymVec args = sym.args(); + if (rng.flip(p)) { + token_t new_token = table.get_random_function(sym.token(), args.size()); + if (new_token != sym.token()) { + changed = true; + sym = Sym(new_token, args); + } + } + + for (unsigned i = 0; i < args.size(); ++i) { + std::pair r = do_mutate(args[i], p, table); + changed |= r.second; + if (r.second) + args[i] = r.first; + } + + if (changed) + return std::make_pair(Sym(sym.token(), args), true); + // else + return std::make_pair(sym, false); +} + + +// these two can (should?) move to an impl file +bool mutate(Sym& sym, double p, const LanguageTable& table) { + std::pair r = do_mutate(sym, p, table); + sym = r.first; + return r.second; +} + + +bool mutate_constants(Sym& sym, double stdev) { + vector values = get_constants(sym); + + if (values.empty()) { + return false; + } + + for (unsigned i = 0; i < values.size(); ++i) { + values[i] += rng.normal() * stdev / values.size(); + } + + sym = set_constants(sym, values); + return true; +} + diff --git a/deprecated/eo/contrib/mathsym/eo_interface/eoSymMutate.h b/deprecated/eo/contrib/mathsym/eo_interface/eoSymMutate.h new file mode 100644 index 000000000..08e23315b --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eo_interface/eoSymMutate.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SYMMUTATE_H +#define SYMMUTATE_H + +#include +#include + +#include +#include + +template +class eoSymSubtreeMutate : public eoMonOp { + + TreeBuilder& subtree_builder; + NodeSelector& node_selector; + public : + + eoSymSubtreeMutate(TreeBuilder& _subtree_builder, NodeSelector& _node_selector) + : subtree_builder(_subtree_builder), node_selector(_node_selector) {} + + + bool operator()(EoType& tomutate) { + unsigned xover_point = node_selector.select_node(tomutate).idx(); + // create subtree + Sym newtree = subtree_builder.build_tree(6, true); // TODO, parameterize + static_cast(tomutate) = insert_subtree(tomutate, xover_point, newtree); + return true; + } + +}; + +/** Class for doing node mutation + * Two parameters: + * + * mutation_rate (the rate at which to do mutation) + * is_rate_absolute : don't rescale the rate to the size of the tree + */ + +extern bool mutate(Sym& sym, double p, const LanguageTable& table); + +template +class eoSymNodeMutate : public eoMonOp { + + LanguageTable& table; + double own_mutation_rate; + bool own_is_rate_absolute; + + + public: + + double& mutation_rate; + bool& is_rate_absolute; + + eoSymNodeMutate(LanguageTable& _table) + : table(_table), + own_mutation_rate(1.0), + own_is_rate_absolute(false), // this means a probability of node mutation of 1/sym.size() + mutation_rate(own_mutation_rate), + is_rate_absolute(own_is_rate_absolute) + {} + + eoSymNodeMutate(LanguageTable& _table, double& _mutation_rate, bool& _is_rate_absolute) + : table(_table), + mutation_rate(_mutation_rate), + is_rate_absolute(_is_rate_absolute) + {} + + + bool operator()(EoType& _eo) { + double p = mutation_rate; + if (!is_rate_absolute) p /= _eo.size(); + + return mutate(_eo, p, table); + } + +}; + +/** + * Simple constant mutation class, adds gaussian noise (configurable variance) to the individuals + **/ +extern bool mutate_constants(Sym& sym, double stdev); +template +class eoSymConstantMutate : public eoMonOp { + + double& stdev; + + + public : + eoSymConstantMutate(double& _stdev) : stdev(_stdev) {} + + bool operator()(EoType& _eo) { + return mutate_constants(_eo, stdev); + } + + +}; + +#endif diff --git a/deprecated/eo/contrib/mathsym/eval/BoundsCheck.cpp b/deprecated/eo/contrib/mathsym/eval/BoundsCheck.cpp new file mode 100644 index 000000000..715ebf524 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/BoundsCheck.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 "BoundsCheck.h" +#include +#include +#include + +using namespace std; + +class IntervalBoundsCheckImpl { + public : + vector bounds; +}; + +IntervalBoundsCheck::IntervalBoundsCheck(const vector& mins, const vector& maxes) { + pimpl = new IntervalBoundsCheckImpl; + vector& b = pimpl->bounds; + + b.resize( mins.size()); + + for (unsigned i = 0; i < b.size(); ++i) { + b[i] = Interval(mins[i], maxes[i]); + } + +} + +IntervalBoundsCheck::~IntervalBoundsCheck() { delete pimpl; } +IntervalBoundsCheck::IntervalBoundsCheck(const IntervalBoundsCheck& that) { pimpl = new IntervalBoundsCheckImpl(*that.pimpl); } +IntervalBoundsCheck& IntervalBoundsCheck::operator=(const IntervalBoundsCheck& that) { *pimpl = *that.pimpl; return *this; } + +bool IntervalBoundsCheck::in_bounds(const Sym& sym) const { + Interval bounds; + + try { + bounds = eval(sym, pimpl->bounds); + if (!valid(bounds)) return false; + } catch (interval_error) { + return false; + } + return true; +} + +std::string IntervalBoundsCheck::get_bounds(const Sym& sym) const { + + try { + Interval bounds = eval(sym, pimpl->bounds); + if (!valid(bounds)) return "err"; + ostringstream os; + os << bounds; + return os.str(); + } catch (interval_error) { + return "err"; + } +} + + +std::pair IntervalBoundsCheck::calc_bounds(const Sym& sym) const { + + Interval bounds = eval(sym, pimpl->bounds); + return make_pair(bounds.lower(), bounds.upper()); +} + + diff --git a/deprecated/eo/contrib/mathsym/eval/BoundsCheck.h b/deprecated/eo/contrib/mathsym/eval/BoundsCheck.h new file mode 100644 index 000000000..d484d0293 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/BoundsCheck.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef BOUNDS_CHECK_H_ +#define BOUNDS_CHECK_H_ + +#include + +class IntervalBoundsCheckImpl; +class Sym; + +class BoundsCheck { + public : + virtual ~BoundsCheck() {}; + virtual bool in_bounds(const Sym&) const = 0; + virtual std::string get_bounds(const Sym&) const = 0; +}; + +// checks if a formula keeps within bounds using interval arithmetic +class IntervalBoundsCheck : public BoundsCheck { + + IntervalBoundsCheckImpl* pimpl; + + public: + + IntervalBoundsCheck(const std::vector& minima, const std::vector& maxima); + ~IntervalBoundsCheck(); + IntervalBoundsCheck(const IntervalBoundsCheck&); + IntervalBoundsCheck& operator=(const IntervalBoundsCheck&); + + bool in_bounds(const Sym&) const; + std::string get_bounds(const Sym&) const; + + std::pair calc_bounds(const Sym&) const; +}; + +class NoBoundsCheck : public BoundsCheck { + bool in_bounds(const Sym&) const { return false; } + std::string get_bounds(const Sym&) const { return ""; } +}; + +#endif + + diff --git a/deprecated/eo/contrib/mathsym/eval/Interval.h b/deprecated/eo/contrib/mathsym/eval/Interval.h new file mode 100644 index 000000000..3b60121e3 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/Interval.h @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef INTERVAL__H__ +#define INTERVAL__H__ + +#include +#include +#include + + +typedef boost::numeric::interval_lib::rounded_transc_exact RoundingTransc; +typedef boost::numeric::interval_lib::save_state Rounding; +typedef boost::numeric::interval_lib::checking_base Checking; +typedef boost::numeric::interval_lib::policies Policy; +typedef boost::numeric::interval Interval; + +struct interval_error{}; + +inline bool valid(const Interval& val) { + if (!finite(val.lower()) || !finite(val.upper())) return false; + + return val.lower() > -1e10 && val.upper() < 1e10; +} + +inline Interval sqrt(const Interval& val) { + if (val.lower() < 0.0) { + return Interval::whole(); + } + + return boost::numeric::sqrt(val); +} + +inline Interval sqr(const Interval& val) { + return square(val); +} + +inline Interval acos(const Interval& val) { + if (val.lower() < 1.0 || val.upper() > 1.0) { + return Interval::whole(); + } + + return boost::numeric::acos(val); +} + +inline Interval asin(const Interval& val) { + if (val.lower() < 1.0 || val.upper() > 1.0) { + return Interval::whole(); + } + + return boost::numeric::asin(val); +} + +inline Interval acosh(const Interval& val) { + if (val.lower() < 1.0) return Interval::whole(); + return boost::numeric::acosh(val); +} + +inline +std::ostream& operator<<(std::ostream& os, const Interval& val) { + os << '[' << val.lower() << ", " << val.upper() << ']'; + return os; +} + +#ifdef TEST_INTERVAL +#endif + +#endif diff --git a/deprecated/eo/contrib/mathsym/eval/MultiFuncs.cpp b/deprecated/eo/contrib/mathsym/eval/MultiFuncs.cpp new file mode 100644 index 000000000..a06be64a3 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/MultiFuncs.cpp @@ -0,0 +1,26 @@ + +namespace multi_function { + +double plus(arg_ptr args) { + return *args[0] + *args[1]; +} + +double mult(arg_ptr args) { + return *args[0] * *args[1]; +} + +double min(arg_ptr args) { + return -**args; +} + +double inv(arg_ptr args) { + return 1 / **args; +} + +//template class F { public: double operator()(double a) { return f(a); } }; + +double exp(arg_ptr args) { + return ::exp(**args); +} + +} // namespace diff --git a/deprecated/eo/contrib/mathsym/eval/MultiFunction.cpp b/deprecated/eo/contrib/mathsym/eval/MultiFunction.cpp new file mode 100644 index 000000000..ec1929d29 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/MultiFunction.cpp @@ -0,0 +1,341 @@ +#include + + +#include "MultiFunction.h" +#include "Sym.h" +#include "FunDef.h" + +using namespace std; + + +typedef vector::const_iterator data_ptr; +typedef vector data_ptrs; +typedef data_ptrs::const_iterator arg_ptr; + +#include "MultiFuncs.cpp" + +typedef double (*fptr)( arg_ptr ); + +string print_function( fptr f) { + if (f == multi_function::plus) return "+"; + if (f == multi_function::mult) return "*"; + if (f == multi_function::min) return "-"; + if (f == multi_function::inv) return "/"; + if (f == multi_function::exp) return "e"; + return "unknown"; +} + + +struct Function { + + fptr function; + arg_ptr args; + + double operator()() const { return function(args); } +}; + +static vector token_2_function; + +Sym make_binary(Sym sym) { + if (sym.args().size() == 2) return sym; + SymVec args = sym.args(); + Sym an = args.back(); + args.pop_back(); + Sym nw = make_binary( Sym( sym.token(), args) ); + args.resize(2); + args[0] = nw; + args[1] = an; + return Sym(sym.token(), args); +} + +class Compiler { + + public: + + enum func_type {constant, variable, function}; + + typedef pair entry; + +#if USE_TR1 + typedef std::tr1::unordered_map HashMap; +#else + typedef hash_map HashMap; +#endif + + HashMap map; + + vector constants; + vector variables; + vector< fptr > functions; + vector< vector > function_args; + + unsigned total_args; + + vector outputs; + + Compiler() : total_args(0) {} + + entry do_add(Sym sym) { + + HashMap::iterator it = map.find(sym); + + if (it == map.end()) { // new entry + + token_t token = sym.token(); + + if (is_constant(token)) { + constants.push_back( get_constant_value(token) ); // set value + entry e = make_pair(constant, constants.size()-1); + map.insert( make_pair(sym, e) ); + return e; + + } else if (is_variable(token)) { + unsigned idx = get_variable_index(token); + variables.push_back(idx); + entry e = make_pair(variable, variables.size()-1); + map.insert( make_pair(sym, e) ); + return e; + } // else + + fptr f; + vector vec; + const SymVec& args = sym.args(); + + switch (token) { + case sum_token: + { + if (args.size() == 0) { + return do_add( SymConst(0.0)); + } + if (args.size() == 1) { + return do_add(args[0]); + } + if (args.size() == 2) { + vec.push_back(do_add(args[0])); + vec.push_back(do_add(args[1])); + f = multi_function::plus; + //cout << "Adding + " << vec[0].second << ' ' << vec[1].second << endl; + break; + + } else { + return do_add( make_binary(sym) ); + } + + } + case prod_token: + { + if (args.size() == 0) { + return do_add( SymConst(1.0)); + } + if (args.size() == 1) { + return do_add(args[0]); + } + if (args.size() == 2) { + vec.push_back(do_add(args[0])); + vec.push_back(do_add(args[1])); + f = multi_function::mult; + //cout << "Adding * " << vec[0].second << ' ' << vec[1].second << endl; + break; + + + } else { + return do_add( make_binary(sym) ); + } + } + case sqr_token: + { + SymVec newargs(2); + newargs[0] = args[0]; + newargs[1] = args[0]; + return do_add( Sym(prod_token, newargs)); + } + default : + { + if (args.size() != 1) { + cerr << "Unknown function " << sym << " encountered" << endl; + exit(1); + } + + vec.push_back(do_add(args[0])); + + switch (token) { + case min_token: f = multi_function::min; break; + case inv_token: f = multi_function::inv; break; + case exp_token :f = multi_function::exp; break; + default : + { + cerr << "Unimplemented token encountered " << sym << endl; + exit(1); + } + } + + //cout << "Adding " << print_function(f) << ' ' << vec[0].second << endl; + + + } + + } + + total_args += vec.size(); + function_args.push_back(vec); + functions.push_back(f); + + entry e = make_pair(function, functions.size()-1); + map.insert( make_pair(sym, e) ); + return e; + + } + + return it->second; // entry + } + + void add(Sym sym) { + entry e = do_add(sym); + outputs.push_back(e); + } + +}; + +class MultiFunctionImpl { + public: + + // input mapping + vector input_idx; + + unsigned constant_offset; + unsigned var_offset; + + // evaluation + vector data; + vector funcs; + data_ptrs args; + + vector output_idx; + + MultiFunctionImpl() {} + + void clear() { + input_idx.clear(); + data.clear(); + funcs.clear(); + args.clear(); + output_idx.clear(); + constant_offset = 0; + } + + void eval(const double* x, double* y) { + unsigned i; + // evaluate variables + for (i = constant_offset; i < constant_offset + input_idx.size(); ++i) { + data[i] = x[input_idx[i-constant_offset]]; + } + + for(; i < data.size(); ++i) { + data[i] = funcs[i-var_offset](); + //cout << i << " " << data[i] << endl; + } + + for (i = 0; i < output_idx.size(); ++i) { + y[i] = data[output_idx[i]]; + } + } + + void eval(const vector& x, vector& y) { + eval(&x[0], &y[0]); + } + + void setup(const vector& pop) { + + clear(); + Compiler compiler; + + for (unsigned i = 0; i < pop.size(); ++i) { + Sym sym = (expand_all(pop[i])); + compiler.add(sym); + } + + // compiler is setup so get the data + constant_offset = compiler.constants.size(); + var_offset = constant_offset + compiler.variables.size(); + int n = var_offset + compiler.functions.size(); + + data.resize(n); + funcs.resize(compiler.functions.size()); + args.resize(compiler.total_args); + + // constants + for (unsigned i = 0; i < constant_offset; ++i) { + data[i] = compiler.constants[i]; + //cout << i << ' ' << data[i] << endl; + } + + // variables + input_idx = compiler.variables; + + //for (unsigned i = constant_offset; i < var_offset; ++i) { + //cout << i << " x" << input_idx[i-constant_offset] << endl; + //} + + // functions + unsigned which_arg = 0; + for (unsigned i = 0; i < funcs.size(); ++i) { + + Function f; + f.function = compiler.functions[i]; + + //cout << i+var_offset << ' ' << print_function(f.function); + + // interpret args + for (unsigned j = 0; j < compiler.function_args[i].size(); ++j) { + + Compiler::entry e = compiler.function_args[i][j]; + + unsigned idx = e.second; + + switch (e.first) { + case Compiler::function: idx += compiler.variables.size(); + case Compiler::variable: idx += compiler.constants.size(); + case Compiler::constant: {} + } + + args[which_arg + j] = data.begin() + idx; + //cout << ' ' << idx << "(" << e.second << ")"; + } + + //cout << endl; + + f.args = args.begin() + which_arg; + which_arg += compiler.function_args[i].size(); + funcs[i] = f; + } + + // output indices + output_idx.resize(compiler.outputs.size()); + for (unsigned i = 0; i < output_idx.size(); ++i) { + output_idx[i] = compiler.outputs[i].second; + switch(compiler.outputs[i].first) { + case Compiler::function: output_idx[i] += compiler.variables.size(); + case Compiler::variable: output_idx[i] += compiler.constants.size(); + case Compiler::constant: {} + } + //cout << "out " << output_idx[i] << endl; + } + } + +}; + + + +MultiFunction::MultiFunction(const std::vector& pop) : pimpl(new MultiFunctionImpl) { + pimpl->setup(pop); +} + +MultiFunction::~MultiFunction() { delete pimpl; } + +void MultiFunction::operator()(const std::vector& x, std::vector& y) { + pimpl->eval(x,y); +} + +void MultiFunction::operator()(const double* x, double* y) { + pimpl->eval(x,y); +} diff --git a/deprecated/eo/contrib/mathsym/eval/MultiFunction.h b/deprecated/eo/contrib/mathsym/eval/MultiFunction.h new file mode 100644 index 000000000..bc333915b --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/MultiFunction.h @@ -0,0 +1,26 @@ +#ifndef MULTIFUNCTION_H_ +#define MULTIFUNCTION_H_ + +#include + +class Sym; +class MultiFunctionImpl; + +class MultiFunction { + MultiFunction& operator=(const MultiFunction&); + MultiFunction(const MultiFunction&); + + MultiFunctionImpl* pimpl; + + public: + + MultiFunction(const std::vector& pop); + ~MultiFunction(); + + void operator()(const std::vector& x, std::vector& y); + void operator()(const double* x, double* y); + +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/eval/c_compile.c b/deprecated/eo/contrib/mathsym/eval/c_compile.c new file mode 100644 index 000000000..36ad392a9 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/c_compile.c @@ -0,0 +1,57 @@ +#include +#include +#include + +static TCCState* s = 0; + +extern void symc_init() { + if (s != 0) { + tcc_delete(s); + } + s = tcc_new(); + if (s == 0) { + fprintf(stderr, "Tiny cc doesn't function properly"); + exit(1); + } + + tcc_set_output_type(s, TCC_OUTPUT_MEMORY); +} + +extern int symc_compile(const char* func_str) { + //printf("Compiling %s\n", func_str); + int err = tcc_compile_string(s, func_str); + + if (err) { + fprintf(stderr,"Compile failed"); + } + return err; +} + +extern int symc_link() { + int err = tcc_relocate(s); + if (err) { + fprintf(stderr,"Compile failed"); + exit(1); + } + return err; +} + +extern void* symc_get_fun(const char* func_name) { + unsigned long val; + tcc_get_symbol(s, &val, func_name); + + if (val == 0) { + fprintf(stderr,"getfun failed"); + exit(1); + } + + return (void*) val; +} + +extern void* symc_make(const char* func_str, const char* func_name) { + symc_init(); + symc_compile(func_str); + symc_link(); + return symc_get_fun(func_name); +} + diff --git a/deprecated/eo/contrib/mathsym/eval/sym_compile.cpp b/deprecated/eo/contrib/mathsym/eval/sym_compile.cpp new file mode 100644 index 000000000..f75bbd5ce --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/sym_compile.cpp @@ -0,0 +1,219 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + + +#include "Sym.h" +#include "FunDef.h" +#include "sym_compile.h" + +#include + +using namespace std; + +extern "C" { + void symc_init(); + int symc_compile(const char* func_str); + int symc_link(); + void* symc_get_fun(const char* func_name); + void* symc_make(const char* func_str, const char* func_name); +} + +string make_prototypes() { + string prot = get_prototypes(); + prot += "double sqr(double x) { return x*x; }"; + return prot; +} + +// contains variable names, like 'a0', 'a1', etc. or regular code + +#if USE_TR1 +typedef std::tr1::unordered_map HashMap; +#else +typedef hash_map HashMap; +#endif + +// prints 'num' in reverse notation. Does not matter as it's a unique id +string make_var(unsigned num) { + string str = "a"; + do { + str += char('0' + (num % 10)); + num /= 10; + } while (num); + return str; +} + +template +string to_string(T t) { + ostringstream os; + os << t; + return os.str(); +} + + +HashMap::iterator find_entry(const Sym& sym, string& str, HashMap& map) { + HashMap::iterator result = map.find(sym); + + if (result == map.end()) { // new entry + const SymVec& args = sym.args(); + + vector argstr(args.size()); + for (unsigned i = 0; i < args.size(); ++i) { + argstr[i] = find_entry(args[i], str, map)->second; + } + + string var = make_var(map.size()); // map.size(): unique id + string code; + // write out the code + const FunDef& fun = get_element(sym.token()); + code = fun.c_print(argstr, vector() ); + + str += "double " + var + "=" + code + ";\n"; + result = map.insert( make_pair(sym, var ) ).first; // only want iterator + } + + return result; +} + +void write_entry(const Sym& sym, string& str, HashMap& map, unsigned out) { + HashMap::iterator it = find_entry(sym, str, map); + + str += "y[" + to_string(out) + "]=" + it->second + ";\n"; + //cout << "wrote " << out << '\n'; +} + +#include +multi_function compile(const std::vector& syms) { + + //cout << "Multifunction " << syms.size() << endl; + // static stream to avoid fragmentation of these LARGE strings + static string str; + str.clear(); + str += make_prototypes(); + + str += "extern double func(const double* x, double* y) { \n "; + + multi_function result; + HashMap map(Sym::get_dag().size()); + + for (unsigned i = 0; i < syms.size(); ++i) { + write_entry(syms[i], str, map, i); + } + + str += ";}"; + + + /*static int counter = 0; + ostringstream nm; + nm << "cmp/compiled" << (counter++) << ".c"; + cout << "Saving as " << nm.str() << endl; + ofstream cmp(nm.str().c_str()); + cmp << str; + cmp.close(); + + //cout << "Multifunction " << syms.size() << endl; + cout << "Size of map " << map.size() << endl; +*/ + + result = (multi_function) symc_make(str.c_str(), "func"); + + if (result==0) { // error + cout << "Error in compile " << endl; + } + + return result; +} + +single_function compile(Sym sym) { + + ostringstream os; + + os << make_prototypes(); + os << "double func(const double* x) { return "; + + string code = c_print(sym); + os << code; + os << ";}"; + string func_str = os.str(); + + //cout << "compiling " << func_str << endl; + + return (single_function) symc_make(func_str.c_str(), "func"); +} + +/* finds and inserts the full code in a hashmap */ +HashMap::iterator find_code(Sym sym, HashMap& map) { + HashMap::iterator result = map.find(sym); + + if (result == map.end()) { // new entry + const SymVec& args = sym.args(); + vector argstr(args.size()); + for (unsigned i = 0; i < args.size(); ++i) { + argstr[i] = find_code(args[i], map)->second; + } + + // write out the code + const FunDef& fun = get_element(sym.token()); + string code = fun.c_print(argstr, vector()); + result = map.insert( make_pair(sym, code) ).first; // only want iterator + } + + return result; +} + +string print_code(Sym sym, HashMap& map) { + HashMap::iterator it = find_code(sym, map); + return it->second; +} + +void compile(const std::vector& syms, std::vector& functions) { + symc_init(); + + static ostringstream os; + os.str(""); + + os << make_prototypes(); + HashMap map(Sym::get_dag().size()); + for (unsigned i = 0; i < syms.size(); ++i) { + + os << "double func" << i << "(const double* x) { return "; + os << print_code(syms[i], map); //c_print(syms[i]); + os << ";}\n"; + + //symc_compile(os.str().c_str()); + //cout << "compiling " << os.str() << endl; + } + + os << ends; +#ifdef INTERVAL_DEBUG + //cout << "Compiling " << os.str() << endl; +#endif + + symc_compile(os.str().c_str()); + symc_link(); + + functions.resize(syms.size()); + for (unsigned i = 0; i < syms.size(); ++i) { + ostringstream os2; + os2 << "func" << i; + + functions[i] = (single_function) symc_get_fun(os2.str().c_str()); + } + +} + + + diff --git a/deprecated/eo/contrib/mathsym/eval/sym_compile.h b/deprecated/eo/contrib/mathsym/eval/sym_compile.h new file mode 100644 index 000000000..79a9d4977 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/eval/sym_compile.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SYMCOMPILE_H_ +#define SYMCOMPILE_H_ + +#include +#include + +typedef double (*single_function)(const double []); +typedef double (*multi_function)(const double[], double[]); + +/* + * Important, after every call of the functions below, the function pointers of the previous + * call are invalidated. Sorry, but that's the way the cookie crumbles (in tcc) + * */ + +single_function compile(Sym sym); +multi_function compile(const std::vector& sym); +void compile(const std::vector& sym, std::vector& functions); + +#endif diff --git a/deprecated/eo/contrib/mathsym/fun/FunDef.cpp b/deprecated/eo/contrib/mathsym/fun/FunDef.cpp new file mode 100644 index 000000000..3e2e7faac --- /dev/null +++ b/deprecated/eo/contrib/mathsym/fun/FunDef.cpp @@ -0,0 +1,891 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 "Sym.h" +#include "FunDef.h" +#include + +using namespace std; +using namespace boost::numeric; + +vector language; + +token_t add_function(FunDef* function) { + language.push_back(function); + return token_t(language.size()-1); +} + +const FunDef& get_element(token_t token) { return *language[token]; } + +/* Printing */ + +string c_print(const Sym& sym) { + return c_print(sym, vector()); +} + +string c_print(const Sym& sym, const vector& vars) { + const SymVec& args = sym.args(); + vector names(args.size()); + for (unsigned i = 0; i < args.size(); ++i) { + names[i] = c_print(args[i], vars); + } + return language[sym.token()]->c_print(names, vars); +} + +/* Evaluation */ + + +double eval(const Sym& sym, const std::vector& inputs) { + return language[sym.token()]->eval(sym.args(), inputs); +} + + +/* Interval Logic */ +Interval eval(const Sym& sym, const vector& inputs) { + const SymVec& args = sym.args(); + vector interv(args.size()); + for (unsigned i = 0; i < args.size(); ++i) { + interv[i] = eval(args[i], inputs); + + if (!valid(interv[i])) throw interval_error(); + } + return language[sym.token()]->eval(interv, inputs); +} + +/* */ +void add_function_to_table(LanguageTable& table, token_t token) { + const FunDef& fundef = *language[token]; + + if (fundef.has_varargs() == false) { + table.add_function(token, fundef.min_arity()); + } else { // sum or prod (or min or max) + table.add_function(token, 2); + } +} + + +// by default it is eager +double FunDef::eval(const SymVec& args, const vector& inputs) const { + vector values(args.size()); + for (unsigned i = 0; i < args.size(); ++i) { + values[i] = ::eval(args[i], inputs); + } + + return eval(values, inputs); +} + +/* Variable Handling */ +FunDef* make_var(int idx); // defined in FunDefs.h +static vector var_token; + +Sym SymVar(unsigned idx) { + if (var_token.size() <= idx) { + // it is new + var_token.resize(idx+1, token_t(-1)); + var_token[idx] = add_function( make_var(idx) ); + } else if (var_token[idx] == token_t(-1)) { + var_token[idx] = add_function( make_var(idx) ); + } + return Sym(var_token[idx]); +} + + +/* Constant Handling */ + +struct HashDouble{ + size_t operator()(double val) const { + unsigned long h = 0; + char* s = (char*)&val; + for (unsigned i=0 ; i DoubleSet; +typedef std::tr1::unordered_map LambdaSet; +#else +typedef hash_map DoubleSet; +typedef hash_map LambdaSet; +#endif + +static DoubleSet doubleSet; // for quick checking if a constant already exists +static vector token_value; + +static LambdaSet lambdaSet; +static vector token_lambda; + +static std::vector free_list; + +void delete_val(token_t token) { // clean up the information about this value + + if (is_constant(token)) { + //cout << "Deleting constant token " << token << endl; + double value = token_value[token]; + doubleSet.erase(value); + + delete language[token]; + language[token] = 0; + free_list.push_back(token); + } + else if (is_lambda(token)) { + //cout << "Deleting lambda token " << token << endl; + + Sym expression = token_lambda[token]; + lambdaSet.erase(expression); + + delete language[token]; + language[token] = 0; + free_list.push_back(token); + } +} + + +FunDef* make_const(double value); + +void extend_free_list(); + +Sym SymConst(double value) { + + DoubleSet::iterator it = doubleSet.find(value); + + if (it != doubleSet.end()) { + return Sym(it->second); // already exists + } + + + if (free_list.empty()) { // make space for tokens; + extend_free_list(); + } + + token_t token = free_list.back(); + free_list.pop_back(); + //cout << "Creating constant with token " << token << endl; + assert(language[token] == 0); + + language[token] = make_const(value); + + doubleSet[value] = token; + if (token_value.size() < token) token_value.resize(token+1); + token_value[token] = value; + + return Sym(token); +} + +/* LanguageTable depends on this one, XXX move somewhere safe.*/ +#include +extern Sym default_const() { return SymConst(rng.normal()); } + +/* The functions */ +namespace { + +class Var : public FunDef { + public : + unsigned idx; + string default_str; + + Var(unsigned _idx) : idx(_idx) { + ostringstream os; + os << "x[" << idx << ']'; // CompiledCode expects this form + default_str = os.str(); + } + + double eval(const vector& _, const vector& inputs) const { return inputs[idx]; } + double eval(const SymVec& _, const vector& inputs) const { return inputs[idx]; } + string c_print(const vector& _, const vector& names) const { + if (names.empty()) { + return default_str; + } + return names[idx]; + } + + Interval eval(const vector& _, const vector& inputs) const { + return inputs[idx]; + } + + unsigned min_arity() const { return 0; } + + string name() const { return "var"; } + +}; + +class Const : public FunDef { + public: + double value; + string value_str; + + Const(double _value) : value(_value) { + ostringstream os; + os.precision(17); + os.setf(ios::showpoint); + os << '(' << value << ')'; + value_str = os.str(); + } + + + double eval(const vector& _, const vector& inputs) const { return value; } + double eval(const SymVec& _, const vector& inputs) const { return value; } + string c_print(const vector& _, const vector& names) const { + return value_str; + } + + Interval eval(const vector& _, const vector& inputs) const { + return Interval(value); + } + + unsigned min_arity() const { return 0; } + + string name() const { return "parameter"; } +}; + +} // namespace + +void get_constants(Sym sym, vector& ret) { + token_t token = sym.token(); + if (is_constant(token)) { + double val = static_cast(language[token])->value; + ret.push_back(val); + } + + const SymVec& args = sym.args(); + for (unsigned i = 0; i < args.size(); ++i) { + get_constants(args[i], ret); + } + +} + +double get_constant_value(token_t token) { + return static_cast(language[token])->value; +} + +/** Get out the values for all constants in the expression */ +vector get_constants(Sym sym) { + vector retval; + get_constants(sym, retval); + return retval; +} + +/** Set the values for all constants in the expression. Vector needs to be the same size as the one get_constants returns + * The argument isn't touched, it will return a new sym with the constants set. */ +Sym set_constants(Sym sym, vector::const_iterator& it) { + + token_t token = sym.token(); + if (is_constant(token)) { + return SymConst(*it++); + } + + SymVec args = sym.args(); + for (unsigned i = 0; i < args.size(); ++i) { + args[i] = set_constants(args[i], it); + } + + return Sym(token, args); +} + +Sym set_constants(Sym sym, const vector& constants) { + vector::const_iterator it = constants.begin(); + return set_constants(sym, it); +} + +// Get functions out, excluding Const and Var +vector get_defined_functions() { + vector res; + for (unsigned i = 0; i < language.size(); ++i) { + res.push_back(language[i]); + + if (is_constant(i) || is_variable(i)) { + res.back() = 0; // erase + } + } + + return res; +} + +FunDef* make_var(int idx) { return new Var(idx); } +FunDef* make_const(double value) { return new Const(value); } + +bool is_constant(token_t token) { + const Const* cnst = dynamic_cast( language[token] ); + return cnst != 0; +} + +bool is_variable(token_t token) { + const Var* var = dynamic_cast( language[token] ); + return var != 0; +} + +unsigned get_variable_index(token_t token) { + const Var* var = static_cast( language[token] ); + return var->idx; +} + +namespace { +class Lambda : public FunDef { + public: + Sym expression; + int arity; + + Lambda(Sym expr, int arity_) : expression(expr), arity(arity_) {} + + double eval(const vector& vals, const vector& _) const { + return ::eval(expression, vals); + } + + string c_print(const vector& args, const vector& _) const { + return string("/*f*/") + ::c_print(expression, args) + string("/*eof*/"); + } + + Interval eval(const vector& args, const vector& _) const { + return ::eval(expression, args); + } + + unsigned min_arity() const { return arity; } + string name() const { return "F"; } + +}; + Sym normalize(Sym sym, SymVec& args) { + // check if it's a variable + token_t token = sym.token(); + const Var* var = dynamic_cast< const Var*>(language[token]); + + if (var != 0) { + for (unsigned i = 0; i < args.size(); ++i) { + if (sym == args[i]) { + return SymVar(i); // replace with reference to arg + } + } + + // not replaced, add it + args.push_back(sym); + return SymVar(args.size()-1); + + } + + SymVec a = sym.args(); + for (unsigned i = 0; i < a.size(); ++i) { + a[i] = normalize(a[i], args); + } + + return Sym(token, a); + } +} + +bool is_lambda(token_t token) { + const Lambda* lambda = dynamic_cast( language[token]); + return lambda != 0; +} + +std::ostream& print_list(Sym sym, ostream& os) { + os << sym.token() << ' '; + + const SymVec& args = sym.args(); + for (unsigned i = 0; i < args.size(); ++i) { + print_list(args[i], os); + } + return os; +} + +token_t new_lambda(Sym sym, int arity) { + // check if already present + + LambdaSet::iterator it = lambdaSet.find(sym); + if (it != lambdaSet.end()) { + return it->second; + } + + + // new, insert + Lambda* lambda = new Lambda(sym, arity); + + if (free_list.empty()) { + extend_free_list(); + } + + token_t token = free_list.back(); + free_list.pop_back(); + language[token] = lambda; + + lambdaSet[sym] = token; + if (token_lambda.size() <= token) token_lambda.resize(token+1); + token_lambda[token] = sym; + + return token; +} + +/* Compression */ +typedef hash_map OccMap; + +void count_occurances(Sym sym, OccMap& occ) { + occ[sym]++; + const SymVec& args = sym.args(); + for (unsigned i = 0; i < args.size(); ++i) { + count_occurances(args[i], occ); + } +} + +Sym create_lambda(Sym sym, OccMap& occ, unsigned nvars, vector& args) { + unsigned o = occ[sym]; + unsigned sz = sym.size(); + + if (o * sz > o + sz + nvars || is_variable(sym.token()) ) { + // check if it's already present + for (unsigned i = 0; i < args.size(); ++i) { + if (args[i] == sym) { + return SymVar(i); + } + } + // push_back + args.push_back(sym); + return SymVar(args.size()-1); + } + + SymVec sym_args = sym.args(); + for (unsigned i = 0; i < sym_args.size(); ++i) { + sym_args[i] = create_lambda(sym_args[i], occ, nvars, args); + } + + return Sym(sym.token(), sym_args); + +} + +Sym compress(Sym sym) { + OccMap occ(sym.size()); + count_occurances(sym, occ); + + unsigned nvars = 0; + for (OccMap::iterator it = occ.begin(); it != occ.end(); ++it) { + if (is_variable(it->first.token())) nvars++; + } + + SymVec args; + Sym body = create_lambda(sym, occ, nvars, args); + + + if (body.size() < sym.size()) { + // see if the body can be compressed some more + body = compress(body); + + token_t token = new_lambda(body, args.size()); + + for (unsigned i = 0; i < args.size(); ++i) { + args[i] = compress(args[i]); + } + + Sym result = Sym(token, args); + return compress(result); // see if it can be compressed some more + } + + return sym; +} + +Sym SymLambda(Sym expr) { return compress(expr); } + +Sym expand(Sym expr, const SymVec& args) { + + const Var* var = dynamic_cast( language[expr.token()] ); + if (var != 0) { + return args[var->idx]; + } + + SymVec expr_args = expr.args(); + for (unsigned i = 0; i < expr_args.size(); ++i) { + expr_args[i] = expand(expr_args[i], args); + } + + return Sym(expr.token(), expr_args); +} + +Sym SymUnlambda(Sym sym) { + Sym retval = sym; + const Lambda* lambda = dynamic_cast( language[sym.token()] ); + if (lambda != 0) { + retval = expand(lambda->expression, sym.args()); + } + + return retval; +} + +Sym expand_all(Sym sym) { + SymVec args = sym.args(); + for (unsigned i = 0; i < args.size(); ++i) { + args[i] = expand_all(args[i]); + } + + Sym nw = SymUnlambda( Sym(sym.token(), args) ); + + if (nw != sym) { + nw = expand_all(nw); + } + + return nw; +} + +namespace { + +class Sum : public FunDef { + + public : + + double eval(const vector& vals, const vector& _) const { + double res = 0; + for (unsigned i = 0; i < vals.size(); ++i) res += vals[i]; + return res; + } + + string c_print(const vector& args, const vector& _) const { + if (args.empty()) { return "0.0"; } + + ostringstream os; + os << "(" << args[0]; + for (unsigned i = 1; i < args.size(); ++i) { + os << "+" << args[i]; + } + os << ")"; + return os.str(); + } + + Interval eval(const vector& args, const vector& inputs) const { + Interval interv(0.0); + for (unsigned i = 0; i < args.size(); ++i) { + interv += args[i]; + } + return interv; + } + + unsigned min_arity() const { return 0; } + bool has_varargs() const { return true; } + + string name() const { return "sum"; } +}; + + +class Prod : public FunDef { + + public : + + double eval(const vector& vals, const vector& _) const { + double res = 1; + for (unsigned i = 0; i < vals.size(); ++i) res *= vals[i]; + return res; + } + + string c_print(const vector& args, const vector& _) const { + if (args.empty()) { return "1.0"; } + + ostringstream os; + os << "(" << args[0]; + for (unsigned i = 1; i < args.size(); ++i) { + os << "*" << args[i]; + } + os << ")"; + + return os.str(); + } + + Interval eval(const vector& args, const vector& inputs) const { + Interval interv(1.0); + for (unsigned i = 0; i < args.size(); ++i) { + interv *= args[i]; + } + return interv; + } + + unsigned min_arity() const { return 0; } + bool has_varargs() const { return true; } + + string name() const { return "prod"; } +}; + + +class Power : public FunDef { + public : + double eval(const vector& vals, const vector& _) const { + return pow(vals[0], vals[1]); + } + + string c_print(const vector& args, const vector& _) const { + return "pow(" + args[0] + ',' + args[1] + ')'; + } + + Interval eval(const vector& args, const vector& _) const { + Interval first = args[0]; + Interval second = args[1]; + Interval lg = log(first); + if (!valid(lg)) throw interval_error(); + return exp(second * lg); + } + + unsigned min_arity() const { return 2; } + + string name() const { return "pow"; } +}; + +class IsNeg : public FunDef { + + public: + double eval(const vector& vals, const vector& _) const { + if (vals[0] < 0.0) return vals[1]; + return vals[2]; + } + + double eval(const Sym& sym, const vector& inputs) const { + const SymVec& args = sym.args(); + double arg0 = ::eval(args[0], inputs); + if (arg0 < 0.0) { + return ::eval(args[1], inputs); + } + return ::eval(args[2], inputs); + } + + string c_print(const vector& args, const vector& _) const { + return "((" + args[0] + "<0.0)?" + args[1] + ":" + args[2]+")"; + } + + Interval eval(const vector& args, const vector& _) const { + Interval a0 = args[0]; + if (a0.upper() < 0.0) return args[1]; + if (a0.lower() >= 0.0) return args[2]; + + return Interval( std::min(args[1].lower(), args[2].lower()), std::max(args[1].upper(), args[2].upper())); + } + + unsigned min_arity() const { return 3; } + + string name() const { return "ifltz"; } +}; + +template +class Unary : public FunDef { + + Func un; + + double eval(const vector& vals, const vector& _) const { + return un(vals[0]); + } + + string c_print(const vector& args, const vector& _) const { + return un(args[0]); + } + + Interval eval(const vector& args, const vector& _) const { + return un(args[0]); + } + + unsigned min_arity() const { return 1; } + + string name() const { return un.name(); } + +}; + +struct Inv { + double operator()(double val) const { return 1.0 / val; } + string operator()(string v) const { return "(1./" + v + ")"; } + Interval operator()(Interval v) const { return 1.0 / v; } + + string name() const { return "inv"; } +}; + +struct Min { + double operator()(double val) const { return -val; } + string operator()(string v) const { return "(-" + v + ")"; } + Interval operator()(Interval v) const { return -v; } + + string name() const { return "min"; } +}; + +} // namespace + +string prototypes = "double pow(double, double);"; +string get_prototypes() { return prototypes; } +unsigned add_prototype(string str) { prototypes += string("double ") + str + "(double);"; return prototypes.size(); } + +token_t add_function(FunDef* function, token_t where) { + if (language.size() <= where) language.resize(where+1); + language[where] = function; + return 0; +} + +namespace { + +#define FUNCDEF(funcname) struct funcname##_struct { \ + double operator()(double val) const { return funcname(val); }\ + string operator()(string val) const { return string(#funcname) + '(' + val + ')'; }\ + Interval operator()(Interval val) const { return funcname(val); }\ + string name() const { return string(#funcname); }\ +};\ +static const token_t funcname##_token_static = add_function( new Unary, funcname##_token);\ +unsigned funcname##_size = add_prototype(#funcname); + +static token_t ssum_token = add_function( new Sum , sum_token); +static token_t sprod_token = add_function( new Prod, prod_token); +static token_t sinv_token = add_function( new Unary, inv_token); +static token_t smin_token = add_function( new Unary, min_token); +static token_t spow_token = add_function( new Power, pow_token); +static token_t sifltz_token = add_function( new IsNeg, ifltz_token); + +FUNCDEF(sin); +FUNCDEF(cos); +FUNCDEF(tan); +FUNCDEF(asin); +FUNCDEF(acos); +FUNCDEF(atan); + +FUNCDEF(sinh); +FUNCDEF(cosh); +FUNCDEF(tanh); +FUNCDEF(asinh); +FUNCDEF(acosh); +FUNCDEF(atanh); + +FUNCDEF(exp); +FUNCDEF(log); +} // namespace + +double sqr(double x) { return x*x; } + +namespace { +FUNCDEF(sqr); +FUNCDEF(sqrt); + +const int buildInFunctionOffset = language.size(); +} // namespace + +void add_tokens() { + unsigned sz = language.size(); + language.resize(sz + sz+1); // double + + for (unsigned i = sz; i < language.size(); ++i) { + free_list.push_back(i); + } +} + +void extend_free_list() { + // first check if we can clean up unused tokens; + const vector& refcount = Sym::token_refcount(); + for (unsigned i = buildInFunctionOffset; i < refcount.size(); ++i) { + if (language[i] == 0) continue; + + bool c = is_constant(i); + bool l = is_lambda(i); + + if (refcount[i] == 0 && (c || l)) { + + if (c) { + doubleSet.erase(token_value[i]); + } + + if (l) { + lambdaSet.erase(token_lambda[i]); + } + + delete language[i]; + language[i] = 0; + free_list.push_back(i); + } + } + + // if still empty, add new tokens + if (free_list.empty()) { + add_tokens(); + } +} + + +/* Serialization */ +void write_raw(ostream& os, const Sym& sym) { + token_t token = sym.token(); + const SymVec& args = sym.args(); + + if (is_constant(token)) { + os << "c" << language[token]->c_print(vector(), vector()); + } else { + + const Var* var = dynamic_cast( language[token] ); + + if (var != 0) { + os << "v" << var->idx; + } else { + os << "f" << token << ' ' << args.size(); + } + } + + for (unsigned i = 0; i < args.size(); ++i) { + write_raw(os, args[i]); + } +} + +string write_raw(const Sym& sym) { + + ostringstream os; + write_raw(os, sym); + + return os.str(); +} + +Sym read_raw(istream& is) { + char id = is.get(); + + switch (id) { + case 'c' : + { + double val; + is.get(); // skip '(' + is >> val; + is.get(); // skip ')' + return SymConst(val); + } + case 'v' : + { + unsigned idx; + is >> idx; + return SymVar(idx); + } + case 'f' : + { + token_t token; + unsigned arity; + is >> token; + is >> arity; + SymVec args(arity); + for (unsigned i = 0; i < arity; ++i) { + args[i] = read_raw(is); + } + + return Sym(token, args); + } + default : { + cerr << "Character = " << id << " Could not read formula from stream" << endl; + exit(1); + } + + } + + return Sym(); +} + +Sym read_raw(string str) { + istringstream is(str); + return read_raw(is); +} + +void read_raw(istream& is, Sym& sym) { + sym = read_raw(is); +} + diff --git a/deprecated/eo/contrib/mathsym/fun/FunDef.h b/deprecated/eo/contrib/mathsym/fun/FunDef.h new file mode 100644 index 000000000..d4ed95a1d --- /dev/null +++ b/deprecated/eo/contrib/mathsym/fun/FunDef.h @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef FUNCTION_DEF_H_ +#define FUNCTION_DEF_H_ + +#include +#include +#include +#include + +#include "sym/Sym.h" +#include "eval/Interval.h" + +class FunDef { + public: + + virtual ~FunDef() {} + + // (possibly) lazy evaluation function, default implementation calls 'eager' eval + virtual double eval(const SymVec& args, const std::vector& inputs) const; + + // eager evaluation function + virtual double eval(const std::vector& args, const std::vector& inputs) const = 0; + + // interval evaluation + virtual Interval eval(const std::vector& args, const std::vector& inputs) const = 0; + + // prints 'c' like code + virtual std::string c_print(const std::vector& names, const std::vector& names) const = 0; + + virtual unsigned min_arity() const = 0; + virtual bool has_varargs() const { return false; } // sum, prod, min, max are variable arity + + virtual std::string name() const = 0; + + protected: + +}; + +/** Gets out all function that are defined (excluding constants and variables) */ +extern std::vector get_defined_functions(); + +/** Gets a specific function (including vars and constants) out */ +extern const FunDef& get_element(token_t token); + +/** Single case evaluation */ +extern double eval(const Sym& sym, const std::vector& inputs); + +/** Static analysis through interval arithmetic */ +extern Interval eval(const Sym& sym, const std::vector& inputs); + +/** Pretty printers, second version allows setting of variable names */ +extern std::string c_print(const Sym& sym); + +/** Pretty printers, allows setting of variable names */ +extern std::string c_print(const Sym& sym, const std::vector& var_names); + +/** Pretty printer streamer */ +inline std::ostream& operator<<(std::ostream& os, const Sym& sym) { return os << c_print(sym); } + +/* Support for Ephemeral Random Constants (ERC) */ + +/** Create constant with this value, memory is managed. If reference count drops to zero value is deleted. */ +extern Sym SymConst(double value); +/** Create variable */ +extern Sym SymVar(unsigned idx); + +/** Create 'lambda expression; + * This is a neutral operation. It will replace + * all variables in the expression by arguments, + * wrap the expression in a Lambda function + * and returns a tree applying the lambda function + * to the original variable. + * + * A call like SymLambda( SymVar(1) + SymVar(1) * 3.1) will result in + * a Lambda function (a0 + a0 * 3.1) with one argument: SymVar(1)*/ + +extern Sym SymLambda(Sym expression); + +extern Sym SymUnlambda(Sym sym); + +/** Expands all lambda expressions inline */ +extern Sym expand_all(Sym sym); +extern Sym compress(Sym sym); + +/** Get out the values for all constants in the expression */ +std::vector get_constants(Sym sym); + +/** Set the values for all constants in the expression. Vector needs to be the same size as the one get_constants returns + * The argument isn't touched, it will return a new sym with the constants set. */ +Sym set_constants(Sym sym, const std::vector& constants); + +/** check if a token is a constant */ +extern bool is_constant(token_t token); +extern double get_constant_value(token_t token); +/** check if a token is a variable */ +extern bool is_variable(token_t token); +extern unsigned get_variable_index(token_t token); + +/** check if a token is a user/automatically defined function */ +extern bool is_lambda(token_t token); + + +/** simplifies a sym (sym_operations.cpp) Currently only simplifies constants */ +extern Sym simplify(Sym sym); + +/** differentiates a sym to a token (sym_operations.cpp) + * The token can be a variable or a constant +*/ +extern Sym differentiate(Sym sym, token_t dx); +struct differentiation_error{}; // thrown in case of ifltz + +/* Add function to the language table (and take a guess at the arity) */ +class LanguageTable; +extern void add_function_to_table(LanguageTable& table, token_t token); + +enum { + sum_token, + prod_token, + inv_token, + min_token, + pow_token, + ifltz_token, + sin_token, cos_token, tan_token, + asin_token, acos_token, atan_token, + sinh_token, cosh_token, tanh_token, + acosh_token, asinh_token, atanh_token, + exp_token, log_token, + sqr_token, sqrt_token +}; + +/* Defition of function overloads: for example, this define the function 'Sym sin(Sym)' */ + +#define HEADERFUNC(name) inline Sym name(Sym arg) { return Sym(name##_token, arg); } + +/* This defines the tokens: sin_token, cos_token, etc. */ +HEADERFUNC(inv); +HEADERFUNC(sin); +HEADERFUNC(cos); +HEADERFUNC(tan); +HEADERFUNC(asin); +HEADERFUNC(acos); +HEADERFUNC(atan); + +HEADERFUNC(sinh); +HEADERFUNC(cosh); +HEADERFUNC(tanh); +HEADERFUNC(asinh); +HEADERFUNC(acosh); +HEADERFUNC(atanh); + +HEADERFUNC(exp); +HEADERFUNC(log); + +HEADERFUNC(sqr); +HEADERFUNC(sqrt); + +/* Get the prototype functions out, this is needed for compilation */ +extern std::string get_prototypes(); + +// reading and writing in internal format, no parser for symbolic functions implemented yet +extern std::string write_raw(const Sym& sym); +extern void write_raw(std::ostream& os, const Sym& sym); +extern Sym read_raw(std::string str); +extern Sym read_raw(std::istream& is); +extern void read_raw(std::istream& is, Sym& sym); + +#include "SymOps.h" + +#endif + diff --git a/deprecated/eo/contrib/mathsym/fun/SymOps.cpp b/deprecated/eo/contrib/mathsym/fun/SymOps.cpp new file mode 100644 index 000000000..2d66b0d05 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/fun/SymOps.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "FunDef.h" +#include "SymOps.h" +#include "Sym.h" + +using namespace std; + +void collect(token_t t, Sym a, SymVec& args) { + + if (a.token() == t) { + const SymVec& a_args = a.args(); + for (unsigned i = 0; i < a_args.size(); ++i) { + collect(t, a_args[i], args); + } + return; + } + + args.push_back(a); +} + +Sym operator+(Sym a, Sym b) { + + SymVec args; + + collect(sum_token, a, args); + collect(sum_token, b, args); + + return Sym(sum_token, args); +} + +Sym operator*(Sym a, Sym b) { + + SymVec args; + + collect(prod_token, a, args); + collect(prod_token, b, args); + + return Sym(prod_token, args); +} + +Sym operator/(Sym a, Sym b) { + + SymVec args; + + collect(prod_token, a, args); + + SymVec args2; + collect(prod_token, b, args2); + + SymVec inv; + inv.push_back(Sym(prod_token, args2)); + + args.push_back( Sym(inv_token, inv) ); + + return Sym(prod_token, args); +} + +Sym operator-(Sym a, Sym b) { + + SymVec args; + + collect(sum_token, a, args); + + SymVec args2; + collect(sum_token, b, args2); + + SymVec min; + min.push_back(Sym(sum_token, args2)); + + args.push_back( Sym(min_token, min) ); + + return Sym(sum_token, args); +} + +Sym operator-(Sym a) { + return Sym(min_token, a); +} + +Sym pow(Sym a, Sym b) { + SymVec args; + args.push_back(a); + args.push_back(b); + return Sym(pow_token, args); +} + +Sym ifltz(Sym a, Sym b, Sym c) { + SymVec args; + args.push_back(a); + args.push_back(b); + args.push_back(c); + return Sym(ifltz_token, args); +} + diff --git a/deprecated/eo/contrib/mathsym/fun/SymOps.h b/deprecated/eo/contrib/mathsym/fun/SymOps.h new file mode 100644 index 000000000..a11994ff6 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/fun/SymOps.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SYMOPS_H +#define SYMOPS_H + +#include "sym/Sym.h" + +extern Sym operator+(Sym a, Sym b); +extern Sym operator*(Sym a, Sym b); +extern Sym operator/(Sym a, Sym b); +extern Sym operator-(Sym a, Sym b); +extern Sym pow(Sym a, Sym b); +extern Sym ifltz(Sym a, Sym b, Sym c); +extern Sym operator-(Sym a); + +#endif diff --git a/deprecated/eo/contrib/mathsym/fun/sym_operations.cpp b/deprecated/eo/contrib/mathsym/fun/sym_operations.cpp new file mode 100644 index 000000000..124c657ad --- /dev/null +++ b/deprecated/eo/contrib/mathsym/fun/sym_operations.cpp @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include + +using namespace std; + +Sym simplify_constants(Sym sym) { + + SymVec args = sym.args(); + token_t token = sym.token(); + + bool has_changed = false; + bool all_constants = true; + + for (unsigned i = 0; i < args.size(); ++i) { + + Sym arg = simplify_constants(args[i]); + + if (arg != args[i]) { + has_changed = true; + } + args[i] = arg; + + all_constants &= is_constant(args[i].token()); + } + + if (args.size() == 0) { + + if (sym.token() == sum_token) return SymConst(0.0); + if (sym.token() == prod_token) return SymConst(1.0); + + return sym; // variable or constant + } + + if (all_constants) { + // evaluate + + vector dummy; + + double v = ::eval(sym, dummy); + + Sym result = SymConst(v); + + return result; + } + + if (has_changed) { + return Sym(token, args); + } + + return sym; + +} + +// currently only simplifies constants +Sym simplify(Sym sym) { + + return simplify_constants(sym); + +} + +Sym derivative(token_t token, Sym x) { + Sym one = Sym(prod_token); + + switch (token) { + case inv_token : return Sym(inv_token, sqr(x)); + + case sin_token : return -cos(x); + case cos_token : return sin(x); + case tan_token : return one + sqr(tan(x)); + + case asin_token : return inv( sqrt(one - sqr(x))); + case acos_token: return -inv( sqrt(one - sqr(x))); + case atan_token : return inv( sqrt(one + sqr(x))); + + case cosh_token : return -sinh(x); + case sinh_token : return cosh(x); + case tanh_token : return one - sqr( tanh(x) ); + + case asinh_token : return inv( sqrt( one + sqr(x) )); + case acosh_token : return inv( sqrt(x-one) * sqrt(x + one) ); + case atanh_token : return inv(one - sqr(x)); + + case exp_token : return exp(x); + case log_token : return inv(x); + + case sqr_token : return SymConst(2.0) * x; + case sqrt_token : return SymConst(0.5) * inv( sqrt(x)); + default : + throw differentiation_error(); + } + + return x; +} + +extern Sym differentiate(Sym sym, token_t dx) { + + token_t token = sym.token(); + + Sym zero = Sym(sum_token); + Sym one = Sym(prod_token); + + if (token == dx) { + return one; + } + + SymVec args = sym.args(); + + if (args.size() == 0) { // df/dx with f != x + return zero; + } + + switch (token) { + + case sum_token: + { + for (unsigned i = 0; i < args.size(); ++i) { + args[i] = differentiate(args[i], dx); + } + + if (args.size() == 1) return args[0]; + return Sym(sum_token, args); + } + case min_token : + { + return -differentiate(args[0],dx); + } + case prod_token: + { + if (args.size() == 1) return differentiate(args[0], dx); + + if (args.size() == 2) { + return args[0] * differentiate(args[1], dx) + args[1] * differentiate(args[0], dx); + } + // else + Sym c = args.back(); + args.pop_back(); + Sym f = Sym(prod_token, args); + Sym df = differentiate( f, dx); + + return c * df + f * differentiate(c,dx); + } + case pow_token : + { + return pow(args[0], args[1]) * args[1] * inv(args[0]); + } + case ifltz_token : + { // cannot be differentiated + throw differentiation_error(); // TODO define proper exception + } + + default: // unary function: apply chain rule + { + Sym arg = args[0]; + return derivative(token, arg) * differentiate(arg, dx); + } + } + +} diff --git a/deprecated/eo/contrib/mathsym/fun/util.cpp b/deprecated/eo/contrib/mathsym/fun/util.cpp new file mode 100644 index 000000000..83e751dec --- /dev/null +++ b/deprecated/eo/contrib/mathsym/fun/util.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 + +using namespace std; + +double error(string errstr) { + cerr << "ERROR: " << errstr << endl; + exit(1); +} + diff --git a/deprecated/eo/contrib/mathsym/gen/LanguageTable.cpp b/deprecated/eo/contrib/mathsym/gen/LanguageTable.cpp new file mode 100644 index 000000000..293f6569b --- /dev/null +++ b/deprecated/eo/contrib/mathsym/gen/LanguageTable.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + + +#include "LanguageTable.h" +#include "Sym.h" + +#include + +using namespace std; + +extern Sym default_const(); + +class LanguageImpl { + public : + std::vector vars; + LanguageTable::erc_func erc; + + std::vector functions; + std::vector< std::vector > functions_per_arity; + + LanguageImpl() : erc(default_const) {} +}; + +LanguageTable::LanguageTable() { + pimpl = new LanguageImpl; +} + +LanguageTable::~LanguageTable() { + delete pimpl; +} + +LanguageTable::LanguageTable(const LanguageTable& that) { + pimpl = new LanguageImpl(*that.pimpl); +} + +LanguageTable& LanguageTable::operator=(const LanguageTable& that) { + *pimpl = *that.pimpl; + return *this; +} + +void LanguageTable::add_function(token_t token, unsigned arity) { + functor_t f = {token, arity}; + add_function( f ); +} + +void LanguageTable::add_function(functor_t f) { + + if (f.arity > 0) { + pimpl->functions.push_back(f); + + } else { + pimpl->vars.push_back(Sym(f.token)); + } + + if (pimpl->functions_per_arity.size() <= f.arity) pimpl->functions_per_arity.resize(f.arity+1); + pimpl->functions_per_arity[f.arity].push_back(f.token); + +} + +void LanguageTable::set_erc( erc_func func) { pimpl->erc = func; } + +/* Getting info out */ + +extern Sym SymConst(double val); + +Sym LanguageTable::get_random_var() const { return rng.choice(pimpl->vars); } +Sym LanguageTable::get_random_const() const { return pimpl->erc(); } + +functor_t LanguageTable::get_random_function() const +{ + return rng.choice(pimpl->functions); +} + +token_t LanguageTable::get_random_function(token_t token, unsigned arity) const +{ + if (pimpl->functions_per_arity.size() <= arity || pimpl->functions_per_arity[arity].empty()) { + return token; // return original token if no functions of this arity are found + } + return rng.choice(pimpl->functions_per_arity[arity]); +} + + + diff --git a/deprecated/eo/contrib/mathsym/gen/LanguageTable.h b/deprecated/eo/contrib/mathsym/gen/LanguageTable.h new file mode 100644 index 000000000..978ef3f5a --- /dev/null +++ b/deprecated/eo/contrib/mathsym/gen/LanguageTable.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef LANGUAGE_TABLE_H +#define LANGUAGE_TABLE_H + +#include + +class LanguageImpl; +class Sym; + +class LanguageTable { + + LanguageImpl* pimpl; + + public: + + LanguageTable(); + ~LanguageTable(); + + LanguageTable(const LanguageTable& org); + + LanguageTable& operator=(const LanguageTable& org); + + /* setting it up */ + typedef Sym (*erc_func)(); + + void add_function(token_t token, unsigned arity); + void add_function(functor_t functor); + void set_erc(erc_func func); + + /* Getting info out */ + + Sym get_random_var() const; + Sym get_random_const() const; + + functor_t get_random_function() const; + token_t get_random_function(token_t org, unsigned arity) const; +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/gen/NodeSelector.cpp b/deprecated/eo/contrib/mathsym/gen/NodeSelector.cpp new file mode 100644 index 000000000..aefa4dd6f --- /dev/null +++ b/deprecated/eo/contrib/mathsym/gen/NodeSelector.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "NodeSelector.h" +#include "Sym.h" + +#include + +// If subtree is not set (by randomnodeselector for instance, find it now +Sym NodeSelector::NodeSelection::subtree() { + if (subtree_.empty()) { + subtree_ = get_subtree(root_, subtree_index_); + } + return subtree_; +} + +NodeSelector::NodeSelection RandomNodeSelector::select_node(Sym sym) const { + unsigned idx = rng.random(sym.size()); + return NodeSelection(sym, idx, Sym() ); // empty subtree, find it when needed +} + +NodeSelector::NodeSelection BiasedNodeSelector::select_node(Sym sym) const { + + unsigned p = rng.random(sym.size()); + Sym res; + for (unsigned i = 0; i < nRounds; ++i) { + res = get_subtree(sym, p); + + if (res.args().size() > 0) break; + + p = rng.random(sym.size()); + } + + return NodeSelection(sym, p, res); +} + diff --git a/deprecated/eo/contrib/mathsym/gen/NodeSelector.h b/deprecated/eo/contrib/mathsym/gen/NodeSelector.h new file mode 100644 index 000000000..c8b2ccf09 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/gen/NodeSelector.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef NODESELECTOR_H +#define NODESELECTOR_H + +#include + +/** Base class for selecting nodes */ +class NodeSelector { + public: + + class NodeSelection { + Sym root_; + unsigned subtree_index_; + Sym subtree_; + + public : + NodeSelection(Sym r, unsigned idx, Sym s) + : root_(r), subtree_index_(idx), subtree_(s) {} + + Sym root() const { return root_; } + unsigned idx() const { return subtree_index_; } + Sym subtree(); + + }; + + virtual ~NodeSelector() {} + + virtual NodeSelection select_node(Sym sym) const = 0; +}; + + +/** Select nodes uniformly */ +class RandomNodeSelector : public NodeSelector { + public: + NodeSelection select_node(Sym sym) const; +}; + +/** A node selector that does a specified number of rounds ignoring terminals */ +class BiasedNodeSelector : public NodeSelector { + public: + unsigned nRounds; + + BiasedNodeSelector() : nRounds(3) {} // 3: for binary trees 87.5% chance of selecting an internal node + BiasedNodeSelector(unsigned n) : nRounds(n) {} + + NodeSelection select_node(Sym sym) const; +}; + +#endif diff --git a/deprecated/eo/contrib/mathsym/gen/TreeBuilder.cpp b/deprecated/eo/contrib/mathsym/gen/TreeBuilder.cpp new file mode 100644 index 000000000..70b7ef53e --- /dev/null +++ b/deprecated/eo/contrib/mathsym/gen/TreeBuilder.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 "TreeBuilder.h" + +Sym TreeBuilder::make_terminal() const { + if (rng.flip(vcprob)) { + return table.get_random_var(); + } + + return table.get_random_const(); +} + +Sym TreeBuilder::build_tree(unsigned max_depth, bool grow) const { + if (max_depth == 0 || grow && rng.random(2) == 0) { + return make_terminal(); + } + + // pick a random function, no matter what arity + + functor_t func = table.get_random_function(); + + SymVec args(func.arity); + + for (unsigned i = 0; i < args.size(); ++i) { + args[i] = build_tree(max_depth-1, grow); + } + + return Sym(func.token, args); +} + diff --git a/deprecated/eo/contrib/mathsym/gen/TreeBuilder.h b/deprecated/eo/contrib/mathsym/gen/TreeBuilder.h new file mode 100644 index 000000000..57cb54582 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/gen/TreeBuilder.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef TREEBUILDER_H_ +#define TREEBUILDER_H_ + +#include "sym/Sym.h" +#include "LanguageTable.h" + +class TreeBuilder { + const LanguageTable& table; + + // probability of selecting a var versus a const when the choice boils down to selecting a terminal + double vcprob; + + Sym make_terminal() const; + public: + + TreeBuilder(const LanguageTable& t) : table(t), vcprob(0.9) {}; + TreeBuilder(const LanguageTable& t, double vc) : table(t), vcprob(vc) {}; + + void set_var_vs_const_probability(double p) { vcprob = p; } + + Sym build_tree(unsigned max_depth, bool grow) const; + + void build_tree(Sym& tree, unsigned max_depth, bool grow) const { tree = build_tree(max_depth, grow); } + +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/header b/deprecated/eo/contrib/mathsym/header new file mode 100644 index 000000000..a4ea44583 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/header @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + diff --git a/deprecated/eo/contrib/mathsym/regression/Dataset.cpp b/deprecated/eo/contrib/mathsym/regression/Dataset.cpp new file mode 100644 index 000000000..bdb314551 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/Dataset.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "Dataset.h" +#include +#include + +#include + +using namespace std; + +class DataSetImpl { + public: + vector< vector > inputs; + vector targets; + + void read_data(vector strings) { + // find the number of inputs + + istringstream cnt(strings[0]); + unsigned n = 0; + for (;;) { + string s; + cnt >> s; + if (!cnt) break; + ++n; + } + + inputs.resize(strings.size(), vector(n-1)); + targets.resize(strings.size()); + + for (unsigned i = 0; i < strings.size(); ++i) { + istringstream is(strings[i]); + for (unsigned j = 0; j < n; ++j) { + + if (!is) { + cerr << "Too few targets in record " << i << endl; + exit(1); + } + + if (j < n-1) { + is >> inputs[i][j]; + } else { + is >> targets[i]; + } + + } + } + + } + +}; + +Dataset::Dataset() { pimpl = new DataSetImpl; } +Dataset::~Dataset() { delete pimpl; } +Dataset::Dataset(const Dataset& that) { pimpl = new DataSetImpl(*that.pimpl); } +Dataset& Dataset::operator=(const Dataset& that) { *pimpl = *that.pimpl; return *this; } + +unsigned Dataset::n_records() const { return pimpl->targets.size(); } +unsigned Dataset::n_fields() const { return pimpl->inputs[0].size(); } +const std::vector& Dataset::get_inputs(unsigned record) const { return pimpl->inputs[record]; } +double Dataset::get_target(unsigned record) const { return pimpl->targets[record]; } + +double error(string errstr); + +void Dataset::load_data(std::string filename) { + vector strings; // first load it in strings + + ifstream is(filename.c_str()); + + for(;;) { + string s; + getline(is, s); + if (!is) break; + + if (s[0] == '#') continue; // comment, skip + + strings.push_back(s); + } + + is.close(); + + if (strings.size() == 0) { + error("No data could be loaded"); + } + + pimpl->read_data(strings); + +} + +std::vector Dataset::input_minima() const { + vector >& in = pimpl->inputs; + + vector mn(in[0].size(), 1e+50); + for (unsigned i = 0; i < in.size(); ++i) { + for (unsigned j = 0; j < in[i].size(); ++j) { + mn[j] = std::min(mn[j], in[i][j]); + } + } + + return mn; +} + +vector Dataset::input_maxima() const { + vector >& in = pimpl->inputs; + + vector mx(in[0].size(), -1e+50); + for (unsigned i = 0; i < in.size(); ++i) { + for (unsigned j = 0; j < in[i].size(); ++j) { + mx[j] = std::max(mx[j], in[i][j]); + } + } + + return mx; +} + + + + diff --git a/deprecated/eo/contrib/mathsym/regression/Dataset.h b/deprecated/eo/contrib/mathsym/regression/Dataset.h new file mode 100644 index 000000000..395036db5 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/Dataset.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef DATASET_H_ +#define DATASET_H_ + +#include +#include + +class DataSetImpl; + +class Dataset { + + DataSetImpl* pimpl; + + Dataset& operator=(const Dataset&); // cannot assign + public: + + Dataset(); + ~Dataset(); + Dataset(const Dataset&); + + void load_data(std::string filename); + + unsigned n_records() const; + unsigned n_fields() const; + + const std::vector& get_inputs(unsigned record) const; + double get_target(unsigned record) const; + + std::vector input_minima() const; + std::vector input_maxima() const; + +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/regression/ErrorMeasure.cpp b/deprecated/eo/contrib/mathsym/regression/ErrorMeasure.cpp new file mode 100644 index 000000000..3a33d0d05 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/ErrorMeasure.cpp @@ -0,0 +1,340 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 + +#include "MultiFunction.h" + +#include "ErrorMeasure.h" +#include "Dataset.h" +#include "Sym.h" +#include "FunDef.h" +#include "sym_compile.h" +#include "TargetInfo.h" +#include "stats.h" + +using namespace std; + +#ifdef INTERVAL_DEBUG + +#include +#include + +vector none; +IntervalBoundsCheck bounds(none, none); + +#endif + + + +static double not_a_number = atof("nan"); + +class ErrorMeasureImpl { + public: + const Dataset& data; + TargetInfo train_info; + + ErrorMeasure::measure measure; + + Scaling no_scaling; + + ErrorMeasureImpl(const Dataset& d, double t_p, ErrorMeasure::measure m) : data(d), measure(m) { + +#ifdef INTERVAL_DEBUG + bounds = IntervalBoundsCheck(d.input_minima(), d.input_maxima()); +#endif + + unsigned nrecords = d.n_records(); + unsigned cases = unsigned(t_p * nrecords); + + valarray t(cases); + + for (unsigned i = 0; i < cases; ++i) { + t[i] = data.get_target(i); + } + + train_info = TargetInfo(t); + no_scaling = Scaling(new NoScaling); + } + + ErrorMeasure::result eval(const valarray& y) { + + ErrorMeasure::result result; + result.scaling = no_scaling; + + + switch(measure) { + case ErrorMeasure::mean_squared: + result.error = pow(train_info.targets() - y, 2.0).sum() / y.size(); + return result; + case ErrorMeasure::absolute: + result.error = abs(train_info.targets() - y).sum() / y.size(); + return result; + case ErrorMeasure::mean_squared_scaled: + result.scaling = ols(y, train_info); + result.error = pow(train_info.targets() - result.scaling->transform(y), 2.0).sum() / y.size(); + return result; + default: + cerr << "Unknown measure encountered: " << measure << " " << __FILE__ << " " << __LINE__ << endl; + } + + return result; + } + + unsigned train_cases() const { + return train_info.targets().size(); + } + + vector multi_function_eval(const vector& pop) { + + if (pop.size() == 0) return vector(); + + multi_function all = compile(pop); + //MultiFunction all(pop); + std::vector y(pop.size()); + + Scaling noScaling = Scaling(new NoScaling); + + const std::valarray& t = train_info.targets(); + + cout << "Population size " << pop.size() << endl; + + if (measure == ErrorMeasure::mean_squared_scaled) { + std::vector var(pop.size()); + std::vector cov(pop.size()); + + Var vart; + + for (unsigned i = 0; i < t.size(); ++i) { + vart.update(t[i]); + + all(&data.get_inputs(i)[0], &y[0]); // evalutate + //all(data.get_inputs(i), y); // evalutate + + for (unsigned j = 0; j < pop.size(); ++j) { + var[j].update(y[j]); + cov[j].update(y[j], t[i]); + } + } + + std::vector result(pop.size()); + + for (unsigned i = 0; i < pop.size(); ++i) { + + // calculate scaling + double b = cov[i].get_cov() / var[i].get_var(); + + if (!finite(b)) { + result[i].scaling = noScaling; + result[i].error = vart.get_var(); // largest error + continue; + } + + double a = vart.get_mean() - b * var[i].get_mean(); + + result[i].scaling = Scaling( new LinearScaling(a,b)); + + // calculate error + double c = cov[i].get_cov(); + c *= c; + + double err = vart.get_var() - c / var[i].get_var(); + result[i].error = err; + if (!finite(err)) { + //cout << pop[i] << endl; + cout << "b " << b << endl; + cout << "var t " << vart.get_var() << endl; + cout << "var i " << var[i].get_var() << endl; + cout << "cov " << cov[i].get_cov() << endl; + + for (unsigned j = 0; j < t.size(); ++j) { + all(&data.get_inputs(i)[0], &y[0]); // evalutate + //all(data.get_inputs(j), y); // evalutate + + cout << y[i] << ' ' << ::eval(pop[i], data.get_inputs(j)) << endl; + } + + exit(1); + } + } + + return result; + } + + + std::vector err(pop.size()); + + for (unsigned i = 0; i < train_cases(); ++i) { + // evaluate + all(&data.get_inputs(i)[0], &y[0]); + //all(data.get_inputs(i), y); + + for (unsigned j = 0; j < pop.size(); ++j) { + double diff = y[j] - t[i]; + if (measure == ErrorMeasure::mean_squared) { // branch prediction will probably solve this inefficiency + err[j] += diff * diff; + } else { + err[j] += fabs(diff); + } + + } + + } + + std::vector result(pop.size()); + + double n = train_cases(); + for (unsigned i = 0; i < pop.size(); ++i) { + result[i].error = err[i] / n; + result[i].scaling = noScaling; + } + + return result; + + } + + vector single_function_eval(const vector & pop) { + + vector funcs(pop.size()); + compile(pop, funcs); // get one function pointer for each individual + + valarray y(train_cases()); + vector result(pop.size()); + for (unsigned i = 0; i < funcs.size(); ++i) { + for (unsigned j = 0; j < train_cases(); ++j) { + y[j] = funcs[i](&data.get_inputs(j)[0]); + } + +#ifdef INTERVAL_DEBUG + //cout << "eval func " << i << " " << pop[i] << endl; + pair b = bounds.calc_bounds(pop[i]); + + // check if y is in bounds + for (unsigned j = 0; j < y.size(); ++j) { + if (y[j] < b.first -1e-4 || y[j] > b.second + 1e-4 || !finite(y[j])) { + cout << "Error " << y[j] << " not in " << b.first << ' ' << b.second << endl; + cout << "Function " << pop[i] << endl; + exit(1); + } + } +#endif + + result[i] = eval(y); + } + + return result; + } + + vector calc_error(const vector& pop) { + + // first declone +#if USE_TR1 + typedef std::tr1::unordered_map HashMap; +#else + typedef hash_map HashMap; +#endif + HashMap clone_map; + vector decloned; + decloned.reserve(pop.size()); + + for (unsigned i = 0; i < pop.size(); ++i) { + HashMap::iterator it = clone_map.find(pop[i]); + + if (it == clone_map.end()) { // new + clone_map[ pop[i] ] = decloned.size(); + decloned.push_back(pop[i]); + } + + } + + // evaluate + vector dresult; + // currently we can only accumulate simple measures such as absolute and mean_squared + switch(measure) { + case ErrorMeasure::mean_squared: + case ErrorMeasure::absolute: + dresult = multi_function_eval(decloned); + break; + case ErrorMeasure::mean_squared_scaled: + dresult = multi_function_eval(decloned); + break; + } + + vector result(pop.size()); + for (unsigned i = 0; i < result.size(); ++i) { + result[i] = dresult[ clone_map[pop[i]] ]; + } + + return result; + } + +}; + +ErrorMeasure::result::result() { + error = 0.0; + scaling = Scaling(0); +} + +bool ErrorMeasure::result::valid() const { + return isfinite(error); +} + +ErrorMeasure::ErrorMeasure(const Dataset& data, double train_perc, measure meas) { + pimpl = new ErrorMeasureImpl(data, train_perc, meas); +} + +ErrorMeasure::~ErrorMeasure() { delete pimpl; } +ErrorMeasure::ErrorMeasure(const ErrorMeasure& that) { pimpl = new ErrorMeasureImpl(*that.pimpl); } + + +ErrorMeasure::result ErrorMeasure::calc_error(Sym sym) { + + single_function f = compile(sym); + + valarray y(pimpl->train_cases()); + + for (unsigned i = 0; i < y.size(); ++i) { + + y[i] = f(&pimpl->data.get_inputs(i)[0]); + + if (!finite(y[i])) { + result res; + res.scaling = Scaling(new NoScaling); + res.error = not_a_number; + return res; + } + } + + return pimpl->eval(y); +} + +vector ErrorMeasure::calc_error(const vector& syms) { + return pimpl->calc_error(syms); + +} + +double ErrorMeasure::worst_performance() const { + + if (pimpl->measure == mean_squared_scaled) { + return pimpl->train_info.tvar(); + } + + return 1e+20; +} + diff --git a/deprecated/eo/contrib/mathsym/regression/ErrorMeasure.h b/deprecated/eo/contrib/mathsym/regression/ErrorMeasure.h new file mode 100644 index 000000000..17619fe97 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/ErrorMeasure.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef ERROR_MEASURE_H +#define ERROR_MEASURE_H + +#include "Scaling.h" + +class ErrorMeasureImpl; +class Sym; +class Dataset; + +class ErrorMeasure { + + ErrorMeasureImpl* pimpl; + + public : + + enum measure { + absolute, + mean_squared, + mean_squared_scaled, + }; + + struct result { + double error; + Scaling scaling; + + result(); + bool valid() const; + }; + + ErrorMeasure(const Dataset& data, double train_perc, measure meas = mean_squared); + + ~ErrorMeasure(); + ErrorMeasure(const ErrorMeasure& that); + ErrorMeasure& operator=(const ErrorMeasure& that); + + result calc_error(Sym sym); + + std::vector calc_error(const std::vector& sym); + + double worst_performance() const; +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/regression/Scaling.cpp b/deprecated/eo/contrib/mathsym/regression/Scaling.cpp new file mode 100644 index 000000000..dd6b0d0fc --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/Scaling.cpp @@ -0,0 +1,417 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "Scaling.h" +#include "TargetInfo.h" + +using namespace std; + +Scaling slope(const std::valarray& x, const TargetInfo& targets) { + + double xx = 0.0; + double xy = 0.0; + + const valarray& y = targets.targets(); + + for (unsigned i = 0; i < x.size(); ++i) { + xx += x[i] * x[i]; + xy += x[i] * y[i]; + } + + if (xx < 1e-7) return Scaling(new LinearScaling(0.0,0.0)); + + double b = xy / xx; + + return Scaling(new LinearScaling(0.0, b)); + +} + +// Still needs proper testing with non-trivial lambda +Scaling regularized_least_squares(const std::valarray& inputs, const TargetInfo& targets, double lambda) { + + double n = inputs.size(); + + valarray x = inputs; + + double a,b,d; + a=b=d=0; + + for (unsigned i = 0; i < n; ++i) { + a += 1 + lambda; + b += x[i]; + d += x[i] * x[i] + lambda; + } + + //invert + + double ad_bc = a*d - b * b; + // if ad_bc equals zero there's a problem + + if (ad_bc < 1e-17) return Scaling(new LinearScaling); + + double ai = d/ad_bc; + double bi = -b/ad_bc; + double di = a/ad_bc; + double ci = bi; + + // Now multiply this inverted covariance matrix (C^-1) with x' * t + + std::valarray ones = x; + + // calculate C^-1 * x' ) + for (unsigned i = 0; i < n; ++i) + { + ones[i] = (ai + bi * x[i]); + x[i] = (ci + di * x[i]); + } + + // results are in [ones, x], now multiply with y + + a = 0.0; // intercept + b = 0.0; // slope + + const valarray& t = targets.targets(); + + for (unsigned i = 0; i < n; ++i) + { + a += ones[i] * t[i]; + b += x[i] * t[i]; + } + + return Scaling(new LinearScaling(a,b)); +} + +Scaling ols(const std::valarray& y, const std::valarray& t) { + double n = y.size(); + + double y_mean = y.sum() / n; + double t_mean = t.sum() / n; + + std::valarray y_var = (y - y_mean); + std::valarray t_var = (t - t_mean); + std::valarray cov = t_var * y_var; + + y_var *= y_var; + t_var *= t_var; + + double sumvar = y_var.sum(); + + if (sumvar == 0. || sumvar/n < 1e-7 || sumvar/n > 1e+7) // breakout when numerical problems are likely + return Scaling(new LinearScaling(t_mean,0.)); + + + double b = cov.sum() / sumvar; + double a = t_mean - b * y_mean; + + Scaling s = Scaling(new LinearScaling(a,b)); + + return s; +} + +Scaling ols(const std::valarray& y, const TargetInfo& targets) { + double n = y.size(); + + double y_mean = y.sum() / n; + + std::valarray y_var = (y - y_mean); + std::valarray cov = targets.tcov_part() * y_var; + + y_var *= y_var; + + double sumvar = y_var.sum(); + + if (sumvar == 0. || sumvar/n < 1e-7 || sumvar/n > 1e+7) // breakout when numerical problems are likely + return Scaling(new LinearScaling(targets.tmean(),0.)); + + + double b = cov.sum() / sumvar; + double a = targets.tmean() - b * y_mean; + + if (!finite(b)) { + + cout << a << ' ' << b << endl; + cout << sumvar << endl; + cout << y_mean << endl; + cout << cov.sum() << endl; + exit(1); + } + + Scaling s = Scaling(new LinearScaling(a,b)); + + return s; +} + + +Scaling wls(const std::valarray& inputs, const TargetInfo& targets) { + + std::valarray x = inputs; + const std::valarray& w = targets.weights(); + + unsigned n = x.size(); + // First calculate x'*W (as W is a diagonal matrix it's simply elementwise multiplication + std::valarray wx = targets.weights() * x; + + // Now x'*W is contained in [w,wx], calculate x' * W * x (the covariance) + double a,b,d; + a=b=d=0.0; + + for (unsigned i = 0; i < n; ++i) + { + a += w[i]; + b += wx[i]; + d += x[i] * wx[i]; + } + + //invert + + double ad_bc = a*d - b * b; + // if ad_bc equals zero there's a problem + + if (ad_bc < 1e-17) return Scaling(new LinearScaling); + + double ai = d/ad_bc; + double bi = -b/ad_bc; + double di = a/ad_bc; + double ci = bi; + + // Now multiply this inverted covariance matrix (C^-1) with x' * W * y + + // create alias to reuse the wx we do not need anymore + std::valarray& ones = wx; + + // calculate C^-1 * x' * W (using the fact that W is diagonal) + for (unsigned i = 0; i < n; ++i) + { + ones[i] = w[i]*(ai + bi * x[i]); + x[i] = w[i]*(ci + di * x[i]); + } + + // results are in [ones, x], now multiply with y + + a = 0.0; // intercept + b = 0.0; // slope + + const valarray& t = targets.targets(); + + for (unsigned i = 0; i < n; ++i) + { + a += ones[i] * t[i]; + b += x[i] * t[i]; + } + + return Scaling(new LinearScaling(a,b)); +} + + +//Scaling med(const std::valarray& inputs, const TargetInfo& targets); + +double mse(const std::valarray& y, const TargetInfo& t) { + + valarray residuals = t.targets()-y; + residuals *= residuals; + double sz = residuals.size(); + if (t.has_weights()) { + residuals *= t.weights(); + sz = 1.0; + } + + return residuals.sum() / sz; +} + +double rms(const std::valarray& y, const TargetInfo& t) { + return sqrt(mse(y,t)); +} + +double mae(const std::valarray& y, const TargetInfo& t) { + valarray residuals = abs(t.targets()-y); + if (t.has_weights()) residuals *= t.weights(); + return residuals.sum() / residuals.size(); +} + + +/* + double standard_error(const std::valarray& y, const std::pair& scaling) { + double a = scaling.first; + double b = scaling.second; + double n = y.size(); + double se = sqrt( pow(a+b*y-current_set->targets,2.0).sum() / (n-2)); + + double mean_y = y.sum() / n; + double sxx = pow( y - mean_y, 2.0).sum(); + + return se / sqrt(sxx); + } + + double scaled_mse(const std::valarray& y){ + std::pair scaling; + return scaled_mse(y,scaling); + } + + double scaled_mse(const std::valarray& y, std::pair& scaling) + { + scaling = scale(y); + + double a = scaling.first; + double b = scaling.second; + + std::valarray tmp = current_set->targets - a - b * y; + tmp *= tmp; + + if (weights.size()) + return (weights * tmp).sum(); + + return tmp.sum() / tmp.size(); + } + + double robust_mse(const std::valarray& ny, std::pair& scaling) { + + double smse = scaled_mse(ny,scaling); + + std::valarray y = ny; + // find maximum covariance case + double n = y.size(); + + int largest = 0; + + { + double y_mean = y.sum() / n; + + std::valarray y_var = (y - y_mean); + std::valarray cov = tcov * y_var; + + std::valarray maxcov = cov == cov.max(); + + for (unsigned i = 0; i < maxcov.size(); ++i) { + if (maxcov[i]) { + largest = i; + break; + } + } + } + + double y_mean = (y.sum() - y[largest]) / (n-1); + y[largest] = y_mean; // dissappears from covariance calculation + + std::valarray y_var = (y - y_mean); + std::valarray cov = tcov * y_var; + y_var *= y_var; + + double sumvar = y_var.sum(); + + if (sumvar == 0. || sumvar/n < 1e-7 || sumvar/n > 1e+7) // breakout when numerical problems are likely + return worst_performance(); + + double b = cov.sum() / sumvar; + double a = tmean - b * y_mean; + + std::valarray tmp = current_set->targets - a - b * y; + tmp[largest] = 0.0; + tmp *= tmp; + + double smse2 = tmp.sum() / (tmp.size()-1); + + static std::ofstream os("smse.txt"); + os << smse << ' ' << smse2 << '\n'; + + if (smse2 > smse) { + return worst_performance(); + //std::cerr << "overfit? " << smse << ' ' << smse2 << '\n'; + } + + scaling.first = a; + scaling.second = b; + + return smse2; + } + + class Sorter { + const std::valarray& scores; + public: + Sorter(const std::valarray& _scores) : scores(_scores) {} + + bool operator()(unsigned i, unsigned j) const { + return scores[i] < scores[j]; + } + }; + + double coc(const std::valarray& y) { + std::vector indices(y.size()); + for (unsigned i = 0; i < y.size(); ++i) indices[i] = i; + std::sort(indices.begin(), indices.end(), Sorter(y)); + + const std::valarray& targets = current_set->targets; + + double neg = 1.0 - targets[indices[0]]; + double pos = targets[indices[0]]; + + double cumpos = 0; + double cumneg = 0; + double sum=0; + + double last_score = y[indices[0]]; + + for(unsigned i = 1; i < targets.size(); ++i) { + + if (fabs(y[indices[i]] - last_score) < 1e-9) { // we call it tied + pos += targets[indices[i]]; + neg += 1.0 - targets[indices[i]]; + + if (i < targets.size()-1) + continue; + } + sum += pos * cumneg + (pos * neg) * 0.5; + cumneg += neg; + cumpos += pos; + pos = targets[indices[i]]; + neg = 1.0 - targets[indices[i]]; + last_score = y[indices[i]]; + } + + return sum / (cumneg * cumpos); + } + + // iterative re-weighted least squares (for parameters.classification) + double irls(const std::valarray& scores, std::pair& scaling) { + const std::valarray& t = current_set->targets; + + std::valarray e(scores.size()); + std::valarray u(scores.size()); + std::valarray w(scores.size()); + std::valarray z(scores.size()); + + parameters.use_irls = false; parameters.classification=false; + scaling = scale(scores); + parameters.use_irls=true;parameters.classification=true; + + if (scaling.second == 0.0) return worst_performance(); + + for (unsigned i = 0; i < 10; ++i) { + e = exp(scaling.first + scaling.second*scores); + u = e / (e + exp(-(scaling.first + scaling.second * scores))); + w = u*(1.-u); + z = (t-u)/w; + scaling = wls(scores, u, w); + //double ll = (log(u)*t + (1.-log(u))*(1.-t)).sum(); + //std::cout << "Scale " << i << ' ' << scaling.first << " " << scaling.second << " LL " << 2*ll << std::endl; + } + + // log-likelihood + u = exp(scaling.first + scaling.second*scores) / (1 + exp(scaling.first + scaling.second*scores)); + double ll = (log(u)*t + (1.-log(u))*(1.-t)).sum(); + return 2*ll; + } +*/ diff --git a/deprecated/eo/contrib/mathsym/regression/Scaling.h b/deprecated/eo/contrib/mathsym/regression/Scaling.h new file mode 100644 index 000000000..efa98a01a --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/Scaling.h @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SCALING_H_ +#define SCALING_H_ + +#include "shared_ptr.h" + +#include +#include +#include + +class TargetInfo; + +class ScalingBase { + public: + + virtual ~ScalingBase() {} + + std::valarray apply(const std::valarray& x) { + std::valarray xtmp = x; + transform(xtmp); + return xtmp; + } + + virtual double transform(double input) const = 0; + virtual void transform(std::valarray& inputs) const = 0; + virtual std::ostream& print(std::ostream& os, std::string str) const = 0; + virtual std::valarray transform(const std::valarray& inputs) const = 0; +}; + +typedef shared_ptr Scaling; + +class LinearScaling : public ScalingBase { + + double a,b; + + public: + LinearScaling() : a(0.0), b(1.0) {} + LinearScaling(double _a, double _b) : a(_a), b(_b) {} + + double transform(double input) const { input *=b; input += a; return input; } + void transform(std::valarray& inputs) const { inputs *= b; inputs += a; } + std::valarray transform(const std::valarray& inputs) const { + std::valarray y = a + b * inputs; + return y; + } + + double intercept() const { return a; } + double slope() const { return b; } + + std::ostream& print(std::ostream& os, std::string str) const { + os.precision(16); + os << a << " + " << b << " * " << str; + return os; + } +}; + +class NoScaling : public ScalingBase{ + void transform(std::valarray&) const {} + double transform(double input) const { return input; } + std::valarray transform(const std::valarray& inputs) const { return inputs; } + std::ostream& print(std::ostream& os, std::string str) const { return os << str; } +}; + +extern Scaling slope(const std::valarray& inputs, const TargetInfo& targets); // slope only +extern Scaling ols(const std::valarray& inputs, const TargetInfo& targets); +extern Scaling wls(const std::valarray& inputs, const TargetInfo& targets); +extern Scaling med(const std::valarray& inputs, const TargetInfo& targets); + +extern Scaling ols(const std::valarray& inputs, const std::valarray& outputs); + +extern double mse(const std::valarray& y, const TargetInfo& t); +extern double rms(const std::valarray& y, const TargetInfo& t); +extern double mae(const std::valarray& y, const TargetInfo& t); + +// Todo Logistic Scaling + +#endif + + diff --git a/deprecated/eo/contrib/mathsym/regression/TargetInfo.cpp b/deprecated/eo/contrib/mathsym/regression/TargetInfo.cpp new file mode 100644 index 000000000..1d386e8c9 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/TargetInfo.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "TargetInfo.h" + +using namespace std; + +TargetInfo::TargetInfo(const TargetInfo& org) { operator=(org); } + +TargetInfo& TargetInfo::operator=(const TargetInfo& org) { + _targets.resize(org._targets.size()); + _weights.resize(org._weights.size()); + _tcov_part.resize(org._tcov_part.size()); + + _targets = org._targets; + _weights = org._weights; + _tcov_part = org._tcov_part; + + _tmean = org._tmean; + _tvar = org._tvar; + _tstd = org._tstd; + _tmed = org._tmed; + return *this; +} + + +TargetInfo::TargetInfo(const std::valarray& t) { + _weights.resize(0); + _targets.resize(t.size()); + _targets = t; + + _tmean = _targets.sum()/_targets.size(); + + _tcov_part.resize(_targets.size()); + _tcov_part = _targets; + _tcov_part -= _tmean; + + std::valarray tmp = _tcov_part; + tmp = _tcov_part; + tmp *= tmp; + + _tvar = tmp.sum() / (tmp.size()-1); + _tstd = sqrt(_tvar); + _tmed = 0; +} + +TargetInfo::TargetInfo(const std::valarray& t, const std::valarray& w) { + + _targets.resize(t.size()); + _weights.resize(w.size()); + + _targets = t; + _weights = w; + + double sumw = _weights.sum(); + // scale weights so that they'll add up to 1 + _weights /= sumw; + + _tmean = (_targets * _weights).sum(); + _tcov_part.resize(_targets.size()); + _tcov_part = _targets; + _tcov_part -= _tmean; + + _tvar = (pow(_targets - _tmean, 2.0) * _weights).sum(); + _tstd = sqrt(_tvar); + _tmed = 0.; +} + +// calculate the members, now in the context of a mask +void TargetInfo::set_training_mask(const std::valarray& tmask) { + + TargetInfo tmp; + + if (has_weights() ) { + tmp = TargetInfo( _targets[tmask], _weights[tmask]); + } else { + tmp = TargetInfo( _targets[tmask] ); + } + + _tcov_part.resize(tmp._tcov_part.size()); + _tcov_part = tmp._tcov_part; + + _tmean = tmp._tmean; + _tvar = tmp._tvar; + _tstd = tmp._tstd; + _tmed = tmp._tmed; + + _training_mask.resize(tmask.size()); + _training_mask = tmask; +} + +struct SortOnTargets +{ + const valarray& t; + SortOnTargets(const valarray& v) : t(v) {} + + bool operator()(int i, int j) const { + return fabs(t[i]) < fabs(t[j]); + } +}; + +vector TargetInfo::sort() { + + vector ind(_targets.size()); + for (unsigned i = 0; i < ind.size(); ++i) { ind[i] = i; } + + std::sort(ind.begin(), ind.end(), SortOnTargets(_targets)); + + valarray tmptargets = _targets; + valarray tmpweights = _weights; + valarray tmpcov = _tcov_part; + + for (unsigned i = 0; i < ind.size(); ++i) + { + _targets[i] = tmptargets[ ind[i] ]; + _tcov_part[i] = tmpcov[ ind[i] ]; + if (_weights.size()) _weights[i] = tmpweights[ ind[i] ]; + } + + return ind; +} + + + diff --git a/deprecated/eo/contrib/mathsym/regression/TargetInfo.h b/deprecated/eo/contrib/mathsym/regression/TargetInfo.h new file mode 100644 index 000000000..ee9a307ff --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/TargetInfo.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef TARGETINFO_H_ +#define TARGETINFO_H_ + +#include +#include + +class TargetInfo { + std::valarray _targets; + std::valarray _weights; + std::valarray _training_mask; + + // some stuff for ols + std::valarray _tcov_part; + double _tmean; + double _tvar; + double _tstd; + double _tmed; + + public: + TargetInfo() {} + + TargetInfo(const std::valarray& t); + TargetInfo(const std::valarray& t, const std::valarray& w); + + TargetInfo(const TargetInfo& org); + TargetInfo& operator=(const TargetInfo& org); + ~TargetInfo() {} + + const std::valarray& targets() const { return _targets; } + const std::valarray& weights() const { return _weights; } + const std::valarray& mask() const { return _training_mask; } + + void set_training_mask(const std::valarray& mask); + + bool has_weights() const { return _weights.size(); } + bool has_mask() const { return _training_mask.size(); } + + std::vector sort(); + + const std::valarray& tcov_part() const { return _tcov_part; } + double tmean() const { return _tmean; } + double tvar() const { return _tvar; } + double tstd() const { return _tstd; } + double devmedian() const { return _tmed; } +}; + +#endif + diff --git a/deprecated/eo/contrib/mathsym/regression/stats.h b/deprecated/eo/contrib/mathsym/regression/stats.h new file mode 100644 index 000000000..0ead60685 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/regression/stats.h @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include + +class Mean { + + double n; + double mean; + + public: + Mean() : n(0), mean(0) {} + + void update(double v) { + n++; + double d = v - mean; + mean += 1/n * d; + } + + double get_mean() const { return mean; } +}; + +class Var { + double n; + double mean; + double sumvar; + + public: + Var() : n(0), mean(0), sumvar(0) {} + + void update(double v) { + n++; + double d = v - mean; + mean += 1/n * d; + sumvar += (n-1)/n * d * d; + } + + double get_mean() const { return mean; } + double get_var() const { return sumvar / (n-1); } + double get_std() const { return sqrt(get_var()); } +}; + +/** Single covariance between two variates */ +class Cov { + double n; + double meana; + double meanb; + double sumcov; + + public: + Cov() : n(0), meana(0), meanb(0), sumcov(0) {} + + void update(double a, double b) { + ++n; + double da = a - meana; + double db = b - meanb; + + meana += 1/n * da; + meanb += 1/n * db; + + sumcov += (n-1)/n * da * db; + } + + double get_meana() const { return meana; } + double get_meanb() const { return meanb; } + double get_cov() const { return sumcov / (n-1); } +}; + +class CovMatrix { + double n; + std::vector mean; + std::vector< std::vector > sumcov; + + public: + CovMatrix(unsigned dim) : n(0), mean(dim), sumcov(dim , std::vector(dim)) {} + + void update(const std::vector& v) { + n++; + + for (unsigned i = 0; i < v.size(); ++i) { + double d = v[i] - mean[i]; + mean[i] += 1/n * d; + + sumcov[i][i] += (n-1)/n * d * d; + + for (unsigned j = i; j < v.size(); ++j) { + double e = v[j] - mean[j]; // mean[j] is not updated yet + + double upd = (n-1)/n * d * e; + + sumcov[i][j] += upd; + sumcov[j][i] += upd; + + } + } + + } + + double get_mean(int i) const { return mean[i]; } + double get_var(int i ) const { return sumcov[i][i] / (n-1); } + double get_std(int i) const { return sqrt(get_var(i)); } + double get_cov(int i, int j) const { return sumcov[i][j] / (n-1); } + +}; + diff --git a/deprecated/eo/contrib/mathsym/shared_ptr.h b/deprecated/eo/contrib/mathsym/shared_ptr.h new file mode 100644 index 000000000..58353fe91 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/shared_ptr.h @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef _SHARED_PTR_H +#define _SHARED_PTR_H + + +template class weak_ptr; + +template +class shared_ptr { + private: + T* ptr; + unsigned* count; // + + /* special case, null pointer (nil-code) */ + static unsigned* nil() { static unsigned nil_counter(1); return &nil_counter; } + + void decref() { if (--(*count) == 0) { delete ptr; delete count; }} + void incref() { ++(*count); } + + friend class weak_ptr; + + public: + + shared_ptr() : ptr(0), count(nil()) { incref(); } + ~shared_ptr() { decref(); } + + shared_ptr(const shared_ptr& o) : ptr(o.ptr), count(o.count) { incref(); } + shared_ptr(T* p) : ptr(p), count(new unsigned(1)) {} + explicit shared_ptr(const weak_ptr& w) : ptr(w.ptr), count(w.count) { incref(); } + + shared_ptr& operator=(const shared_ptr& o) { + if (ptr == o.ptr) return *this; + decref(); + ptr = o.ptr; + count = o.count; + incref(); + return *this; + } + + T* get() { return ptr; } + T* operator->() { return ptr; } + T& operator*() { return *ptr; } + + const T* get() const { return ptr; } + const T* operator->() const { return ptr; } + const T& operator*() const { return *ptr; } + + bool operator==(const shared_ptr& o) const { return ptr == o.ptr; } + bool operator!=(const shared_ptr& o) const { return ptr != o.ptr; } + bool operator<(const shared_ptr& o) const { return ptr < o.ptr; } + + unsigned refcount() const { return *count; } +}; + +template +class weak_ptr { + T* ptr; + unsigned* count; + + friend class shared_ptr; + + public: + + weak_ptr() : ptr(0), count(shared_ptr::nil()) {} + explicit weak_ptr( const shared_ptr& s) : ptr(s.ptr), count(s.count) {} + + shared_ptr lock() const { return shared_ptr(*this); } + + + T* get() { return ptr; } + T* operator->() { return ptr; } + T& operator*() { return *ptr; } + + const T* get() const { return ptr; } + const T* operator->() const { return ptr; } + const T& operator*() const { return *ptr; } + + bool operator==(const shared_ptr& o) const { return ptr == o.ptr; } + bool operator!=(const shared_ptr& o) const { return ptr != o.ptr; } + bool operator<(const shared_ptr& o) const { return ptr < o.ptr; } + + unsigned refcount() const { return *count; } + +}; + +#endif diff --git a/deprecated/eo/contrib/mathsym/sym/README.cpp b/deprecated/eo/contrib/mathsym/sym/README.cpp new file mode 100644 index 000000000..c62e6cbac --- /dev/null +++ b/deprecated/eo/contrib/mathsym/sym/README.cpp @@ -0,0 +1,364 @@ + +/* + DESCRIPTION: + + +The class 'Sym' in this package provides a reference counted, hashed tree structure that can be used in genetic programming. +The hash table behind the scenes makes sure that every subtree in the application is stored only once. +This has a couple of advantages: + +o Memory: all subtrees are stored only once +o Comparison: comparison for equality for two subtrees boils down to a pointer comparison +o Overview: by accessing the hashtable, you get an instant overview of the state of the population + + +The disadvantage of this method is the constant time overhead for computing hashes. In practice, +it seems to be fast enough. + + +===== How to Use this ========= + +In essence, the Sym data structure contains two important pieces of data, +the 'token' (of type token_t = int) and the children, a vector of Sym (called SymVec). +The token should contain all information to be able to figure out which +function/terminal is represented by the node in the tree. By retrieving this token value +and the SymVec it is possible to write recursive traversal routines for evaluation, printing, +etc. + +*/ + +#include +#include "Sym.h" + +using namespace std; + + +/* + * Suppose token value '0' designates our terminal, and token value '1' designates a binary function. + * Later on a ternary function will be used as well, designated with token value '2' + * The function below will create a tree of size three +*/ +Sym test1() { + + SymVec children; + children.push_back( Sym(0) ); // push_back is a member from std::vector, SymVec is derived from std::vector + children.push_back( Sym(0) ); + + Sym tree = Sym(token_t(1), children); // creates the tree + + /* Done, now print some information about the node */ + + cout << "Size = " << tree.size() << endl; // prints 3 + cout << "Depth = " << tree.depth() << endl; // prints 2 + cout << "Refcount = " << tree.refcount() << endl; // prints 1 + + Sym tree2 = tree; // make a copy (this only changes refcount) + + cout << "Refcount now = " << tree.refcount() << endl; // print 2 + + return tree; // tree2 will be deleted and reference count returns to 1 +} + +/* To actually use the tree, evaluate it, the following simple recursive function + * can be used +*/ + +int eval(const Sym& sym) { + if (sym.token() == 0) { // it's a terminal in this example + return 1; + } + // else it's the function + const SymVec& children = sym.args(); // get the children out, children.size() is the arity + + // let's assume that we've also got a ternary function designated by token '2' + + if (sym.token() == token_t(1)) + return eval(children[0]) + eval(children[1]); // evaluate + + return eval(children[0]) + eval(children[1]) * eval(children[2]); // a ternary function +} + +/* Note that you simply use the stored token that was defined above. Simply checking the size of SymVec in + * this particular example could have sufficed, but it's instructive to use the tokens. + * + * And to test this: +*/ + +void test_eval() { + + Sym tree = test1(); + + cout << "Evaluating tree1 returns " << eval(tree) << endl; +} + +/* Writing initialization functions. + * + * As the Sym class is recursive in nature, initialization can simply be done using + * recursive routines as above. As an example, the following code does 'full' initialization. + */ + +Sym init_full(int depth_left) { + if (depth_left == 0) return Sym(0); // create terminal + // else create either a binary or a ternary function + + depth_left--; + + if (rand() % 2 == 0) { // create binary + SymVec vec(2); + vec[0] = init_full(depth_left); + vec[1] = init_full(depth_left); + + return Sym(token_t(1), vec); + + } else { // create ternary tree + SymVec vec(3); + vec[0] = init_full(depth_left); + vec[1] = init_full(depth_left); + vec[2] = init_full(depth_left); + + return Sym(token_t(2), vec); // token value 2 designates a ternary now, even though the arity can simply be read from the size of the 'SymVec' + } + +} + + +/* Examining the hash table. + * + * The hash table is a static member of the Sym class, but can be obtained and inspected + * at any point during the run. The hash table follows the SGI implementation of hashmap (and effectively + * uses it in gcc). An example: + */ + +void inspect_hashtable() { + SymMap& dag = Sym::get_dag(); // get the hashmap + unsigned i = 0; + for (SymMap::iterator it = dag.begin(); it != dag.end(); ++it) { + Sym node(it); // initialize a 'sym' with the iterator + + cout << "Node " << i++ << " size " << node.size(); + cout << " refcount " << node.refcount()-1; // -1: note that by creating the Sym above the refcount is increased + cout << " depth " << node.depth(); + cout << '\n'; + } + +} + +/* The above code effectively examines all distinct subtrees in use in the application and prints some stats for the node */ + +/* Manipulating trees + * + * The Sym class is set up in such a way that you cannot change a Sym, so how do you perform crossover and mutation? + * + * Simple, you create new syms. The Sym class supports two functions to make this easier: 'get_subtree' and 'insert_subtree'. + * These traverse the tree by index, where 0 designates the root and other values are indexed depth first. + */ + +Sym subtree_xover(Sym a, Sym b) { + + Sym to_insert = get_subtree(a, rand() % a.size() ); // select random subtree, will crash if too high a value is given + + /* 'insert' it into b. This will not really insert, it will however create a new sym, + * equal to 'b' but with a's subtree inserted at the designated spot. */ + return insert_subtree(b, rand() % b.size(), to_insert); + +} + +/* Tying it together, we can create a simple genetic programming system. Mutation is not implemented here, + * but would be easy enough to add by using recursion and/or 'set'. */ + +void run_gp() { + + int ngens = 50; + int popsize = 1000; + + cout << "Starting running " << popsize << " individuals for " << ngens << " generations." << endl; + + vector pop(popsize); + + // init population + for (unsigned i = 0; i < pop.size(); ++i) { + pop[i] = init_full(5); + } + + double best = 0.0; + + // do a very simple steady state tournament + for (unsigned gen = 0; gen < ngens * pop.size(); ++gen) { + int sel1 = rand()% pop.size(); + int sel2 = rand() % pop.size(); + int sel3 = rand() % pop.size(); + + double ev1 = eval(pop[sel1]); + double ev3 = eval(pop[sel3]); + + double bst = max(ev1,ev3); + if (bst > best) { + best = bst; + } + + if (ev3 > ev1) { + sel1 = sel3; // selection pressure + } + + Sym child = subtree_xover(pop[sel1], pop[sel2]); + + // Check for uniqueness + if (child.refcount() == 1) pop[ rand() % pop.size() ] = child; + } + + // and at the end: + + inspect_hashtable(); + + // and also count number of nodes in the population + int sz = 0; + for (unsigned i = 0; i < pop.size(); ++i) { sz += pop[i].size(); } + cout << "Number of distinct nodes " << Sym::get_dag().size() << endl; + cout << "Nodes in population " << sz << endl; + cout << "ratio " << double(Sym::get_dag().size())/sz << endl; + cout << "Best fitness " << best << endl; + +} + +/* One extra mechanism is supported to add annotations to nodes. Something derived from + * 'UniqueNodeStats' can be used to attach new information to nodes. For this to function, + * we need to supply a 'factory' function that creates these node-stats; attach this function to the + * Sym class, so that it gets called whenever a new node is created. The constructors of the Sym class + * take care of this. + * + * IMPORTANT: + * in a realistic application, the factory function needs to be set BEFORE any Syms are created + * Mixing Syms creating with and without the factory can lead to unexpected results + * + * First we derive some structure from UniqueNodeStats: */ + +struct MyNodeStats : public UniqueNodeStats { + + int sumsize; + + ~MyNodeStats() { cout << "MyNodeStats::~MyNodeStats, sumsize = " << sumsize << endl; } +}; + +/* then define the factory function. It will get a Sym, which is just created. */ +UniqueNodeStats* create_stats(const Sym& sym) { + MyNodeStats* stats = new MyNodeStats; // Sym will take care of memory management + + int sumsize = sym.size(); + for (unsigned i = 0; i < sym.args().size(); ++i) { + // retrieve the extra node stats of the child + UniqueNodeStats* unique_stats = sym.args()[i].extra_stats(); // extra_stats retrieves the stats + MyNodeStats* child_stats = static_cast(unique_stats); // cast it to the right struct + sumsize += child_stats->sumsize; + } + + stats->sumsize = sumsize; + return stats; // now it will get attached to the node and deleted when its reference count goes to zero +} + +void test_node_stats() { + + if (Sym::get_dag().size() != 0) { + cerr << "Cannot mix nodes with and without factory functions" << endl; + exit(1); + } + + /* Very Important: attach the factory function to the Sym class */ + Sym::set_factory_function(create_stats); + + Sym tree = init_full(5); // create a tree + + // get extra node stats out + MyNodeStats* stats = static_cast( tree.extra_stats() ); + + cout << "Size = " << tree.size() << " SumSize = " << stats->sumsize << endl; + + Sym::clear_factory_function(); // reset +} + + +/* And run the code above */ + +int main() { + srand(time(0)); + cout << "********** TEST EVALUATION **************\n"; + test_eval(); + cout << "********** TEST ALGORITHM ***************\n"; + run_gp(); + + cout << "********** TEST FACTORY ****************\n"; + test_node_stats(); // can work because there are no live nodes + +} + +/* ********** Member function reference: ******************** + * + * Sym() The default constructor will create an undefined node (no token and no children), check for empty() to see if a node is undefined + * + * Sym(token_t) Create a terminal + * + * Sym(token_t, const SymVec&) + * Create a node with token and SymVec as the children + * + * Sym(SymIterator it) + * Create a sym from an iterator (taken from the hashtable directly, or from Sym::iterator) + * + * dtor, copy-ctor and assignment + * + * UniqueNodeStats* extra_stats() + * Returns an UniqueNodeStats pointer (= 0 if no factory is defined) + * + * + * int hashcode() returns the hashcode for the node + * + * int refcount() returns the reference count for the node + * + * bool operator== checks for equality (note that this is a pointer compare, really really fast) + * + * bool empty() returns whether the node is undefined, i.e. created through the default ctor + * + * int arity() shorthand for sym.args().size() + * + * token_t token() return identifying token for the node + * + * const SymVec& args() + * returns the children of the node (in a vector) + * + * unsigned size() returns the size, i.e., number of nodes + * + * unsigned depth() returns the depth + * + * iterator() returns the pointer to the node in the hashtable + * + * + ********** Static functions: ******************** + * + * + * + * SymMap& get_dag() returns the hash table containing all nodes. This should only be used for inspection, + * even though the dag itself is not const. This to enable the use of the ctor Sym(SymIterator) to inspect + * using the Sym interface (rather than the hash table interface). This does allow you to make destructive + * changes to the class, so use with care + * + * set_factory_function( UniqueNodeStats (*)(const Sym&) ) + * Set the factory function + * + * clear_factory_function() + * Clears the factory function, allocated UniqueNodeStats will still be deleted, but no new ones will be created. + * + ********** Utility Functions ******************** + * + * Sym get_subtree(const Sym& org, int i) + * Retreive the i-th subtree from the Sym. Standard depth first ordering, where root has index 0 and the + * rightmost terminal has index sym.size()-1 + * + * Sym insert_subtree(const Sym& org, int i, const Sym& subtree) + * Returns a Sym that is equal to 'org', for which the i-th subtree (same ordering as get_subtree) is replaced + * by the third argument subtree. + * + * Sym next(const Sym&) + * Returns the successor of the argument sym from the hashtable with wrap around. This is implemented just because + * it can be done. It may be an interesting way to mutate... + * + * */ + + diff --git a/deprecated/eo/contrib/mathsym/sym/Sym.cpp b/deprecated/eo/contrib/mathsym/sym/Sym.cpp new file mode 100644 index 000000000..4d3c2227d --- /dev/null +++ b/deprecated/eo/contrib/mathsym/sym/Sym.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 + +#include "Sym.h" + +using namespace std; + +typedef UniqueNodeStats* (*NodeStatFunc)(Sym&); + +UniqueNodeStats* (*Sym::factory)(const Sym&) = 0; + +SymMap Sym::dag(100000); // reserve space for so many nodes +std::vector Sym::token_count; + + +size_t get_size(const SymVec& vec) { + size_t sz = 0; + for (unsigned i = 0; i < vec.size(); ++i) { + sz += vec[i].size(); + } + return sz; +} + +size_t get_depth(const SymVec& vec) { + size_t dp = 1; + for (unsigned i = 0; i < vec.size(); ++i) { + dp = std::max(dp, vec[i].depth()); + } + return dp; +} + +Sym::Sym(token_t tok, const SymVec& args_) : node(dag.end()) +{ + detail::SymKey key(tok, detail::SymArgs(args_)); + detail::SymValue val; + + node = dag.insert(pair(key, val)).first; + + if (__unchecked_refcount() == 0) { // new node, set some stats + node->second.size = 1 + get_size(args_); + node->second.depth = 1 + get_depth(args_); + + // token count + if (tok >= token_count.size()) { + token_count.resize(tok+1); + } + + incref(); + node->first.fixate(); + // call the factory function if available + if (factory) node->second.uniqueNodeStats = factory(*this); + + } + else incref(); +} + +Sym::Sym(token_t tok, const Sym& a) : node(dag.end()) { + SymVec args_; args_.push_back(a); + detail::SymKey key(tok, detail::SymArgs(args_)); + detail::SymValue val; + + node = dag.insert(pair(key, val)).first; + + if (__unchecked_refcount() == 0) { // new node, set some stats + node->second.size = 1 + get_size(args_); + node->second.depth = 1 + get_depth(args_); + + // token count + if (tok >= token_count.size()) { + token_count.resize(tok+1); + } + + incref(); + node->first.fixate(); + // call the factory function if available + if (factory) node->second.uniqueNodeStats = factory(*this); + } + else incref(); +} + +Sym::Sym(token_t tok) : node(dag.end()) { + detail::SymKey key(tok); + detail::SymValue val; + node = dag.insert(pair(key, val)).first; + + if (__unchecked_refcount() == 0) { // new node, set some stats + node->second.size = 1; + node->second.depth = 1; + + // token count + if (tok >= token_count.size()) { + token_count.resize(tok+1); + } + + incref(); + + // call the factory function if available + if (factory) node->second.uniqueNodeStats = factory(*this); + + } + else incref(); +} + +std::pair insert_subtree_impl(const Sym& cur, size_t w, const Sym& nw) { + if (w-- == 0) return make_pair(nw, !(nw == cur)); + + const SymVec& vec = cur.args(); + std::pair result; + unsigned i; + + for (i = 0; i < vec.size(); ++i) { + if (w < vec[i].size()) { + result = insert_subtree_impl(vec[i], w, nw); + if (result.second == false) return std::make_pair(cur, false); // unchanged + break; + } + w -= vec[i].size(); + } + SymVec newvec = cur.args(); + newvec[i] = result.first; + return make_pair(Sym(cur.token(), newvec), true); +} + +Sym insert_subtree(const Sym& cur, size_t w, const Sym& nw) { + return insert_subtree_impl(cur,w,nw).first; +} +Sym get_subtree(const Sym& cur, size_t w) { + if (w-- == 0) return cur; + + const SymVec& vec = cur.args(); + for (unsigned i = 0; i < vec.size(); ++i) { + if (w < vec[i].size()) return get_subtree(vec[i], w); + w-=vec[i].size(); + } + return cur; +} + + diff --git a/deprecated/eo/contrib/mathsym/sym/Sym.h b/deprecated/eo/contrib/mathsym/sym/Sym.h new file mode 100644 index 000000000..2eecc5985 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/sym/Sym.h @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef SYMNODE_H_ +#define SYMNODE_H_ + +#include + +#if __GNUC__ >= 3 +#include +#elif __GNUC__ < 3 +#include +using std::hash_map; +#endif + +/* Empty 'extra statistics' structure, derive from this to keep other characteristics of nodes */ +struct UniqueNodeStats { virtual ~UniqueNodeStats(){} }; + +#include "SymImpl.h" +#include "token.h" + +#if __GNUC__ == 4 +#define USE_TR1 1 +#else +#define USE_TR1 0 +#endif +// TR1 is buggy at times +#undef USE_TR1 +#define USE_TR1 0 + +#if USE_TR1 +#include +typedef std::tr1::unordered_map SymMap; +#else +typedef hash_map SymMap; +#endif + +typedef SymMap::iterator SymIterator; + +/* Sym is the tree, for which all the nodes are stored in a hash table. + * This makes checking for equality O(1) */ +class Sym +{ + public: + + Sym() : node(dag.end()) {} + explicit Sym(token_t token, const SymVec& args); + explicit Sym(token_t token, const Sym& args); + explicit Sym(token_t var); + + explicit Sym(SymIterator it) : node(it) { incref(); } + + Sym(const Sym& oth) : node(oth.node) { incref(); } + ~Sym() { decref(); } + + const Sym& operator=(const Sym& oth) { + if (oth.node == node) return *this; + decref(); + node = oth.node; + incref(); + return *this; + } + + /* Unique Stats are user defined */ + UniqueNodeStats* extra_stats() const { return empty()? 0 : node->second.uniqueNodeStats; } + + int hashcode() const { return node->first.get_hash_code(); } //detail::SymKey::Hash hash; return hash(node->first); } + + // Friends, need to touch the node + friend struct detail::SymKey::Hash; + friend struct detail::SymKey; + + unsigned refcount() const { return empty()? 0: node->second.refcount; } + + bool operator==(const Sym& other) const { + return node == other.node; + } + bool operator!=(const Sym& other) const { return !(*this == other); } + + bool empty() const { return node == dag.end(); } + + /* Support for traversing trees */ + unsigned arity() const { return node->first.arity(); } + token_t token() const { return node->first.token; } + + const SymVec& args() const { return node->first.vec(); } + + /* size() - depth */ + unsigned size() const { return empty()? 0 : node->second.size; } + unsigned depth() const { return empty()? 0 : node->second.depth; } + + SymMap::iterator iterator() const { return node; } + + /* Statics accessing some static members */ + static SymMap& get_dag() { return dag; } + + /* This function can be set to create some UniqueNodeStats derivative that can contain extra stats for a node, + * it can for instance be used to create ERC's and what not. */ + static void set_factory_function(UniqueNodeStats* (*f)(const Sym&)) { factory=f; } + static void clear_factory_function() { factory = 0; } + + static const std::vector& token_refcount() { return token_count; } + + unsigned address() const { return reinterpret_cast(&*node); } + + private : + + // implements getting subtrees + Sym private_get(size_t w) const; + + unsigned __unchecked_refcount() const { return node->second.refcount; } + + void incref() { + if (!empty()) { + ++(node->second.refcount); + ++token_count[token()]; + } + } + void decref() { + if (!empty()) { + --token_count[token()]; + if (--(node->second.refcount) == 0) { + dag.erase(node); + } + } + } + + // The one and only data member, an iterator into the static map below + SymIterator node; + + // A static hash_map that contains all live nodes.. + static SymMap dag; + + static std::vector token_count; + + // Factory function for creating extra node stats, default will be 0 + static UniqueNodeStats* (*factory)(const Sym&); + +}; + +/* Utility hash functor for syms */ +class HashSym { + public: + int operator()(const Sym& sym) const { return sym.hashcode(); } +}; + +/* Utility Functions */ + +// get_subtree retrieves a subtree by standard ordering (0=root, and then depth first) +Sym get_subtree(const Sym& org, size_t w); + +// insert_subtree uses the same ordering as get and inserts the second argument, returning a new tree +Sym insert_subtree(const Sym& org, size_t w, const Sym& nw); + +/* Get the successor from the hashtable, no particular purpose other than an interesting way to mutate */ +inline Sym next(const Sym& sym) { + SymIterator it = sym.iterator(); + ++it; + if (it == Sym::get_dag().end()) it = Sym::get_dag().begin(); + return Sym(it); +} + +#endif diff --git a/deprecated/eo/contrib/mathsym/sym/SymImpl.cpp b/deprecated/eo/contrib/mathsym/sym/SymImpl.cpp new file mode 100644 index 000000000..1e15e70a9 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/sym/SymImpl.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include "Sym.h" + +using namespace std; +namespace detail { + +class SymArgsImpl { + public: + std::vector owned_args; +}; + +size_t SymArgs::len() const { + return vec().size(); +} + +SymArgs::SymArgs() : pimpl( new SymArgsImpl ) { + args_ptr = &pimpl->owned_args; +} + +SymArgs::SymArgs(const std::vector& v) : pimpl(0) { + args_ptr = &v; +} + +SymArgs::~SymArgs() { + delete pimpl; +} + +SymArgs::SymArgs(const SymArgs& args) : pimpl(0), args_ptr(args.args_ptr) { + if (args.pimpl && args.args_ptr == &args.pimpl->owned_args) { + pimpl = new SymArgsImpl(*args.pimpl); + args_ptr = &pimpl->owned_args; + } +} + +SymArgs& SymArgs::operator=(const SymArgs& args) { + if (args.pimpl && args.args_ptr == &args.pimpl->owned_args) { + pimpl = new SymArgsImpl(*args.pimpl); + args_ptr = &pimpl->owned_args; + } else { + args_ptr = args.args_ptr; + } + + return *this; +} + +void SymArgs::fixate() const { + assert(pimpl == 0); + pimpl = new SymArgsImpl; + pimpl->owned_args = *args_ptr; + args_ptr = &pimpl->owned_args; +} + +// For Tackett's hashcode +#define PRIMET 21523 +#define HASHMOD 277218551 + +const int nprimes = 4; +const unsigned long primes[] = {3221225473ul, 201326611ul, 1610612741ul, 805306457ul}; + +int SymKey::calc_hash() const { + unsigned long hash = unsigned(token); + hash *= PRIMET; + + const std::vector& v = args.vec(); + for (unsigned i = 0; i < v.size(); ++i) { + hash += ( (v[i].address() >> 3) * primes[i%nprimes]) % HASHMOD; + } + + return hash;// % HASHMOD; +} + +bool SymKey::operator==(const SymKey& other) const { + if (token != other.token) return false; + return args.vec() == other.args.vec(); +} + +/* Just to store this info somewhere: + * + * Address Based Hash Function Implementation + * uint32 address_hash(char* addr) + * { + * register uint32 key; + * key = (uint32) addr; + * return (key >> 3) * 2654435761; + * } + */ + +SymValue::SymValue() : refcount(0), size(0), depth(0), uniqueNodeStats(0) {} + +SymValue::~SymValue() { delete uniqueNodeStats; } + + + +} // namespace detail diff --git a/deprecated/eo/contrib/mathsym/sym/SymImpl.h b/deprecated/eo/contrib/mathsym/sym/SymImpl.h new file mode 100644 index 000000000..b5bf96371 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/sym/SymImpl.h @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef __SYM_IMPL_H__ +#define __SYM_IMPL_H__ + +#include + +#include "token.h" + +class Sym; + +#if __GNUC__ > 4 +#include +typedef std::vector > std::vector; +//typedef std::vector SymVec; +#else +typedef std::vector SymVec; +#endif + + +namespace detail { + +class SymArgsImpl; +class SymArgs { + + mutable SymArgsImpl* pimpl; // contains circular reference to vector + mutable const std::vector* args_ptr; + + public: + + SymArgs(); + SymArgs(const std::vector& v); + ~SymArgs(); + + SymArgs(const SymArgs& args); + SymArgs& operator=(const SymArgs& other); + + size_t len() const; + const std::vector& vec() const { return *args_ptr; } + void fixate() const; +}; + +class SymKey +{ + public: + SymKey(token_t _token) : args(), token(_token), hash_code(calc_hash()) {} + SymKey(token_t _token, const detail::SymArgs& _args) : args(_args), token(_token), hash_code(calc_hash()) {} + + bool operator==(const SymKey& other) const; + + struct Hash + { + int operator()(const SymKey& k) const { return k.calc_hash(); }; + }; + + unsigned arity() const { return args.len(); } + const std::vector& vec() const { return args.vec(); } + + // fixates (i.e. claims memory) for the embedded vector of Syms + void fixate() const { args.fixate(); } + + int get_hash_code() const { return hash_code; } + + detail::SymArgs args; + token_t token; // identifies the function + + private: + int calc_hash() const; + int hash_code; +}; + +struct SymValue +{ + friend class Sym; + + SymValue(); + ~SymValue(); + + unsigned getRefCount() const { return refcount; } + unsigned getSize() const { return size; } + unsigned getDepth() const { return depth; } + + + + // for reference counting + unsigned refcount; + + // some simple stats + unsigned size; + unsigned depth; + UniqueNodeStats* uniqueNodeStats; + +}; + + +} // namespace detail + +#endif + diff --git a/deprecated/eo/contrib/mathsym/sym/token.h b/deprecated/eo/contrib/mathsym/sym/token.h new file mode 100644 index 000000000..68008959d --- /dev/null +++ b/deprecated/eo/contrib/mathsym/sym/token.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef TOKEN_H +#define TOKEN_H + + +typedef unsigned token_t; + +struct functor_t { + token_t token; + unsigned arity; +}; + +#endif diff --git a/deprecated/eo/contrib/mathsym/symreg.cpp b/deprecated/eo/contrib/mathsym/symreg.cpp new file mode 100644 index 000000000..5e55196bf --- /dev/null +++ b/deprecated/eo/contrib/mathsym/symreg.cpp @@ -0,0 +1,394 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 +#include +#include + +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using namespace std; + +typedef EoSym EoType; + +static int functions_added = 0; + +void add_function(LanguageTable& table, eoParser& parser, string name, unsigned arity, token_t token, const FunDef& fun); +void setup_language(LanguageTable& table, eoParser& parser); + +template +T& select(bool check, T& a, T& b) { if (check) return a; return b; } + +class eoBestIndividualStat : public eoSortedStat { + public: + eoBestIndividualStat() : eoSortedStat("", "best individual") {} + + void operator()(const vector& _pop) { + ostringstream os; + os << (Sym) *_pop[0]; + value() = os.str(); + } + +}; + +class AverageSizeStat : public eoStat { + public: + AverageSizeStat() : eoStat(0.0, "Average size population") {} + + void operator()(const eoPop& _pop) { + double total = 0.0; + for (unsigned i = 0; i < _pop.size(); ++i) { + total += _pop[i].size(); + } + value() = total/_pop.size(); + } +}; + +class SumSizeStat : public eoStat { + public: + SumSizeStat() : eoStat(0u, "Number of subtrees") {} + + void operator()(const eoPop& _pop) { + unsigned total = 0; + for (unsigned i = 0; i < _pop.size(); ++i) { + total += _pop[i].size(); + } + value() = total; + } +}; + +class DagSizeStat : public eoStat { + public: + DagSizeStat() : eoStat(0u, "Number of distinct subtrees") {} + + void operator()(const eoPop& _pop) { + value() = Sym::get_dag().size(); + } +}; + +int main(int argc, char* argv[]) { + + eoParser parser(argc, argv); + + /* Language */ + LanguageTable table; + setup_language(table, parser); + + /* Data */ + + eoValueParam datafile = parser.createParam(string(""), "datafile", "Training data", 'd', string("Regression"), true); // mandatory + double train_percentage = parser.createParam(1.0, "trainperc", "Percentage of data used for training", 0, string("Regression")).value(); + + /* Population */ + + unsigned pop_size = parser.createParam(500u, "population-size", "Population Size", 'p', string("Population")).value(); + + uint32_t seed = parser.createParam( uint32_t(time(0)), "random-seed", "Seed for rng", 'D').value(); + + cout << "Seed " << seed << endl; + rng.reseed(seed); + + double var_prob = parser.createParam( + 0.9, + "var-prob", + "Probability of selecting a var vs. const when creating a terminal", + 0, + "Population").value(); + + + double grow_prob = parser.createParam( + 0.5, + "grow-prob", + "Probability of selecting 'grow' method instead of 'full' in initialization and mutation", + 0, + "Population").value(); + + unsigned max_depth = parser.createParam( + 8u, + "max-depth", + "Maximum depth used in initialization and mutation", + 0, + "Population").value(); + + + bool use_uniform = parser.createParam( + false, + "use-uniform", + "Use uniform node selection instead of bias towards internal nodes (functions)", + 0, + "Population").value(); + + double constant_mut_prob = parser.createParam( + 0.1, + "constant-mut-rate", + "Probability of performing constant mutation", + 0, + "Population").value(); + + + double subtree_mut_prob = parser.createParam( + 0.2, + "subtree-mut-rate", + "Probability of performing subtree mutation", + 0, + "Population").value(); + + double node_mut_prob = parser.createParam( + 0.2, + "node-mut-rate", + "Probability of performing node mutation", + 0, + "Population").value(); + +/* double lambda_mut_prob = parser.createParam( + 1.0, + "lambda-mut-rate", + "Probability of performing (neutral) lambda extraction/expansion", + 0, + "Population").value(); +*/ + double subtree_xover_prob = parser.createParam( + 0.4, + "xover-rate", + "Probability of performing subtree crossover", + 0, + "Population").value(); + + double homologous_prob = parser.createParam( + 0.4, + "homologous-rate", + "Probability of performing homologous crossover", + 0, + "Population").value(); + + unsigned max_gens = parser.createParam( + 50, + "max-gens", + "Maximum number of generations to run", + 'g', + "Population").value(); + + unsigned tournamentsize = parser.createParam( + 5, + "tournament-size", + "Tournament size used for selection", + 't', + "Population").value(); + + unsigned maximumSize = parser.createParam( + -1u, + "maximum-size", + "Maximum size after crossover", + 's', + "Population").value(); + + unsigned meas_param = parser.createParam( + 2u, + "measure", + "Error measure:\n\ + 0 -> absolute error\n\ + 1 -> mean squared error\n\ + 2 -> mean squared error scaled (equivalent with correlation)\n\ + ", + 'm', + "Regression").value(); + + + ErrorMeasure::measure meas = ErrorMeasure::mean_squared_scaled; + if (meas_param == 0) meas = ErrorMeasure::absolute; + if (meas_param == 1) meas = ErrorMeasure::mean_squared; + + + /* End parsing */ + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + return 1; + } + + if (functions_added == 0) { + cout << "ERROR: no functions defined" << endl; + exit(1); + } + + + Dataset dataset; + dataset.load_data(datafile.value()); + + cout << "Data " << datafile.value() << " loaded " << endl; + + /* Add Variables */ + unsigned nvars = dataset.n_fields(); + for (unsigned i = 0; i < nvars; ++i) { + table.add_function( SymVar(i).token(), 0); + } + + TreeBuilder builder(table, var_prob); + eoSymInit init(builder, grow_prob, max_depth); + + eoPop pop(pop_size, init); + + BiasedNodeSelector biased_sel; + RandomNodeSelector random_sel; + + NodeSelector& node_selector = select(use_uniform, random_sel, biased_sel); + + //eoProportionalOp genetic_operator; + eoSequentialOp genetic_operator; + + eoSymSubtreeMutate submutate(builder, node_selector); + genetic_operator.add( submutate, subtree_mut_prob); + + // todo, make this parameter, etc + double std = 1.0; + eoSymConstantMutate constmutate(std); + genetic_operator.add(constmutate, constant_mut_prob); + + eoSymNodeMutate nodemutate(table); + genetic_operator.add(nodemutate, node_mut_prob); + +// eoSymLambdaMutate lambda_mutate(node_selector); +// genetic_operator.add(lambda_mutate, lambda_mut_prob); // TODO: prob should be settable + + //eoQuadSubtreeCrossover quad(node_selector); + eoSizeLevelCrossover bin;//(node_selector); + //eoBinSubtreeCrossover bin(node_selector); + genetic_operator.add(bin, subtree_xover_prob); + + eoBinHomologousCrossover hom; + genetic_operator.add(hom, homologous_prob); + + + IntervalBoundsCheck check(dataset.input_minima(), dataset.input_maxima()); + ErrorMeasure measure(dataset, train_percentage, meas); + + eoSymPopEval evaluator(check, measure, maximumSize); + + eoDetTournamentSelect selectOne(tournamentsize); + eoGeneralBreeder breeder(selectOne, genetic_operator,1); + eoPlusReplacement replace; + + // Terminators + eoGenContinue term(max_gens); + eoCheckPoint checkpoint(term); + + eoBestFitnessStat beststat; + checkpoint.add(beststat); + + eoBestIndividualStat printer; + AverageSizeStat avgSize; + DagSizeStat dagSize; + SumSizeStat sumSize; + + checkpoint.add(printer); + checkpoint.add(avgSize); + checkpoint.add(dagSize); + checkpoint.add(sumSize); + + eoStdoutMonitor genmon; + genmon.add(beststat); + genmon.add(printer); + genmon.add(avgSize); + genmon.add(dagSize); + genmon.add(sumSize); + genmon.add(term); // add generation counter + + checkpoint.add(genmon); + + eoPop dummy; + evaluator(pop, dummy); + + eoEasyEA ea(checkpoint, evaluator, breeder, replace); + + ea(pop); // run + +} + +void add_function(LanguageTable& table, eoParser& parser, string name, unsigned arity, token_t token, const FunDef& fun, bool all) { + ostringstream desc; + desc << "Enable function " << name << " arity = " << arity; + bool enabled = parser.createParam(false, name, desc.str(), 0, "Language").value(); + + if (enabled || all) { + cout << "Func " << name << " enabled" << endl; + table.add_function(token, arity); + if (arity > 0) functions_added++; + } +} + +void setup_language(LanguageTable& table, eoParser& parser) { + + bool all = parser.createParam(false,"all", "Enable all functions").value(); + bool ratio = parser.createParam(false,"ratio","Enable rational functions (inv,min,sum,prod)").value(); + bool poly = parser.createParam(false,"poly","Enable polynomial functions (min,sum,prod)").value(); + + // assumes that at this point all tokens are defined (none are zeroed out, which can happen with ERCs) + vector lang = get_defined_functions(); + + for (token_t i = 0; i < lang.size(); ++i) { + + if (lang[i] == 0) continue; + + bool is_poly = false; + if (poly && (i == prod_token || i == sum_token || i == min_token) ) { + is_poly = true; + } + + bool is_ratio = false; + if (ratio && (is_poly || i == inv_token)) { + is_ratio = true; + } + + const FunDef& fun = *lang[i]; + + if (fun.has_varargs() ) { + + for (unsigned j = fun.min_arity(); j < fun.min_arity() + 8; ++j) { + if (j==1) continue; // prod 1 and sum 1 are useless + ostringstream nm; + nm << fun.name() << j; + bool addanyway = (all || is_ratio || is_poly) && j == 2; + add_function(table, parser, nm.str(), j, i, fun, addanyway); + } + } + else { + add_function(table, parser, fun.name(), fun.min_arity(), i, fun, all || is_ratio || is_poly); + } + } +} + + diff --git a/deprecated/eo/contrib/mathsym/tcc.tar.gz b/deprecated/eo/contrib/mathsym/tcc.tar.gz new file mode 100644 index 000000000..5b9354733 Binary files /dev/null and b/deprecated/eo/contrib/mathsym/tcc.tar.gz differ diff --git a/deprecated/eo/contrib/mathsym/tcc_patched.tar.gz b/deprecated/eo/contrib/mathsym/tcc_patched.tar.gz new file mode 100644 index 000000000..9b82e54d8 Binary files /dev/null and b/deprecated/eo/contrib/mathsym/tcc_patched.tar.gz differ diff --git a/deprecated/eo/contrib/mathsym/test/test_compile.cpp b/deprecated/eo/contrib/mathsym/test/test_compile.cpp new file mode 100644 index 000000000..adac41a9f --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test/test_compile.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 +#include + +#include +#include +#include +#include +#include + +#include + +using namespace std; + +void test_xover(); + +int main() { + Dataset dataset; + dataset.load_data("test_data.txt"); + + cout << "Records/Fields " << dataset.n_records() << ' ' << dataset.n_fields() << endl; + + LanguageTable table; + table.add_function(sum_token, 2); + table.add_function(prod_token, 2); + table.add_function(sum_token, 0); + table.add_function(prod_token, 0); + table.add_function(inv_token, 1); + table.add_function(min_token, 1); + + for (unsigned i = 0; i < dataset.n_fields(); ++i) { + table.add_function( SymVar(i).token(), 0); + } + + TreeBuilder builder(table); + + IntervalBoundsCheck bounds(dataset.input_minima(), dataset.input_maxima() ); + ErrorMeasure measure(dataset, 1.0); + + + unsigned n = 1000; + unsigned k = 0; + + vector pop; + double sumsize = 0; + for (unsigned i = 0; i < n; ++i) { + + Sym sym = builder.build_tree(6, i%2); + pop.push_back(sym); + sumsize += sym.size(); + } + + cout << "Size " << sumsize/pop.size() << endl; + + // shuffle + for (unsigned gen = 0; gen < 10; ++gen) { + random_shuffle(pop.begin(), pop.end()); + for (unsigned i = 0; i < pop.size(); i+=2) { + + unsigned p1 = rng.random(pop[i].size()); + unsigned p2 = rng.random(pop[i+1].size()); + + Sym a = insert_subtree(pop[i], p1, get_subtree(pop[i+1], p2)); + Sym b = insert_subtree(pop[i+1], p2, get_subtree(pop[i], p1)); + + pop[i] = a; + pop[i+1] = b; + + } + cout << gen << ' ' << Sym::get_dag().size() << endl; + } + + vector oldpop; + swap(pop,oldpop); + for (unsigned i = 0; i < oldpop.size(); ++i) { + Sym sym = oldpop[i]; + if (!bounds.in_bounds(sym)) { + k++; + continue; + } + pop.push_back(sym); + } + + cout << "Done" << endl; + + // full compilation + + time_t start_time = time(0); + time_t compile_time; + { + multi_function f = compile(pop); + compile_time = time(0); + vector out(pop.size()); + + cout << "Compiled" << endl; + + for (unsigned j = 0; j < dataset.n_records(); ++j) { + f(&dataset.get_inputs(j)[0], &out[0]); + } + } + + time_t end_time = time(0); + + cout << "Evaluated " << n-k << " syms in " << end_time - start_time << " seconds, compile took " << compile_time - start_time << " seconds" << endl; + + start_time = time(0); + vector funcs; + compile(pop, funcs); + compile_time = time(0); + for (unsigned i = 0; i < pop.size(); ++i) { + + single_function f = funcs[i]; + for (unsigned j = 0; j < dataset.n_records(); ++j) { + f(&dataset.get_inputs(j)[0]); + } + + } + + end_time = time(0); + + cout << "Evaluated " << n-k << " syms in " << end_time - start_time << " seconds, compile took " << compile_time - start_time << " seconds" << endl; + return 0; // skip the 'slow' one-by-one method + start_time = time(0); + for (unsigned i = 0; i < pop.size(); ++i) { + + single_function f = compile(pop[i]); + for (unsigned j = 0; j < dataset.n_records(); ++j) { + f(&dataset.get_inputs(j)[0]); + } + + } + + end_time = time(0); + + cout << "Evaluated " << n-k << " syms in " << end_time - start_time << " seconds" << endl; + +} + +void test_xover() { + Sym c = SymVar(0); + Sym x = c + c * c + c; + + cout << c << endl; + cout << x << endl; + + vector pop; + for (unsigned i = 0; i < x.size(); ++i) { + for (unsigned j = 0; j < x.size(); ++j) { + + Sym s = insert_subtree(x, i, get_subtree(x, j)); + pop.push_back(s); + cout << i << ' ' << j << ' ' << s << endl; + } + } + + x = Sym(); + c = Sym(); + + SymMap& dag = Sym::get_dag(); + + for (SymMap::iterator it = dag.begin(); it != dag.end(); ++it) { + Sym s(it); + cout << s << ' ' << s.refcount() << endl; + } + + + +} + diff --git a/deprecated/eo/contrib/mathsym/test/test_diff.cpp b/deprecated/eo/contrib/mathsym/test/test_diff.cpp new file mode 100644 index 000000000..09dd292d4 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test/test_diff.cpp @@ -0,0 +1,17 @@ +#include +#include +#include + +using namespace std; + +int main() { + + Sym v = SymConst(1.2); + + Sym g = exp(-sqr(v)); + + cout << g << endl; + cout << differentiate(g, v.token()) << endl; + +} + diff --git a/deprecated/eo/contrib/mathsym/test/test_lambda.cpp b/deprecated/eo/contrib/mathsym/test/test_lambda.cpp new file mode 100644 index 000000000..dc8e1ac70 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test/test_lambda.cpp @@ -0,0 +1,34 @@ +#include + +using namespace std; + +int main() { + + Sym x = SymVar(0); + Sym y = SymVar(1); + + Sym f = y + x*x; + + Sym l = SymLambda(f); + + SymVec args = l.args(); + args[0] = x; + args[1] = y; + l = Sym(l.token(), args); + + vector v(3); + v[0] = 2.0; + v[1] = 3.0; + v[2] = 4.0; + + double v1 = eval(f,v); + double v2 = eval(l,v); + + cout << v1 << ' ' << v2 << endl; + cout << f << endl; + cout << l << endl; + + if (v1 != 7.0) return 1; + if (v2 != 11.0) return 1; +} + diff --git a/deprecated/eo/contrib/mathsym/test/test_mf.cpp b/deprecated/eo/contrib/mathsym/test/test_mf.cpp new file mode 100644 index 000000000..8cccfb128 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test/test_mf.cpp @@ -0,0 +1,45 @@ + +#include "Sym.h" +#include "MultiFunction.h" +#include "FunDef.h" + +using namespace std; + +int main() { + + Sym v = SymVar(0); + Sym c = SymConst(0.1); + + Sym sym = inv(v) + c; + Sym a = sym; + + sym = sym * sym; + Sym b = sym; + sym = sym + sym; + + c = sym; + + vector pop; + pop.push_back(sym); + + MultiFunction m(pop); + + + vector vec(1); + vec[0] = 10.0; + cout << sym << endl; + + cout << "Eval " << eval(sym, vec); + + vector y(1); + + m(vec,y); + + cout << " " << y[0] << endl; + + cout << "3 " << eval(a,vec) << endl; + cout << "4 " << eval(b, vec) << endl; + cout << "5 " << eval(c, vec) << endl; + +} + diff --git a/deprecated/eo/contrib/mathsym/test/test_simplify.cpp b/deprecated/eo/contrib/mathsym/test/test_simplify.cpp new file mode 100644 index 000000000..73c920f2a --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test/test_simplify.cpp @@ -0,0 +1,21 @@ + +#include + +using namespace std; + +int main() { + + Sym c1 = SymConst(0.4); + Sym c2 = SymConst(0.3); + Sym v1 = SymVar(0); + + Sym expr = (c1 + c2) * ( (c1 + c2) * v1); + + cout << expr << endl; + cout << simplify(expr) << endl; + + Sym dv = differentiate( exp(expr) , v1.token()); + cout << dv << endl; + cout << simplify(dv) << endl; +} + diff --git a/deprecated/eo/contrib/mathsym/test/testeo.cpp b/deprecated/eo/contrib/mathsym/test/testeo.cpp new file mode 100644 index 000000000..a15303cb0 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test/testeo.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2005 Maarten Keijzer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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 +#include +#include + +#include +#include +#include +#include +#include +#include + +typedef EoSym EoType; + +int main() { + + LanguageTable table; + table.add_function(sum_token, 2); + table.add_function(prod_token, 2); + table.add_function(inv_token, 1); + table.add_function(min_token, 1); + table.add_function( SymVar(0).token(), 0); + + table.add_function(tan_token, 1); + + table.add_function(sum_token, 0); + table.add_function(prod_token, 0); + + TreeBuilder builder(table); + + eoSymInit init(builder); + + eoPop pop(10, init); + + for (unsigned i = 0; i < pop.size(); ++i) { + // write out pretty printed + cout << (Sym) pop[i] << endl; + } + + BiasedNodeSelector node_selector; + eoSymSubtreeMutate mutate1(builder, node_selector); + eoSymNodeMutate mutate2(table); + + cout << "****** MUTATION ************" << endl; + + for (unsigned i = 0; i < pop.size(); ++i) { + + cout << "Before " << (Sym) pop[i] << endl; + mutate1(pop[i]); + cout << "After 1 " << (Sym) pop[i] << endl; + mutate2(pop[i]); + cout << "After 2 " << (Sym) pop[i] << endl; + } + + cout << "****** CROSSOVER ***********" << endl; + + eoQuadSubtreeCrossover quad(node_selector); + eoBinSubtreeCrossover bin(node_selector); + eoBinHomologousCrossover hom; + + for (unsigned i = 0; i < pop.size()-1; ++i) { + cout << "Before " << (Sym) pop[i] << endl; + cout << "Before " << (Sym) pop[i+1] << endl; + + hom(pop[i], pop[i+1]); + + cout << "After hom " << (Sym) pop[i] << endl; + cout << "After hom " << (Sym) pop[i+1] << endl; + + + quad(pop[i], pop[i+1]); + + cout << "After quad " << (Sym) pop[i] << endl; + cout << "After quad " << (Sym) pop[i+1] << endl; + + bin(pop[i], pop[i+1]); + + cout << "After bin " << (Sym) pop[i] << endl; + cout << "After bin " << (Sym) pop[i+1] << endl; + + cout << endl; + } + + cout << "****** Evaluation **********" << endl; + + Dataset dataset; + dataset.load_data("test_data.txt"); + IntervalBoundsCheck check(dataset.input_minima(), dataset.input_maxima()); + ErrorMeasure measure(dataset, 0.90, ErrorMeasure::mean_squared_scaled); + + eoSymPopEval evaluator(check, measure, 20000); + + eoPop dummy; + evaluator(pop, dummy); + + for (unsigned i = 0; i < pop.size(); ++i) { + cout << pop[i] << endl; + } + +} + diff --git a/deprecated/eo/contrib/mathsym/test_data.txt b/deprecated/eo/contrib/mathsym/test_data.txt new file mode 100644 index 000000000..754b1f0d1 --- /dev/null +++ b/deprecated/eo/contrib/mathsym/test_data.txt @@ -0,0 +1,102 @@ +# 101 2 nan nan + 0.0 -0 + 0.1 -8.89903723981037e-05 + 0.2 -0.00122598240763888 + 0.3 -0.00517587564272387 + 0.4 -0.0132382052428645 + 0.5 -0.0254643081877282 + 0.6 -0.0407070337997998 + 0.7 -0.057285499199392 + 0.8 -0.0737562490233578 + 0.9 -0.0892727708954409 + 1 -0.103268200413493 + 1.1 -0.114577577792354 + 1.2 -0.120446083316857 + 1.3 -0.116000062935524 + 1.4 -0.0946298417869761 + 1.5 -0.0493963195458011 + 1.6 0.0248409598316732 + 1.7 0.129207388804052 + 1.8 0.259260510831339 + 1.9 0.404709502287215 + 2 0.550653582802201 + 2.1 0.680124882844178 + 2.2 0.777313232294796 + 2.3 0.830628236863242 + 2.4 0.834788256127692 + 2.5 0.79140362503436 + 2.6 0.707953643967287 + 2.7 0.595509207315954 + 2.8 0.46588939354196 + 2.9 0.329064872475183 + 3 0.191504886385553 + 3.1 0.0558518299407852 + 3.2 -0.0781019284912663 + 3.3 -0.211542824409141 + 3.4 -0.344524221510933 + 3.5 -0.474312294176053 + 3.6 -0.594727989459508 + 3.7 -0.696713721292122 + 3.8 -0.769988957905497 + 3.9 -0.805344773512717 + 4 -0.796949283133396 + 4.1 -0.744036874310458 + 4.2 -0.651525836186196 + 4.3 -0.529396820025977 + 4.4 -0.39098574050144 + 4.5 -0.250612439788816 + 4.6 -0.121113466670896 + 4.7 -0.0118426008551395 + 4.8 0.0724429930487275 + 4.9 0.13163323998176 + 5 0.169341449166714 + 5.1 0.191319990014267 + 5.2 0.203657703492626 + 5.3 0.211210264725322 + 5.4 0.216611758596317 + 5.5 0.220036646440173 + 5.6 0.219677788419796 + 5.7 0.212731354762643 + 5.8 0.196574232374672 + 5.9 0.169803441763318 + 6 0.132875383837662 + 6.1 0.0882099910986659 + 6.2 0.0397733622937463 + 6.3 -0.00771703924831375 + 6.4 -0.0497388405970527 + 6.5 -0.0828196592845663 + 6.6 -0.105101954751146 + 6.7 -0.116508794142315 + 6.8 -0.118508967610477 + 6.9 -0.113576955648085 + 7 -0.104507044103426 + 7.1 -0.0937591677397028 + 7.2 -0.0829871341075209 + 7.3 -0.0728391340503617 + 7.4 -0.0630443677389944 + 7.5 -0.0527284491080759 + 7.6 -0.0408508284036276 + 7.7 -0.0266394584962638 + 7.8 -0.00991225704809318 + 7.9 0.00878546797299183 + 8 0.0282459694154097 + 8.1 0.0468334978875681 + 8.2 0.0628175943181446 + 8.3 0.0747179317764707 + 8.4 0.0815794072993519 + 8.5 0.0831208473565567 + 8.6 0.0797359724522078 + 8.7 0.072361534724142 + 8.8 0.0622560784562081 + 8.9 0.0507477567273995 + 9 0.0390091892966309 + 9.1 0.0279034956336959 + 9.2 0.0179233472968783 + 9.3 0.00922050032813963 + 9.4 0.00170282350837218 + 9.5 -0.00483635091477891 + 9.6 -0.010593872761556 + 9.7 -0.0156676782318098 + 9.8 -0.020019888098685 + 9.9 -0.0234934811028401 + 10 -0.0258701880584331 diff --git a/deprecated/eo/doc/CMakeLists.txt b/deprecated/eo/doc/CMakeLists.txt new file mode 100644 index 000000000..ac8c13ab2 --- /dev/null +++ b/deprecated/eo/doc/CMakeLists.txt @@ -0,0 +1,51 @@ +########################################################################################## +### EO Doc generation using Doxygen +########################################################################################## +IF (DOXYGEN_FOUND) + + SET(DOC_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "EO documentation directory") + SET(EO_DOC_CONFIG_FILE "eo.cfg" CACHE PATH "EO documentation configuration file") + + # Copy necessary doc files + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/index.h ${DOC_DIR}/index.h COPYONLY) + FILE(GLOB header_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.htm*) + FILE(GLOB pdf_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.pdf) + FILE(GLOB jpg_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.jpg) + FOREACH (file ${header_files} ${pdf_files} ${jpg_files}) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file} ${DOC_DIR}/${file} COPYONLY) + ENDFOREACH (file) + + # define the doc target + IF (DOXYGEN_EXECUTABLE) + # Creating the custom target + if(UNIX AND NOT ${CMAKE_VERBOSE_MAKEFILE}) + add_custom_target(doc-eo + COMMAND ${DOXYGEN_EXECUTABLE} ${EO_DOC_CONFIG_FILE} 2> /dev/null > /dev/null + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + else(UNIX AND NOT ${CMAKE_VERBOSE_MAKEFILE}) + ADD_CUSTOM_TARGET(doc-eo + COMMAND ${DOXYGEN_EXECUTABLE} ${EO_DOC_CONFIG_FILE} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + endif() + ENDIF (DOXYGEN_EXECUTABLE) + + # configure cfg file + CONFIGURE_FILE( + "${CMAKE_CURRENT_SOURCE_DIR}/${EO_DOC_CONFIG_FILE}.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/${EO_DOC_CONFIG_FILE}" + ) + + INSTALL( + DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + DESTINATION local/share${INSTALL_SUB_DIR}/eo COMPONENT doc + PATTERN "CMakeFiles" EXCLUDE + PATTERN "cmake_install.cmake" EXCLUDE + PATTERN "Makefile" EXCLUDE + PATTERN "eo.cfg" EXCLUDE + PATTERN "eo.doxytag" EXCLUDE + ) +ELSE (DOXYGEN_FOUND) + MESSAGE(STATUS "Unable to generate the documentation, Doxygen package not found") +ENDIF (DOXYGEN_FOUND) diff --git a/deprecated/eo/doc/ChangeLog b/deprecated/eo/doc/ChangeLog new file mode 100644 index 000000000..10c4be341 --- /dev/null +++ b/deprecated/eo/doc/ChangeLog @@ -0,0 +1,27 @@ +2007-01-23 Jochen Kpper + + * eo.cfg (PROJECT_NUMBER): Bump to 1.0.1 + +2006-12-18 Jochen Kpper + + * mainpage.html, publications.html: Update for release. + + * index.h: Add old ToDos + + * eo.cfg (PROJECT_NUMBER): Bump version to 1.0 + +2006-12-03 Jochen Kpper + + * mainpage.html: update, add link to Niko Hansen's comparison + +2006-12-01 Jochen Kpper + + * Makefile.am: Update for release-distribution. + + + + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/deprecated/eo/doc/EO_EA2001.pdf b/deprecated/eo/doc/EO_EA2001.pdf new file mode 100644 index 000000000..2a3116f3d Binary files /dev/null and b/deprecated/eo/doc/EO_EA2001.pdf differ diff --git a/deprecated/eo/doc/LeCreusot.pdf b/deprecated/eo/doc/LeCreusot.pdf new file mode 100644 index 000000000..7c0acb95c Binary files /dev/null and b/deprecated/eo/doc/LeCreusot.pdf differ diff --git a/eo/doc/eo.cfg.cmake b/deprecated/eo/doc/eo.cfg.cmake similarity index 100% rename from eo/doc/eo.cfg.cmake rename to deprecated/eo/doc/eo.cfg.cmake diff --git a/deprecated/eo/doc/index.h b/deprecated/eo/doc/index.h new file mode 100644 index 000000000..52a5758cf --- /dev/null +++ b/deprecated/eo/doc/index.h @@ -0,0 +1,62 @@ +/** @mainpage Welcome to Evolving Objects + +@section shortcuts In one word + +The best place to learn about the features and approaches of %EO with the help of examples is to look at +the tutorial. + +Once you have understand the @ref design of %EO, you could search for advanced features by browsing the modules page. + + +@section intro Introduction + + %EO is a template-based, ANSI-C++ evolutionary computation library which helps you to write your own stochastic optimization algorithms insanely fast. + +It contains classes for almost any kind of evolutionary computation you might come +up to - at least for the ones we could think of. It is component-based, so that +if you don't find the class you need in it, it is very easy to subclass existing +abstract or concrete classes. + +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. + + + +@section design Overall Design + +%EO is a framework. It is oriented toward facilitating the design of adhoc evolutionary algorithms. +It is not (at the moment) a complete library of algorithms ready to use on canonical problems. + +If you have a well-known problem and want to solve it as soon as possible, try another software. +If you have a real problem and want to build the best evolutionary algorithm to solve it, you've made +the good choice. + +Bascially, %EO manipulate "individuals" with a "fitness", that is objects +encoding a solution to a given optimization problem, associated with +the quality of this solution. The fitness is defined in the %EO class, +but the representation of a solution cannot be as generic. Thus, %EO +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. +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, +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 +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 + - http://eodev.sourceforge.net/eo/doc/LeCreusot.pdf + - http://eodev.sourceforge.net/eo/doc/EO_EA2001.pdf +*/ diff --git a/deprecated/eo/doc/mainpage.html b/deprecated/eo/doc/mainpage.html new file mode 100644 index 000000000..e175850c6 --- /dev/null +++ b/deprecated/eo/doc/mainpage.html @@ -0,0 +1,280 @@ + + + + + + + + +EO Evolutionary Computation Framework + + + +
+

EO Evolutionary Computation Framework

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

What is EO?

+
+ +

EO is a templates-based, ANSI-C++ compliant evolutionary computation + library. It contains classes for almost any kind of evolutionary + computation you might come up to - at least for the ones we could think + of. It is component-based, so that if you don't find the class you need + in it, it is very easy to subclass existing abstract or concrete + classes.

+ +

EO was started by the Geneura + Team at the University of Granada, headed by Juan Julin Merelo. The original Web site is also the only place where you + will find old releases of EO (up to 0.8.7), but beware that it is not + compatible at all with the current version.

+ +

The developement team has then been reinforced by Maarten Keijzer, the C++ + wizzard, and Marc Schoenauer. + Later came Jeroen + Eggermont, who, among other things, did a lot of work on GP, + INRIA Dolphin Team, Olivier Knig, who did a + lot of useful additions and cleaning of the code and Jochen Kpper, working on + infrastructure maintenance.

+ +
+

Platforms

+
+ +

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
  • +
+ +

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.

+ +
+

Documentation

+
+ +

The tutorial demonstrates that writing an evolutionary algorithm + evolving your own structures is now easy, using ready-to-use + template files. Although the tutorial has not been upgraded for some + time now and refers to version 0.9.2 of EO, it nevertheless remains the + best way to dive into EO. You can start by trying it on-line at LRI + or SourceForge, + before downloading it. The + tutorial is also included in the released + sources.

+ +

The latest tutorial + release +

+ +

The complete code is also well documented and you can look at the + generated interface + documentation.

+ +

The easiest way to create a complete new EO-project, even for new + genomes, is to use the script provided in tutorial/Templates/; see + the README in that directory and lesson 5 of the tutorial for + detail.

+ +
+

Presentations

+
+ +

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

+ +

A PowerPoint presentation shows the EO philosophy, and + it includes a Visual Basic macro for evolving objects in Visual Basic + for Applications.

+ +

You can also look a the list of + publications that used EO to solve real problems.

+ +
+

Download

+
+ +

The current release is EO 1.0. + It supports any Standard-compliant C++ compiler.

+ +

You can obtain the latest version directly via cvs or download a + daily snapshot from LRI.

+ +

All releases can be obtained from the SourceForge download + area.

+ +
+

Mailing Lists

+
+ + We would like EO to be an open development effort; that is why we have + created mailing lists to discuss future developments, solve technical + problems, announce releases, publish patches, and discuss evolutionary + computation in general. Browse the archives or join the EO mailing lists. + +
+

EO@sourceforge

+
+ +

The following resources are available, thanks to sourceforge

+ +
+

License

+
EO is distributed under the + GNU Lesser General + Public License + +
+

Related Apps

+
+ +

ParadisEO provides EO extensions for + the flexible design of single solution-based metaheuristics, + metaheuristics for multi objective optimization as well as hybrid, parallel and distributed + metaheuristics.

+ +

DegaX is an ActiveX control which embeds EO 0.8.4. +

+ +
+

Links

+
+ + +
+ +

Hosted by:
SF logo

+ +

Valid HTML 4.01 Transitional
Please send comments on this webpage to the EO mailing +list.

+ + + + + + + + + diff --git a/deprecated/eo/doc/publications.html b/deprecated/eo/doc/publications.html new file mode 100644 index 000000000..26ff646f4 --- /dev/null +++ b/deprecated/eo/doc/publications.html @@ -0,0 +1,75 @@ + + + + + + + + + EO Evolutionary Computation Framework + + + +
+

List of publications using EO

+
+ + + + + + + + + +
+

+ M. + Keijzer, J.J. Merelo, G. Romero, G., M. Schoenauer: "Evolving + objects: A general purpose evolutionary computation + library", Art. Evol. 2310, 231-242 (2002). +

+
+

+ J.J. Gilijamse, J. Kpper, + S. Hoekstra, S.Y.T. van de Meerakker, G. Meijer: + "Optimizing the Stark-decelerator beamline for the trapping of + cold molecules using evolutionary strategies", + Phys. Rev. A 73, 063410 (2006).
+ Also available at arXiv + physics/0603108 (2006). +

+
+
+

+ Hosted by:
SF logo +

+
+

+ + Valid HTML 4.01 Transitional +
+ Please send publications that belong on this page and general comments on + this webpage to + the EO + mailing list. +

+ + + + + + + + diff --git a/deprecated/eo/doc/sflogo-hammer1.jpg b/deprecated/eo/doc/sflogo-hammer1.jpg new file mode 100644 index 000000000..a7e2f00f4 Binary files /dev/null and b/deprecated/eo/doc/sflogo-hammer1.jpg differ diff --git a/deprecated/eo/install_symlink.py.cmake b/deprecated/eo/install_symlink.py.cmake new file mode 100755 index 000000000..fd71d68b5 --- /dev/null +++ b/deprecated/eo/install_symlink.py.cmake @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +#NAME = "@PROJECT_NAME@" +NAME = "eo" +SOURCE = "@CMAKE_SOURCE_DIR@" +BINARY = "@CMAKE_BINARY_DIR@" +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)), + ] + } + +LIBRARIES = ["libcma.a", "libeo.a", "libeoutils.a", "libes.a", "libga.a"] +DATA['links'] += [ ("%s/lib/%s" % (BINARY, lib), "%s/lib/%s" % (PREFIX, lib)) for lib in LIBRARIES ] + +import os, sys + +def isroot(): + if os.getuid() != 0: + print('[WARNING] you have to be root') + return False + return True + +def uninstall(): + for dummy, link in DATA['links']: os.remove(link) + for dirname in DATA['dirs']: os.rmdir(dirname) + print('All symlinks have been removed.') + +def install(): + for dirname in DATA['dirs']: os.mkdir(dirname) + for src, dst in DATA['links']: os.symlink(src, dst) + print('All symlinks have been installed.') + +def data(): + from pprint import pprint + pprint(DATA, width=200) + +if __name__ == '__main__': + if not isroot(): + sys.exit() + + if len(sys.argv) < 2: + print(('Usage: %s [install|uninstall|data]' % sys.argv[0])) + sys.exit() + + if sys.argv[1] == 'install': install() + elif sys.argv[1] == 'uninstall': uninstall() + elif sys.argv[1] == 'data': data() diff --git a/deprecated/eo/pc.cmake b/deprecated/eo/pc.cmake new file mode 100644 index 000000000..ad3c17ef2 --- /dev/null +++ b/deprecated/eo/pc.cmake @@ -0,0 +1,6 @@ +# Package Information for pkg-config +Name: @PACKAGE_NAME@ +Description: @PACKAGE_NAME@ +Version: @PROJECT_VERSION@ +Libs: -L@PCPREFIX@/lib @PCFLAGS@ +Cflags: -I@PCPREFIX@/include/@PCINCLUDEDIR@ diff --git a/deprecated/eo/src/CMakeLists.txt b/deprecated/eo/src/CMakeLists.txt new file mode 100644 index 000000000..7042e065e --- /dev/null +++ b/deprecated/eo/src/CMakeLists.txt @@ -0,0 +1,54 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the eo target +###################################################################################### + +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 + ) + +ADD_LIBRARY(eo STATIC ${EO_SOURCES}) +INSTALL(TARGETS eo ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +FILE(GLOB HDRS *.h eo) +INSTALL(FILES ${HDRS} DESTINATION local/include${INSTALL_SUB_DIR}/eo COMPONENT headers) + +INSTALL(DIRECTORY do es ga gp other utils + DESTINATION local/include${INSTALL_SUB_DIR}/eo + COMPONENT headers + FILES_MATCHING PATTERN "*.h" PATTERN "checkpointing" PATTERN external_eo + ) + +###################################################################################### +### 3) Optionnal: define your target(s)'s version: no effect for windows +###################################################################################### + +SET(EO_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(eo PROPERTIES VERSION "${EO_VERSION}") + +###################################################################################### +### 4) Where must cmake go now ? +###################################################################################### + +ADD_SUBDIRECTORY(es) +ADD_SUBDIRECTORY(ga) +ADD_SUBDIRECTORY(utils) + +IF(ENABLE_PYEO) + ADD_SUBDIRECTORY(pyeo) +ENDIF(ENABLE_PYEO) + +###################################################################################### diff --git a/deprecated/eo/src/EO.h b/deprecated/eo/src/EO.h new file mode 100644 index 000000000..f904559d4 --- /dev/null +++ b/deprecated/eo/src/EO.h @@ -0,0 +1,173 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// EO.h +// (c) GeNeura Team 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EO_H +#define EO_H + +//----------------------------------------------------------------------------- + +#include // std::runtime_error +#include // eoObject +#include // eoPersistent + +/** + @defgroup Core Core components + + This are the base classes from which useful objects inherits. + + @{ + */ + +/** 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. + + 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. + + 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. + + The fitness object must have, besides an void ctor, a copy ctor. + + @example t-eo.cpp +*/ +template class EO: public eoObject, public eoPersistent +{ +public: + typedef F Fitness; + + /** Default constructor. + */ + EO(): repFitness(Fitness()), invalidFitness(true) { } + + /// Virtual dtor + virtual ~EO() {}; + + /// Return fitness value. + const Fitness& fitness() const { + if (invalid()) + throw std::runtime_error("invalid fitness"); + return repFitness; + } + + /// Get fitness as reference, useful when fitness is set in a multi-stage way, e.g., MOFitness gets performance information, is subsequently ranked + Fitness& fitnessReference() { + if (invalid()) throw std::runtime_error("invalid fitness"); + return repFitness; + } + + // Set fitness as invalid. + void invalidate() { invalidFitness = true; repFitness = Fitness(); } + + /** Set fitness. At the same time, validates it. + * @param _fitness New fitness value. + */ + void fitness(const Fitness& _fitness) + { + repFitness = _fitness; + invalidFitness = false; + } + + /** Return true If fitness value is invalid, false otherwise. + * @return true If fitness is invalid. + */ + bool invalid() const { return invalidFitness; } + + /** Returns true if + @return true if the fitness is higher + */ + bool operator<(const EO& _eo2) const { return fitness() < _eo2.fitness(); } + bool operator>(const EO& _eo2) const { return !(fitness() <= _eo2.fitness()); } + + /// Methods inherited from eoObject + //@{ + + /** Return the class id. + * @return the class name as a std::string + */ + virtual std::string className() const { return "EO"; } + + /** + * Read object.\\ + * Calls base class, just in case that one had something to do. + * The read and print methods should be compatible and have the same format. + * In principle, format is "plain": they just print a number + * @param _is a std::istream. + * @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. + std::string fitness_str; + int pos = _is.tellg(); + _is >> fitness_str; + + if (fitness_str == "INVALID") + { + invalidFitness = true; + } + else + { + invalidFitness = false; + _is.seekg(pos); // rewind + _is >> repFitness; + } + } + + /** + * Write object. Called printOn since it prints the object _on_ a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const { + + + // the latest version of the code. Very similar to the old code + if (invalid()) { + _os << "INVALID "; + } + else + { + _os << repFitness << ' '; + } + + } + + //@} + +private: + Fitness repFitness; // value of fitness for this chromosome + bool invalidFitness; // true if the value of fitness is invalid +}; + + +#endif + +/** @} */ diff --git a/deprecated/eo/src/PO.h b/deprecated/eo/src/PO.h new file mode 100644 index 000000000..0c246135e --- /dev/null +++ b/deprecated/eo/src/PO.h @@ -0,0 +1,191 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// PO.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef PO_H +#define PO_H + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + +/** PO inheriting from EO is specially designed for particle swarm optimization particle.POs have got a fitness, + which at the same time needs to be only an object with the operation less than (<) + defined. A best fitness also belongs to the particle.Fitness says how + good is the particle for a current iteration whereas the best fitness can be saved for + many iterations. + + @ingroup Core +*/ +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 + + /** Default constructor. + Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor. + */ + PO ():repFitness (Fitness ()), invalidFitness (true), + bestFitness (Fitness()){} + + + /// Return fitness value. + Fitness fitness () const + { + if (invalid ()) + throw std::runtime_error ("invalid fitness in PO.h"); + return repFitness; + } + + + /** Set fitness. At the same time, validates it. + * @param _fitness New fitness value. + */ + void fitness (const Fitness & _fitness) + { + repFitness = _fitness; + invalidFitness = false; + } + + /** Return the best fitness. + * @return bestFitness + */ + Fitness best () const + { + if (invalid ()) + throw std::runtime_error ("invalid best fitness in PO.h"); + return bestFitness; + } + + + /** Set the best fitness. + * @param _bestFitness New best fitness found for the particle. + */ + void best (const Fitness & _bestFitness) + { + bestFitness = _bestFitness; + invalidBestFitness = false; + } + + + /** Return true If fitness value is invalid, false otherwise. + * @return true If fitness is invalid. + */ + bool invalid () const + { + return invalidFitness; + } + + /** Invalidate the fitness. + * @return + */ + void invalidate () + { + invalidFitness = true; + } + + /** Return true If the best fitness value is invalid, false otherwise. + * @return true If the bestfitness is invalid. + */ + bool invalidBest () const + { + return invalidBestFitness; + } + + /** Invalidate the best fitness. + * @return + */ + void invalidateBest () + { + invalidBestFitness = true; + } + + /** Return the class id. + * @return the class name as a std::string + */ + virtual std::string className () const + { + return "PO"; + } + + /** Returns true if + @return true if the fitness is higher + */ + bool operator< (const PO & _po2) const { return fitness () < _po2.fitness ();} + bool operator> (const PO & _po2) const { return !(fitness () <= _po2.fitness ());} + + + /** + * Write object. Called printOn since it prints the object _on_ a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const { _os << bestFitness << ' ' ;} + + + /** + * Read object.\\ + * Calls base class, just in case that one had something to do. + * The read and print methods should be compatible and have the same format. + * In principle, format is "plain": they just print a number + * @param _is a std::istream. + * @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. + std::string fitness_str; + int pos = _is.tellg(); + _is >> fitness_str; + + if (fitness_str == "INVALID") + { + invalidFitness = true; + } + else + { + invalidFitness = false; + _is.seekg(pos); // rewind + _is >> repFitness; + } + } + +private: + Fitness repFitness; // value of fitness for this particle + bool invalidFitness; // true if the value of the fitness is invalid + + Fitness bestFitness; // value of the best fitness found for the particle + bool invalidBestFitness; // true if the value of the best fitness is invalid + +}; + +//----------------------------------------------------------------------------- + +#endif /*PO_H */ diff --git a/deprecated/eo/src/apply.h b/deprecated/eo/src/apply.h new file mode 100644 index 000000000..f685f8d3b --- /dev/null +++ b/deprecated/eo/src/apply.h @@ -0,0 +1,119 @@ +// -*- 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 _apply_h +#define _apply_h + +#include +#include +#include +#include +#include +#include + +/** + Applies a unary function to a std::vector of things. + + @ingroup Utilities +*/ +template +void apply(eoUF& _proc, std::vector& _pop) +{ + size_t size = _pop.size(); + +#ifdef _OPENMP + + double t1 = 0; + + if ( eo::parallel.enableResults() ) + { + t1 = omp_get_wtime(); + } + + 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]); } + } + + if ( eo::parallel.enableResults() ) + { + double t2 = omp_get_wtime(); + eoLogger log; + log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; + } + +#else // _OPENMP + + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } + +#endif // !_OPENMP +} + +/** + 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) +// { +// size_t size = _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]); +// } +// } + +/** + And now we are using the dynamic scheduling. + + @ingroup Utilities +*/ +// template +// void omp_dynamic_apply(eoUF& _proc, std::vector& _pop) +// { +// size_t size = _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]); +// } +// } + +#endif diff --git a/deprecated/eo/src/do/Readme b/deprecated/eo/src/do/Readme new file mode 100644 index 000000000..0b3ccd8ac --- /dev/null +++ b/deprecated/eo/src/do/Readme @@ -0,0 +1,36 @@ +This directory contains templatized code that is supposed to be +instanciated and compiled in an actual library for every type of EOT + +The user can then modify and recompile only the part he/she wishes to +change (as in any library!). + +See in EO src/ga dir the corresponding .cpp files, that simply instanciate +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 +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 +is defined + +make_algo_scalar.h The selection/replacement for scalar fitnesses +make_checkpoint.h The output facilities +make_continue.h The stpping criteria +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) + +Note: +----- +two additional make_XXX.h files need to be defined for each representation + +make_genotype.h Builds an initializer for the corresponding EOType +make_op.h Builds a general Operator to be used in the algo + +MS, April 23, 2001 + July 23, 2001 diff --git a/deprecated/eo/src/do/make_algo_easea.h b/deprecated/eo/src/do/make_algo_easea.h new file mode 100644 index 000000000..c432c1e82 --- /dev/null +++ b/deprecated/eo/src/do/make_algo_easea.h @@ -0,0 +1,389 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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: Pierre.Collet@polytechnique.fr + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_algo_easea_h +#define _make_algo_easea_h + +#include // for eo_is_a_rate +// everything tha's needed for the algorithms - SCALAR fitness + +// Selection +// the eoSelectOne's +#include +#include +#include +#include +#include +#include +#include +// #include included in all others + +// Breeders +#include + +// Replacement +#include "make_general_replacement.h" +#include "eoMGGReplacement.h" +#include "eoG3Replacement.h" + + +// Algorithm (only this one needed) +#include + + // also need the parser and param includes +#include +#include + +/* + * This function builds the algorithm (i.e. selection and replacement) + * from existing continue (or checkpoint) and operators + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * This is why the template is the complete EOT even though only the fitness + * is actually templatized here + * + * + * @ingroup Builders +*/ +template +eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalFunc& _popeval, eoContinue& _continue, eoGenOp& _op) +{ + // the selection + eoValueParam& selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection", "Selection: Roulette, Ranking(p,e), DetTour(T), StochTour(t), Sequential(ordered/unordered) or EliteSequentialSelect", 'S', "Evolution Engine"); + + eoParamParamType & ppSelect = selectionParam.value(); // std::pair > + + eoSelectOne* select ; + 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")); + } + 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("StochTour")) + { + 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()); + + 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()); + } + 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")); + } + // 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")); + } + // 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")); + } + // now we're OK + eoPerf2Worth & p2w = _state.storeFunctor( new eoRanking(p,e) ); + select = new eoRouletteWorthSelect(p2w); + } + else if (ppSelect.first == std::string("Sequential")) // one after the other + { + 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")); + } + else + 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 + { + select = new eoEliteSequentialSelect; + } + else if (ppSelect.first == std::string("Roulette")) // no argument (yet) + { + select = new eoProportionalSelect; + } + else if (ppSelect.first == std::string("Random")) // no argument + { + select = new eoRandomSelect; + } + else + { + std::string stmp = std::string("Invalid selection: ") + ppSelect.first; + throw std::runtime_error(stmp.c_str()); + } + + _state.storeFunctor(select); + + // the number of offspring + eoValueParam& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); + + ///////////////////////////////////////////////////// + // the replacement + ///////////////////////////////////////////////////// + + /** Replacement type - high level: predefined replacements + * ESComma : + * elite = 0 + * surviveParents=0 (no reduce) + * surviveOffspring=100% (no reduce) + * reduceFinal = Deterministic + * + * ESPlus : idem, except for + * surviveParents = 100% + * + * GGA : generational GA - idem ESComma except for + * offspringRate = 100% + * all reducers are unused + * + * SSGA(T/t) : Steady-State GA + * surviveParents = 1.0 - offspringRate + * reduceFinal = DetTour(T>1) ou StochTour(0.5 * ptReplace; + + // first, separate G3 and MGG + // maybe one day we have a common class - but is it really necessary??? + if (replacementParam.first == std::string("G3")) + { + // reduce the parents: by default, survive parents = -2 === 2 parents die + eoHowMany surviveParents = _parser.createParam(eoHowMany(-2,false), "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); + // at the moment, this is the only argument + ptReplace = new eoG3Replacement(-surviveParents); // must receive nb of eliminated parets! + _state.storeFunctor(ptReplace); + } + else if (replacementParam.first == std::string("MGG")) + { + float t; + unsigned tSize; + // reduce the parents: by default, survive parents = -2 === 2 parents die + eoHowMany surviveParents = _parser.createParam(eoHowMany(-2,false), "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); + // 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")); + } + 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"); + } + } + 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); + eoHowMany surviveParents (0.0); + eoParamParamType reduceParentType ("Deterministic"); + eoHowMany surviveOffspring (1.0); + eoParamParamType reduceOffspringType ("Deterministic"); + eoParamParamType reduceFinalType ("Deterministic"); + + // depending on the value entered by the user, change some of the above + double t; + + // ---------- General + if (replacementParam.first == std::string("General")) + { + ; // defaults OK + } + // ---------- ESComma + else if (replacementParam.first == std::string("ESComma")) + { + ; // OK too + } + // ---------- ESPlus + else if (replacementParam.first == std::string("ESPlus")) + { + surviveParents = eoHowMany(1.0); + } + // ---------- Generational + else if (replacementParam.first == std::string("Generational")) + { + ; // 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")); + } + // by coincidence, the syntax for the EP reducer is the same than here: + reduceFinalType = replacementParam; + surviveParents = eoHowMany(1.0); + } + // ---------- SSGA + else if (replacementParam.first == std::string("SSGA")) + { + 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)")); + } + 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() + ")"); + } + } + // + surviveParents = eoHowMany(-1); + surviveOffspring = eoHowMany(1); + } + else // no replacement recognized + { + throw std::runtime_error("Invalid replacement type " + replacementParam.first); + } + + ptReplace = & make_general_replacement( + _parser, _state, elite, strongElitism, surviveParents, reduceParentType, surviveOffspring, reduceOffspringType, reduceFinalType); + + } // end of the ugly construct due to G3 and MGG - totaly heterogeneous at the moment + + + /////////////////////////////// + // the general breeder + /////////////////////////////// + eoGeneralBreeder *breed = + new eoGeneralBreeder(*select, _op, offspringRateParam.value()); + _state.storeFunctor(breed); + + /////////////////////////////// + // now the eoEasyEA + /////////////////////////////// + eoAlgo *algo = new eoEasyEA(_continue, _popeval, *breed, *ptReplace); + _state.storeFunctor(algo); + // that's it! + return *algo; +} + +/* + * This function builds the algorithm (i.e. selection and replacement) + * from existing continue (or checkpoint) and operators + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * This is why the template is the complete EOT even though only the fitness + * is actually templatized here +*/ +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); +} + + + +#endif diff --git a/deprecated/eo/src/do/make_algo_scalar.h b/deprecated/eo/src/do/make_algo_scalar.h new file mode 100644 index 000000000..52df8f4f4 --- /dev/null +++ b/deprecated/eo/src/do/make_algo_scalar.h @@ -0,0 +1,313 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_algo_scalar_h +#define _make_algo_scalar_h + +#include // for eo_is_a_rate +// everything tha's needed for the algorithms - SCALAR fitness + +// Selection +// the eoSelectOne's +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Breeders +#include + +// Replacement +// #include +#include +#include +#include + +// distance +#include + +// Algorithm (only this one needed) +#include + + // also need the parser and param includes +#include +#include + + +/* + * This function builds the algorithm (i.e. selection and replacement) + * from existing continue (or checkpoint) and operators + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * This is why the template is the complete EOT even though only the fitness + * is actually templatized here + * + * @ingroup Builders +*/ +template +eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op, eoDistance * _dist = NULL) +{ + // the selection : help and comment depend on whether or not a distance is passed + std::string comment; + 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)"; + + 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")) + { + 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")); + } + 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")) + { + 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")); + } + else // parameter passed by user as DetTour(T) + nicheSize = atof(ppSelect.second[0].c_str()); + 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); + } + else if (ppSelect.first == std::string("StochTour")) + { + 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()); + + 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()); + } + 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")); + } + // 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")); + } + // 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")); + } + // now we're OK + eoPerf2Worth & p2w = _state.storeFunctor( new eoRanking(p,e) ); + select = new eoRouletteWorthSelect(p2w); + } + else if (ppSelect.first == std::string("Sequential")) // one after the other + { + 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")); + } + else + b = !(ppSelect.second[0] == std::string("unordered")); + select = new eoSequentialSelect(b); + } + else if (ppSelect.first == std::string("Roulette")) // no argument (yet) + { + select = new eoProportionalSelect; + } + else if (ppSelect.first == std::string("Random")) // no argument + { + select = new eoRandomSelect; + } + else + { + std::string stmp = std::string("Invalid selection: ") + ppSelect.first; + throw std::runtime_error(stmp.c_str()); + } + + _state.storeFunctor(select); + + // the number of offspring + eoValueParam& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); + + // the replacement + eoValueParam& replacementParam = _parser.createParam(eoParamParamType("Comma"), "replacement", "Replacement: Comma, Plus or EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t)", 'R', "Evolution Engine"); + + eoParamParamType & ppReplace = replacementParam.value(); // std::pair > + + eoReplacement* replace ; + if (ppReplace.first == std::string("Comma")) // Comma == generational + { + replace = new eoCommaReplacement; + } + else if (ppReplace.first == std::string("Plus")) + { + replace = new eoPlusReplacement; + } + 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()); + + replace = new eoEPReplacement(detSize); + } + else if (ppReplace.first == std::string("SSGAWorst")) + { + replace = new eoSSGAWorseReplacement; + } + 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()); + + 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()); + + replace = new eoSSGAStochTournamentReplacement(p); + } + else + { + std::string stmp = std::string("Invalid replacement: ") + ppReplace.first; + throw std::runtime_error(stmp.c_str()); + } + + _state.storeFunctor(replace); + + // adding weak elitism + eoValueParam& weakElitismParam = _parser.createParam(false, "weakElitism", "Old best parent replaces new worst offspring *if necessary*", 'w', "Evolution Engine"); + if (weakElitismParam.value()) + { + eoReplacement *replaceTmp = replace; + replace = new eoWeakElitistReplacement(*replaceTmp); + _state.storeFunctor(replace); + } + + // the general breeder + eoGeneralBreeder *breed = + new eoGeneralBreeder(*select, _op, offspringRateParam.value()); + _state.storeFunctor(breed); + + // now the eoEasyEA + eoAlgo *algo = new eoEasyEA(_continue, _eval, *breed, *replace); + _state.storeFunctor(algo); + // that's it! + return *algo; +} +/** @example t-eoGA.cpp + */ + +#endif diff --git a/deprecated/eo/src/do/make_checkpoint.h b/deprecated/eo/src/do/make_checkpoint.h new file mode 100644 index 000000000..8e5295115 --- /dev/null +++ b/deprecated/eo/src/do/make_checkpoint.h @@ -0,0 +1,353 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_checkpoint.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk +*/ +//----------------------------------------------------------------------------- + +#ifndef _make_checkpoint_h +#define _make_checkpoint_h + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +#include +#include // for minimizing_fitness() +#include +#include +#include + +// at the moment, in utils/make_help.cpp +// this should become some eoUtils.cpp with corresponding eoUtils.h +bool testDirRes(std::string _dirName, bool _erase); +/////////////////// The checkpoint and other I/O ////////////// + +/** + * + * CHANGE (March 2008): now receiving an eoValueParam instead of an eoEvalFuncCounter. This function is just interested + * in the value of the parameter calculated on the evaluation function, not in the actual function itself!! + * + * @ingroup Builders + */ +template +eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValueParam& _eval, eoContinue& _continue) +{ + // first, create a checkpoint from the eoContinue + eoCheckPoint *checkpoint = new eoCheckPoint(_continue); + + _state.storeFunctor(checkpoint); + + //////////////////// + // Signal monitoring + //////////////////// + +#ifndef _MSC_VER + // the CtrlC monitoring interception + eoSignal *mon_ctrlCCont; + eoValueParam& mon_ctrlCParam = _parser.createParam(false, "monitor-with-CtrlC", "Monitor current generation upon Ctrl C",0, "Stopping criterion"); + if (mon_ctrlCParam.value()) + { + mon_ctrlCCont = new eoSignal; + // store + _state.storeFunctor(mon_ctrlCCont); + // add to checkpoint + checkpoint->add(*mon_ctrlCCont); + } +#endif + + /////////////////// + // Counters + ////////////////// + + // is nb Eval to be used as counter? + eoValueParam& useEvalParam = _parser.createParam(true, "useEval", "Use nb of eval. as counter (vs nb of gen.)", '\0', "Output"); + eoValueParam& useTimeParam = _parser.createParam(true, "useTime", "Display time (s) every generation", '\0', "Output"); + // if we want the time, we need an eoTimeCounter + eoTimeCounter * tCounter = NULL; + + // Create anyway a generation-counter + // Recent change (03/2002): it is now an eoIncrementorParam, both + // a parameter AND updater so you can store it into the eoState + eoIncrementorParam *generationCounter = new eoIncrementorParam("Gen."); + + // store it in the state + _state.storeFunctor(generationCounter); + + // And add it to the checkpoint, + checkpoint->add(*generationCounter); + + // dir for DISK output + 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(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); + + bool dirOK = false; // not tested yet + + ///////////////////////////////////////// + // now some statistics on the population: + ///////////////////////////////////////// + + /** + * existing stats as of today, April 10. 2001 + * + * eoBestFitnessStat : best value in pop - type EOT::Fitness + * eoAverageStat : average value in pop - type EOT::Fitness + * eoSecondMomentStat: average + stdev - type std::pair + * eoSortedPopStat : whole population - type std::string (!!) + * eoScalarFitnessStat: the fitnesses - type std::vector + */ + + // Best fitness in population + //--------------------------- + eoValueParam& printBestParam = _parser.createParam(true, "printBestStat", "Print Best/avg/stdev every gen.", '\0', "Output"); + eoValueParam& plotBestParam = _parser.createParam(false, "plotBestStat", "Plot Best/avg Stat", '\0', "Output - Graphical"); + eoValueParam& fileBestParam = _parser.createParam(false, "fileBestStat", "Output bes/avg/std to file", '\0', "Output - Disk"); + + eoBestFitnessStat *bestStat = NULL; + 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); + // check if monitoring with signal + if ( mon_ctrlCParam.value() ) + mon_ctrlCCont->add(*bestStat); + } + + // Average fitness alone + //---------------------- + eoAverageStat *averageStat = NULL; // do we need averageStat? + if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() ) // we need it for gnuplot output + { + averageStat = new eoAverageStat; + // store it + _state.storeFunctor(averageStat); + // add it to the checkpoint + checkpoint->add(*averageStat); + // check if monitoring with signal + if ( mon_ctrlCParam.value() ) + mon_ctrlCCont->add(*averageStat); + } + + // Second moment stats: average and stdev + //--------------------------------------- + eoSecondMomentStats *secondStat = NULL; + if ( printBestParam.value() || fileBestParam.value() ) // we need it for screen output or file output + { + secondStat = new eoSecondMomentStats; + // store it + _state.storeFunctor(secondStat); + // add it to the checkpoint + checkpoint->add(*secondStat); + // check if monitoring with signal + if ( mon_ctrlCParam.value() ) + mon_ctrlCCont->add(*secondStat); + } + + // Dump of the whole population + //----------------------------- + eoSortedPopStat *popStat = NULL; + eoValueParam& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output"); + + if ( printPopParam.value() ) // we do want pop dump + { + popStat = new eoSortedPopStat; + // store it + _state.storeFunctor(popStat); + // add it to the checkpoint + checkpoint->add(*popStat); + // check if monitoring with signal + if ( mon_ctrlCParam.value() ) + mon_ctrlCCont->add(*popStat); + } + + // do we wnat some histogram of fitnesses snpashots? + eoValueParam plotHistogramParam = _parser.createParam(false, "plotHisto", "Plot histogram of fitnesses", '\0', "Output - Graphical"); + + /////////////// + // The monitors + /////////////// + + // do we want an eoStdoutMonitor? + bool needStdoutMonitor = printBestParam.value() + || printPopParam.value() ; + + // The Stdout monitor will print parameters to the screen ... + if ( needStdoutMonitor ) + { + eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + _state.storeFunctor(monitor); + + // when called by the checkpoint (i.e. at every generation) + // check if monitoring with signal + if ( ! mon_ctrlCParam.value() ) + checkpoint->add(*monitor); + else + mon_ctrlCCont->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 (useTimeParam.value()) // we want time + { + tCounter = new eoTimeCounter; + _state.storeFunctor(tCounter); + // check if monitoring with signal + if ( ! mon_ctrlCParam.value() ) + checkpoint->add(*tCounter); + else + mon_ctrlCCont->add(*tCounter); + monitor->add(*tCounter); + } + + if (printBestParam.value()) + { + monitor->add(*bestStat); + monitor->add(*secondStat); + } + + if ( printPopParam.value()) + monitor->add(*popStat); + } + + // first handle the dir test - if we need at least one file + if ( ( fileBestParam.value() || plotBestParam.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 + { +#ifdef _MSVC + std::string stmp = dirNameParam.value() + "\best.xg"; +#else + std::string stmp = dirNameParam.value() + "/best.xg"; +#endif + 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); + if (tCounter) // we want the time as well + { + // std::cout << "On met timecounter\n"; + fileMonitor->add(*tCounter); + } + fileMonitor->add(*bestStat); + fileMonitor->add(*secondStat); + } + +#if defined(HAVE_GNUPLOT) + 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()) // do we want eval as X coordinate + gnuMonitor->add(_eval); + else if (tCounter) // or time? + gnuMonitor->add(*tCounter); + else // default: generation + gnuMonitor->add(*generationCounter); + gnuMonitor->add(*bestStat); + gnuMonitor->add(*averageStat); + } + + // 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); + } + +#endif + + ////////////////////////////////// + // State savers + ////////////////////////////// + + // feed the state to state savers + // save state every N generation + eoValueParam& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" ); + + if (_parser.isItThere(saveFrequencyParam)) + { + // first make sure dirName is OK + if (! dirOK ) + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + + unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX ); +#ifdef _MSVC + std::string stmp = dirNameParam.value() + "\generations"; +#else + std::string stmp = dirNameParam.value() + "/generations"; +#endif + eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp); + _state.storeFunctor(stateSaver1); + checkpoint->add(*stateSaver1); + } + + // save state every T seconds + eoValueParam& saveTimeIntervalParam = _parser.createParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" ); + if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0) + { + // first make sure dirName is OK + if (! dirOK ) + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + +#ifdef _MSVC + std::string stmp = dirNameParam.value() + "\time"; +#else + std::string stmp = dirNameParam.value() + "/time"; +#endif + eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); + _state.storeFunctor(stateSaver2); + checkpoint->add(*stateSaver2); + } + + // and that's it for the (control and) output + return *checkpoint; +} + +#endif diff --git a/deprecated/eo/src/do/make_checkpoint_FDC.h b/deprecated/eo/src/do/make_checkpoint_FDC.h new file mode 100644 index 000000000..33c7f7206 --- /dev/null +++ b/deprecated/eo/src/do/make_checkpoint_FDC.h @@ -0,0 +1,303 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_checkpoint.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_checkpoint_h +#define _make_checkpoint_h + +#include + +#include +#include // for minimizing_fitness() +#include +#include +#include + +// at the moment, in utils/make_help.cpp +// this should become some eoUtils.cpp with corresponding eoUtils.h +bool testDirRes(std::string _dirName, bool _erase); +/////////////////// The checkpoint and other I/O ////////////// + + +/** + * @ingroup Builders + */ +template +eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) +{ + // first, create a checkpoint from the eoContinue + eoCheckPoint *checkpoint = new eoCheckPoint(_continue); + _state.storeFunctor(checkpoint); + + /////////////////// + // Counters + ////////////////// + // is nb Eval to be used as counter? + eoValueParam& useEvalParam = _parser.createParam(true, "useEval", "Use nb of eval. as counter (vs nb of gen.)", '\0', "Output"); + + // Create anyway a generation-counter parameter + eoValueParam *generationCounter = new eoValueParam(0, "Gen."); + // Create an incrementor (sub-class of eoUpdater). + eoIncrementor* increment = new eoIncrementor(generationCounter->value()); + // Add it to the checkpoint, + checkpoint->add(*increment); + // and store it in the state + _state.storeFunctor(increment); + + // dir for DISK output + 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 + + ///////////////////////////////////////// + // now some statistics on the population: + ///////////////////////////////////////// + /** + * existing stats as of today, April 10. 2001 + * + * eoBestFitnessStat : best value in pop - type EOT::Fitness + * eoAverageStat : average value in pop - type EOT::Fitness + * eoSecondMomentStat: average + stdev - type std::pair + * eoSortedPopStat : whole population - type std::string (!!) + * eoScalarFitnessStat: the fitnesses - type std::vector + * eoDFCSTat : FDC wrt best in pop or absolute best - type double + * requires an eoDistance. See eoFDCStat.h + * also computes all elements for the FDC scatter plot + */ + + // Best fitness in population + //--------------------------- + eoValueParam& printBestParam = _parser.createParam(true, "printBestStat", "Print Best/avg/stdev every gen.", '\0', "Output"); + eoValueParam& plotBestParam = _parser.createParam(false, "plotBestStat", "Plot Best/avg Stat", '\0', "Output - Graphical"); + eoValueParam& fileBestParam = _parser.createParam(false, "fileBestStat", "Output bes/avg/std to file", '\0', "Output - Disk"); + + eoBestFitnessStat *bestStat = NULL; + 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); + } + + // Average fitness alone + //---------------------- + 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); + } + + // Second moment stats: average and stdev + //--------------------------------------- + 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); + } + + + // Dump of the whole population + //----------------------------- + eoSortedPopStat *popStat = NULL; + 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); + } + + + // the Fitness Distance Correlation + //--------------------------------- + eoValueParam& printFDCParam = _parser.createParam(true, "printFDC", "Print FDC coeff. every gen.", '\0', "Output"); + eoValueParam& plotFDCParam = _parser.createParam(false, "plotFDCStat", "Plot FDC scatter plot", '\0', "Output - Graphical"); + + 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); + } + + // do we wnat some histogram of fitnesses snpashots? + eoValueParam plotHistogramParam = _parser.createParam(false, "plotHisto", "Plot histogram of fitnesses", '\0', "Output - Graphical"); + + /////////////// + // The monitors + /////////////// + // do we want an eoStdoutMonitor? + bool needStdoutMonitor = printBestParam.value() || printFDCParam.value() + || printPopParam.value() ; + + // The Stdout monitor will print parameters to the screen ... + if ( needStdoutMonitor ) + { + eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + _state.storeFunctor(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); + } + + // 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 + 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); + } + + 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); + } + + 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); + + // 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); + } + + ////////////////////////////////// + // State savers + ////////////////////////////// + + // feed the state to state savers + // save state every N generation + eoValueParam& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" ); + + if (_parser.isItThere(saveFrequencyParam)) + { + // first make sure dirName is OK + if (! dirOK ) + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + + unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX ); + std::string stmp = dirNameParam.value() + "/generations"; + eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp); + _state.storeFunctor(stateSaver1); + checkpoint->add(*stateSaver1); + } + + // save state every T seconds + eoValueParam& saveTimeIntervalParam = _parser.createParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" ); + if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0) + { + // first make sure dirName is OK + if (! dirOK ) + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + + std::string stmp = dirNameParam.value() + "/time"; + eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); + _state.storeFunctor(stateSaver2); + checkpoint->add(*stateSaver2); + } + + // and that's it for the (control and) output + return *checkpoint; +} + +#endif diff --git a/deprecated/eo/src/do/make_checkpoint_assembled.h b/deprecated/eo/src/do/make_checkpoint_assembled.h new file mode 100644 index 000000000..26463fab3 --- /dev/null +++ b/deprecated/eo/src/do/make_checkpoint_assembled.h @@ -0,0 +1,212 @@ + /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- */ + +//----------------------------------------------------------------------------- +// make_checkpoint_assembled.h +// Marc Wintermantel & Oliver Koenig +// IMES-ST@ETHZ.CH +// March 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 + 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 +*/ +//----------------------------------------------------------------------------- + +#ifndef _make_checkpoint_assembled_h +#define _make_checkpoint_assembled_h + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include +#include +#include +#include +#include + +// at the moment, in utils/make_help.cpp +// this should become some eoUtils.cpp with corresponding eoUtils.h +bool testDirRes(std::string _dirName, bool _erase); +/////////////////// The checkpoint and other I/O ////////////// + +/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! + * + * + * @ingroup Builders + * */ +template +eoCheckPoint& do_make_checkpoint_assembled(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) +{ + + // SOME PARSER PARAMETERS + // ---------------------- + std::string dirName = _parser.getORcreateParam(std::string("Res"), "resDir", + "Directory to store DISK outputs", + '\0', "Output").value(); + bool erase = _parser.getORcreateParam(true, "eraseDir", + "Erase files in dirName if any", + '\0', "Output").value(); + bool gnuplots = _parser.getORcreateParam(true, "plots", + "Plot stuff using GnuPlot", + '\0', "Output").value(); + bool printFile = _parser.getORcreateParam(true, "printFile", + "Print statistics file", + '\0', "Output").value(); + + eoValueParam& saveFrequencyParam + = _parser.getORcreateParam(unsigned(0), "saveFrequency", + "Save every F generation (0 = only final state, absent = never)", + '\0', "Persistence" ); + + testDirRes(dirName, erase); // TRUE + + // CREATE CHECKPOINT FROM eoContinue + // --------------------------------- + eoCheckPoint *checkpoint = new eoCheckPoint(_continue); + _state.storeFunctor(checkpoint); + + // GENERATIONS + // ----------- + eoIncrementorParam *generationCounter = new eoIncrementorParam("Gen."); + _state.storeFunctor(generationCounter); + checkpoint->add(*generationCounter); + + // TIME + // ---- + eoTimeCounter * tCounter = NULL; + tCounter = new eoTimeCounter; + _state.storeFunctor(tCounter); + checkpoint->add(*tCounter); + + // ACCESS DESCRIPTIONS OF TERMS OF FITNESS CLASS + // --------------------------------------------- + // define a temporary fitness instance + typedef typename EOT::Fitness Fit; + Fit fit; + std::vector fitness_descriptions = fit.getDescriptionVector(); + unsigned nTerms = fitness_descriptions.size(); + + // STAT VALUES OF A POPULATION + // --------------------------- + + // average vals + std::vector* > avgvals( nTerms ); + for (unsigned i=0; i < nTerms; ++i){ + std::string descr = "Avg. of " + fitness_descriptions[i]; + avgvals[i] = new eoAssembledFitnessAverageStat(i, descr); + _state.storeFunctor( avgvals[i] ); + checkpoint->add( *avgvals[i] ); + } + + // best vals + std::vector* > bestvals( nTerms ); + for (unsigned j=0; j < nTerms; ++j){ + std::string descr = fitness_descriptions[j] + " of best ind."; + bestvals[j] = new eoAssembledFitnessBestStat(j, descr); + _state.storeFunctor( bestvals[j] ); + checkpoint->add( *bestvals[j] ); + } + + // STDOUT + // ------ + eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + _state.storeFunctor(monitor); + checkpoint->add(*monitor); + monitor->add(*generationCounter); + monitor->add(_eval); + monitor->add(*tCounter); + + // Add best fitness + monitor->add( *bestvals[0] ); + + // Add all average vals + for (unsigned l=0; l < nTerms; ++l) + monitor->add( *avgvals[l] ); + + // GNUPLOT + // ------- + if (gnuplots ){ + std::string stmp; + + // Histogramm of the different fitness vals + eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; + _state.storeFunctor(fitStat); + checkpoint->add(*fitStat); +#ifdef HAVE_GNUPLOT + // 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 + fitSnapshot->add(*fitStat); + // and of course add it to the checkpoint + checkpoint->add(*fitSnapshot); + + std::vector gnumonitors(nTerms, NULL ); + for (unsigned k=0; k < nTerms; ++k){ + stmp = dirName + "/gnuplot_" + fitness_descriptions[k] + ".xg"; + gnumonitors[k] = new eoGnuplot1DMonitor(stmp,true); + _state.storeFunctor(gnumonitors[k]); + checkpoint->add(*gnumonitors[k]); + gnumonitors[k]->add(*generationCounter); + gnumonitors[k]->add(*bestvals[k]); + gnumonitors[k]->add(*avgvals[k]); + } +#endif + } + + // WRITE STUFF TO FILE + // ------------------- + if( printFile ){ + std::string stmp2 = dirName + "/eoStatistics.sav"; + eoFileMonitor *fileMonitor = new eoFileMonitor(stmp2); + _state.storeFunctor(fileMonitor); + checkpoint->add(*fileMonitor); + fileMonitor->add(*generationCounter); + fileMonitor->add(_eval); + fileMonitor->add(*tCounter); + + for (unsigned i=0; i < nTerms; ++i){ + fileMonitor->add(*bestvals[i]); + fileMonitor->add(*avgvals[i]); + } + + } + + // STATE SAVER + // ----------- + // feed the state to state savers + + if (_parser.isItThere(saveFrequencyParam)) { + + unsigned freq = (saveFrequencyParam.value() > 0 ? saveFrequencyParam.value() : UINT_MAX ); + std::string stmp = dirName + "/generations"; + eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp); + _state.storeFunctor(stateSaver1); + checkpoint->add(*stateSaver1); + } + + // and that's it for the (control and) output + return *checkpoint; +} + +#endif diff --git a/deprecated/eo/src/do/make_continue.h b/deprecated/eo/src/do/make_continue.h new file mode 100644 index 000000000..27b4e9450 --- /dev/null +++ b/deprecated/eo/src/do/make_continue.h @@ -0,0 +1,167 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_continue.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_continue_h +#define _make_continue_h + +/* +Contains the templatized version of parser-based choice of stopping criterion +It can then be instantiated, and compiled on its own for a given EOType +(see e.g. in dir ga, ga.cpp) +*/ + +// Continuators - all include eoContinue.h +#include +#include +#include +#include +#include +#ifndef _MSC_VER +#include // CtrlC handling (using 2 global variables!) +#endif + + // also need the parser and param includes +#include +#include + + +/////////////////// the stopping criterion //////////////// + /** + * @ingroup Builders + */ +template +eoCombinedContinue * make_combinedContinue(eoCombinedContinue *_combined, eoContinue *_cont) +{ + if (_combined) // already exists + _combined->add(*_cont); + else + _combined = new eoCombinedContinue(*_cont); + return _combined; +} + +/** + * + * @ingroup Builders + */ +template +eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval) +{ + //////////// Stopping criterion /////////////////// + // the combined continue - to be filled + eoCombinedContinue *continuator = NULL; + + // for each possible criterion, check if wanted, otherwise do nothing + + // First the eoGenContinue - need a default value so you can run blind + // but we also need to be able to avoid it <--> 0 + eoValueParam& maxGenParam = _parser.getORcreateParam(unsigned(100), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion"); + + 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); + } + + // the steadyGen continue - only if user imput + eoValueParam& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion"); + 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); + } + + // Same thing with Eval - but here default value is 0 + eoValueParam& maxEvalParam + = _parser.getORcreateParam((unsigned long)0, "maxEval", + "Maximum number of evaluations (0 = none)", + 'E', "Stopping criterion"); + + 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); + } + /* + // the steadyEval continue - only if user imput + eoValueParam& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion"); + 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); + } + */ + // the target fitness + eoFitContinue *fitCont; + 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); + } + +#ifndef _MSC_VER + // the CtrlC interception (Linux only I'm afraid) + eoCtrlCContinue *ctrlCCont; + 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); + } +#endif + + // now check that there is at least one! + if (!continuator) + throw std::runtime_error("You MUST provide a stopping criterion"); + // OK, it's there: store in the eoState + _state.storeFunctor(continuator); + + // and return + return *continuator; +} + +#endif diff --git a/deprecated/eo/src/do/make_general_replacement.h b/deprecated/eo/src/do/make_general_replacement.h new file mode 100644 index 000000000..1d42345c8 --- /dev/null +++ b/deprecated/eo/src/do/make_general_replacement.h @@ -0,0 +1,184 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_general_replacement_h +#define _make_general_replacement_h + +#include // for eo_is_a_rate + +// Replacement +#include + +// also need the parser and param includes +#include +#include + + +/** a helper function that decodes a parameter read by the parser into an + * eoReduce & (allocates the pointer and stores it into an eoState) + * + * @ingroup Builders + */ +template +eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) +{ + unsigned int detSize; + eoReduce * ptReduce; + + // ---------- Deterministic + if ( (_ppReduce.first == std::string("Deterministic")) || + (_ppReduce.first == std::string("Sequential")) + ) + { + ptReduce = new eoTruncate; + } + // ---------- EP + else if (_ppReduce.first == std::string("EP")) + { + if (!_ppReduce.second.size()) // no parameter added + { + std::cerr << "WARNING, no parameter passed to EP, using 6" << std::endl; + detSize = 6; + // 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) + detSize = atoi(_ppReduce.second[0].c_str()); + ptReduce = new eoEPReduce(detSize); + } + // ---------- DetTour + else if (_ppReduce.first == std::string("DetTour")) + { + 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")); + } + else // parameter passed by user as DetTour(T) + detSize = atoi(_ppReduce.second[0].c_str()); + ptReduce = new eoDetTournamentTruncate(detSize); + } + else if (_ppReduce.first == std::string("StochTour")) + { + 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]"); + } + + ptReduce = new eoStochTournamentTruncate(p); + } + else if ( (_ppReduce.first == std::string("Uniform")) || + (_ppReduce.first == std::string("Random")) + ) + { + ptReduce = new eoRandomReduce; + } + else // no known reduction entered + { + throw std::runtime_error("Unknown reducer: " + _ppReduce.first); + } + // all done, stores and return a reference + _state.storeFunctor(ptReduce); + return (*ptReduce); +} + +/** 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 + * strong = elite parents survive, whatever the offspring + * weak - elite patents compete AFTER replacement with best offspring + * eoHowMany _surviveParents number of parents after parents recuction + * eoParamParamType & _reduceParentType how the parents are reduced + * eoHowMany _surviveOffspring number of offspring after offspring recuction + * eoParamParamType & _reduceOffspringType how the offspring are reduced + * eoParamParamType & _reduceFinalType how the final population is reduced to initial population size + * + * @ingroup Builders + */ +template +eoReplacement & make_general_replacement( + 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 + ///////////////////////////////////////////////////// + + // Elitism + eoHowMany elite = _parser.createParam(_elite, "elite", "Nb of elite parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); + + bool strongElitism = _parser.createParam(_strongElitism,"eliteType", "Strong (true) or weak (false) elitism (set elite to 0 for none)", '\0', "Evolution Engine / Replacement").value(); + + // 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); + + eoParamParamType & reduceFinalType = _parser.createParam(_reduceFinalType, "reduceFinal", "Final reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value(); + + eoReduce & reduceFinal = decode_reduce(reduceFinalType, _state); + + // now the replacement itself + eoReduceMergeReduce *ptReplace = new eoReduceMergeReduce(elite, strongElitism, surviveParents, reduceParent, surviveOffspring, reduceOffspring, reduceFinal); + _state.storeFunctor(ptReplace); + + // that's it! + return *ptReplace; +} + +#endif diff --git a/deprecated/eo/src/do/make_pop.h b/deprecated/eo/src/do/make_pop.h new file mode 100644 index 000000000..c2a1d1a84 --- /dev/null +++ b/deprecated/eo/src/do/make_pop.h @@ -0,0 +1,116 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_pop.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_pop_h +#define _make_pop_h + +#include // for time(0) for random seeding +#include +#include +#include +#include +#include + +/** @defgroup Builders Automatic builders + * + * Automatic builders are functions that automagically builds most commons instances for you. + * + * All the options you needs are set in the command-line parser. + * Those functions all start with the "do_make_" prefix. + * + * @ingroup Utilities + */ + +/** + * Templatized version of parser-based construct of the population + * + other initializations that are NOT representation-dependent. + * + * It must then be instantiated, and compiled on its own for a given EOType + * (see e.g. ga.h and ga.pp in dir ga) + * + * @ingroup Builders +*/ +template +eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _init) +{ + // random seed + eoValueParam& seedParam = _parser.getORcreateParam(uint32_t(0), "seed", "Random number seed", 'S'); + if (seedParam.value() == 0) + seedParam.value() = time(0); + eoValueParam& popSize = _parser.getORcreateParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine"); + + // Either load or initialize + // create an empty pop and let the state handle the memory + eoPop& pop = _state.takeOwnership(eoPop()); + + eoValueParam& loadNameParam = _parser.getORcreateParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); + eoValueParam & recomputeFitnessParam = _parser.getORcreateParam(false, "recomputeFitness", "Recompute the fitness after re-loading the pop.?", 'r', "Persistence" ); + + if (loadNameParam.value() != "") // something to load + { + // create another state for reading + eoState inState; // a state for loading - WITHOUT the parser + // register the rng and the pop in the state, so they can be loaded, + // and the present run will be the exact continuation of the saved run + // eventually with different parameters + inState.registerObject(pop); + inState.registerObject(rng); + inState.load(loadNameParam.value()); // load the pop and the rng + // 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()); + } + } + else // nothing loaded from a file + { + rng.reseed(seedParam.value()); + } + + if (pop.size() < popSize.value()) // missing some guys + { + // Init pop from the randomizer: need to use the append function + pop.append(popSize.value(), _init); + } + + // for future stateSave, register the algorithm into the state + _state.registerObject(_parser); + _state.registerObject(pop); + _state.registerObject(rng); + + return pop; +} + +#endif diff --git a/deprecated/eo/src/do/make_run.h b/deprecated/eo/src/do/make_run.h new file mode 100644 index 000000000..485cb8700 --- /dev/null +++ b/deprecated/eo/src/do/make_run.h @@ -0,0 +1,46 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_run_h +#define _make_run_h + +// Algorithm (only this one needed) +#include + +/* + * A trivial function - only here to allow instanciation with a give EOType + * and separate compilation - see in ga dir, make_run_ga + * + * + * @ingroup Builders +*/ +template +void do_run(eoAlgo& _algo, eoPop& _pop) +{ + _algo(_pop); +} + +#endif diff --git a/deprecated/eo/src/eo b/deprecated/eo/src/eo new file mode 100644 index 000000000..8cebd23a0 --- /dev/null +++ b/deprecated/eo/src/eo @@ -0,0 +1,209 @@ +//----------------------------------------------------------------------------- +// eo +// (c) GeNeura Team 1998 - 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 + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#ifndef _eo_ +#define _eo_ + +#ifdef HAVE_CONFIG_H +#include +#endif + +// general purpose +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +// eo's +#include + +#include + +#include +#include +#include + +// the variation operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include +// didactic (mimics SGA-like variation into an eoGenOp) +// calls crossover and mutation sequentially, +// with their respective mutation rates +#include +// its dual: crossover, mutation (and copy) - proportional choice +// w.r.t. given relative weights +#include + +// population +#include + +// Evaluation functions (all include eoEvalFunc.h) +#include +#include +#include +#include +#include + +// Continuators - all include eoContinue.h +#include +#include +#include +#include +#include +#include +#include // added th T.Legrand +#ifndef _MSC_VER +#include // CtrlC handling (using 2 global variables!) +#endif +// Selection +// the eoSelectOne's +#include +#include +#include +#include +#include // also contains eoLinearFitScaling.h +#include +#include +#include +// Embedding truncation selection +#include + +// the batch selection - from an eoSelectOne +#include +#include +#include +#include + +// other batch selections +// DetSelect can also be obtained as eoSequentialSelect, an eoSelectOne +// (using setup and an index) +#include + +// Breeders +#include // applies one eoGenOp, stop on offspring count +// #include // parent + SINGLE offspring compete (e.g. DE) - not ready yet... + +// Replacement +// #include +#include +#include +#include + +// a simple transformer +#include + +// Perf2Worth stuff - includes eoSelectFromWorth.h +#include + + +// Algorithms +#include +#include +// #include removed for a while - until eoGenOp is done + +// Utils +#include +#include // includes eoRealBounds.h +#include // no eoIntVectorBounds + +// aliens +#include +#include + + +//----------------------------------------------------------------------------- +// to be continued ... +//----------------------------------------------------------------------------- + +/*** Particle Swarm Optimization stuff ***/ + +// basic particle definitions +#include +#include +#include +#include + +// initialization +#include +#include + +// velocities +#include +#include +#include +#include +#include +#include +#include +#include + +// flights +#include +#include +#include +#include +#include + +// topologies +#include +#include +#include +#include +#include +#include + +// PS algorithms +#include +#include +#include + +// utils +#include +#include +#include +#include +#include + +#include +#include + +#endif + +// Local Variables: +// mode: C++ +// End: diff --git a/deprecated/eo/src/eoAlgo.h b/deprecated/eo/src/eoAlgo.h new file mode 100644 index 000000000..494b7b76c --- /dev/null +++ b/deprecated/eo/src/eoAlgo.h @@ -0,0 +1,56 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAlgo.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOALGO_H +#define _EOALGO_H + +#include // for population +#include + +/** + @defgroup Algorithms Algorithms + + In EO, an algorithm is a functor that takes one or several solutions to an optimization + problem as arguments, and iteratively modify them with the help of operators. + + Generally, an EO object is built by assembling together @ref Operators in an algorithm instance, + and then calling the algorithm's operator() on an initial population (an eoPop). The algorithm will then + manipulate the solutions within the population to search for the problem's optimum. +*/ + +/** + This is the base class for population-transforming algorithms. There + is only one operator defined, which takes a population and does stuff to + it. It needn't be a complete algorithm, can be also a step of an + algorithm. This class just gives a common interface to linear + population-transforming algorithms. + + @ingroup Algorithms +*/ +template< class EOT > +class eoAlgo : public eoUF&, void> +{}; + + +#endif diff --git a/deprecated/eo/src/eoBinaryFlight.h b/deprecated/eo/src/eoBinaryFlight.h new file mode 100644 index 000000000..9672bd3f3 --- /dev/null +++ b/deprecated/eo/src/eoBinaryFlight.h @@ -0,0 +1,44 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoBinaryFlight.h +// (c) OPAC Team, 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOBINARYFLIGHT_H +#define EOBINARYFLIGHT_H + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + + + +/** Abstract class for binary flight of particle swarms. Positions are updated but are expected to be binary. + * A function must be used to decide, according to continuous velocities, of the + * new positions (0,1 ... ?) + * + * @ingroup Core + */ +template < class POT > class eoBinaryFlight:public eoFlight < POT >{}; + + + +#endif /*EOBINARYFLIGHT_H */ diff --git a/deprecated/eo/src/eoBitParticle.h b/deprecated/eo/src/eoBitParticle.h new file mode 100644 index 000000000..87f98aa1b --- /dev/null +++ b/deprecated/eo/src/eoBitParticle.h @@ -0,0 +1,50 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoBitParticle.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOBITPARTICLE_H +#define _EOBITPARTICLE_H + + +#include + + +/** eoBitParticle: Implementation of a bit-coded particle (swarm optimization). + * Positions and best positions are 0 or 1 but the velocity is a vector of double. + * + * @ingroup Bitstring +*/ +template < class FitT> class eoBitParticle: public eoVectorParticle + +{ +public: + + eoBitParticle(unsigned size = 0, bool positions = 0,double velocities = 0.0,bool bestPositions = 0): eoVectorParticle (size, positions,velocities,bestPositions) {} + + virtual std::string className() const + { + return "eoBitParticle"; + } +}; + +#endif /*_EOBITPARTICLE_H*/ diff --git a/deprecated/eo/src/eoBreed.h b/deprecated/eo/src/eoBreed.h new file mode 100644 index 000000000..0b00ec584 --- /dev/null +++ b/deprecated/eo/src/eoBreed.h @@ -0,0 +1,79 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoBreed.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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoBreed_h +#define _eoBreed_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** Breeding: combination of selecting and transforming a population + +Breeding is thought of a combination of selecting and transforming a +population. For efficiency reasons you might want to build your own +eoBreed derived class rather than relying on a seperate select and +transform function. + +@see eoSelect, eoTransform, eoSelectTransform + +@ingroup Combination +*/ +template +class eoBreed : public eoBF&, eoPop&, void> +{}; + + + +/** Embedded select, followed by an embedded transform + +Special breeder that is just an application of an embedded select, +followed by an embedded transform + +@ingroup Combination +*/ +template +class eoSelectTransform : public eoBreed +{ + public: + eoSelectTransform(eoSelect& _select, eoTransform& _transform) : + select(_select), transform(_transform) + {} + + void operator()(const eoPop& _parents, eoPop& _offspring) + { + select(_parents, _offspring); + transform(_offspring); + } + + private : + eoSelect& select; + eoTransform& transform; +}; + +#endif diff --git a/deprecated/eo/src/eoCellularEasyEA.h b/deprecated/eo/src/eoCellularEasyEA.h new file mode 100644 index 000000000..fbf3085fc --- /dev/null +++ b/deprecated/eo/src/eoCellularEasyEA.h @@ -0,0 +1,162 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +// "eoCellularEasyEA.h" + +// (c) OPAC Team, LIFL, 2002 + +/* This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: cahon@lifl.fr +*/ + +#ifndef eoCellularEasyEA_h +#define eoCellularEasyEA_h + +#include +#include +#include +#include +#include +#include + +/** + 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 ? */ + ) : + cont (_cont), + eval (_eval), + popEval (_eval), + sel_neigh (_sel_neigh), + cross (_cross), + 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 + ) : + cont (_cont), + eval (_eval), + popEval (_eval), + sel_neigh (_sel_neigh), + cross (_cross), + mut (_mut), + sel_child (_sel_child), + sel_repl (_sel_repl) { + + } + + /** + For a given population. + */ + + 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) ; + + // To perform mutation + mut (pop [i]) ; + mut (part) ; + + 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 ; + eoSelectOne & sel_neigh ; + eoBF & cross ; + eoMonOp & mut ; + eoSelectOne & sel_child ; + eoSelectOne & sel_repl ; + + class eoSelectFirstOne : public eoSelectOne { + + public : + + const EOT & operator () (const eoPop & pop) { + + return pop [0] ; + } + + } ; + +} ; + +#endif diff --git a/deprecated/eo/src/eoCloneOps.h b/deprecated/eo/src/eoCloneOps.h new file mode 100644 index 000000000..e53cbd749 --- /dev/null +++ b/deprecated/eo/src/eoCloneOps.h @@ -0,0 +1,82 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +//----------------------------------------------------------------------------- +// 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 + 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 + 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 $ + */ +//----------------------------------------------------------------------------- + +#ifndef _eoCloneOps_H +#define _eoCloneOps_H + +#include + +/** + * The different null-variation operators (i.e. they do nothing) + * + * 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 :-) + * + * @addtogroup Core + * @{ + */ + +/** +Mon clone: one argument +*/ +template +class eoMonCloneOp: public eoMonOp +{ +public: + /// Ctor + eoMonCloneOp() : eoMonOp() {} + virtual std::string className() const {return "eoMonCloneOp";} + virtual bool operator()(EOT&){return false;} +}; + + +/** Binary clone: two operands, only the first could be modified + */ +template +class eoBinCloneOp: public eoBinOp +{ +public: + /// Ctor + eoBinCloneOp() : eoBinOp() {} + virtual std::string className() const {return "eoBinCloneOp";} + virtual bool operator()(EOT&, const EOT&){return false;} +}; + +/** Quad clone: two operands, both could be modified - but are not! +*/ +template +class eoQuadCloneOp: public eoQuadOp +{ +public: + /// Ctor + eoQuadCloneOp():eoQuadOp() {} + virtual std::string className() const {return "eoQuadCloneOp";} +virtual bool operator()(EOT& , EOT& ) {return false;} +}; + +#endif +/** @} */ diff --git a/deprecated/eo/src/eoCombinedContinue.h b/deprecated/eo/src/eoCombinedContinue.h new file mode 100644 index 000000000..dfb70f67b --- /dev/null +++ b/deprecated/eo/src/eoCombinedContinue.h @@ -0,0 +1,102 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 +Authors : + todos@geneura.ugr.es + Marc Schoenauer + Ramn Casero Caas + Johann Dro + */ +//----------------------------------------------------------------------------- + +#ifndef _eoCombinedContinue_h +#define _eoCombinedContinue_h + +#include + +/** + Combined continuators - logical AND: + Continues until one of the embedded continuators says halt! + +20/11/00 MS: Changed the 2-continuator construct to a std::vector > + to be consistent with other Combined constructs + and allow to easily handle more than 2 continuators + +02/2003 Ramn Casero Caas - added the removeLast() method + +@ingroup Combination +*/ +template< class EOT> +class eoCombinedContinue: public eoContinue, public std::vector* > { +public: + + /// Define Fitness + typedef typename EOT::Fitness FitnessType; + + /// Ctor, make sure that at least on continuator is present + eoCombinedContinue( eoContinue& _cont) + : eoContinue(), std::vector* >(1, &_cont) + { + } + + /// Ctor - for historical reasons ... should disspear some day + eoCombinedContinue( eoContinue& _cont1, eoContinue& _cont2) + : eoContinue(), std::vector* >() + { +#ifndef DEPRECATED_MESSAGES +#pragma message "The double continuators constructor of eocombinedContinue is deprecated and will be removed in the next release." +#endif // !DEPRECATED_MESSAGES + + this->push_back(&_cont1); + this->push_back(&_cont2); + } + + void add(eoContinue & _cont) + { + this->push_back(&_cont); + } + + void removeLast(void) + { +#ifndef DEPRECATED_MESSAGES +#pragma message "The removeLast method of eocombinedContinue is deprecated and will be removed in the next release, use pop_back instead." +#endif // !DEPRECATED_MESSAGES + + this->pop_back(); + } + + + /** Returns false when one of the embedded continuators say so (logical and) + */ + virtual bool operator() ( const eoPop& _pop ) + { + for (unsigned i = 0; i < this->size(); ++i) + if ( ! (*this->at(i))(_pop) ) return false; + return true; + } + + virtual std::string className(void) const { return "eoCombinedContinue"; } + +//private: +// std::vector*> continuators; +}; + +#endif diff --git a/deprecated/eo/src/eoCombinedInit.h b/deprecated/eo/src/eoCombinedInit.h new file mode 100644 index 000000000..d41122d85 --- /dev/null +++ b/deprecated/eo/src/eoCombinedInit.h @@ -0,0 +1,92 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoCombinedInit_h +#define _eoCombinedInit_h + +#include + +/** + Combined INIT: a proportional recombination of eoInit objects + + @ingroup Initializators +*/ +template< class EOT> +class eoCombinedInit: public eoInit { +public: + + /** Ctor, make sure that at least one eoInit is present */ + eoCombinedInit( eoInit& _init, double _rate) + : eoInit () + { + initializers.push_back(&_init); + rates.push_back(_rate); + } + + void add(eoInit & _init, double _rate, bool _verbose) + { + 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) + { + initializers.push_back(&_init); + rates.push_back(_rate); + // compute the relative rates in percent - to warn the user! + printOn( eo::log << eo::logging ); + } + + /** outputs the operators and percentages */ + virtual void printOn(std::ostream & _os) + { + double total = 0; + unsigned i; + for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %\n"; + } + + /** Performs the init: chooses among all initializers + * using roulette wheel on the rates + */ + virtual void operator() ( EOT & _eo ) + { + unsigned what = rng.roulette_wheel(rates); // choose one op + (*initializers[what])(_eo); // apply it + return; + } + + virtual std::string className(void) const { return "eoCombinedInit"; } + +private: +std::vector*> initializers; +std::vector rates; +}; + +#endif diff --git a/deprecated/eo/src/eoConstrictedVariableWeightVelocity.h b/deprecated/eo/src/eoConstrictedVariableWeightVelocity.h new file mode 100644 index 000000000..9e96d7ef3 --- /dev/null +++ b/deprecated/eo/src/eoConstrictedVariableWeightVelocity.h @@ -0,0 +1,209 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoConstrictedVariableWeightVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H +#define EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + + +/** Inertia variable + constriction velocity for particle swarm optimization. Derivated from abstract eoVelocity, +* At step t: v(t+1)= K * ( w*v(t) + c1*r1* (xbest(t)-x(t)) + c2*r2* (gbest(t) - x(t))) +* w is updated each time the velocity performer is called and K is fixed +* (ci given and Ri chosen at random in [0;1]). +* +* @ingroup Variators +*/ +template < class POT > class eoConstrictedVariableWeightVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** Full constructor: Bounds and bound modifier required + * @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. + * 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 + */ + eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology, + const VelocityType & _coeff, + eoWeightUpdater & _weightUpdater, + const VelocityType & _c1, + const VelocityType & _c2 , + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + coeff(_coeff), + weightUpdater(_weightUpdater), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** Constructor: No bound updater required <-> fixed bounds + * @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. + * 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 + */ + eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology, + const VelocityType & _coeff, + eoWeightUpdater & _weightUpdater, + const VelocityType & _c1, + const VelocityType & _c2, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + coeff(_coeff), + weightUpdater(_weightUpdater), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _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 _gen - The eo random generator, default=rng + */ + eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology, + const VelocityType & _coeff, + eoWeightUpdater & _weightUpdater, + const VelocityType & _c1, + const VelocityType & _c2, + eoRng & _gen = rng): + topology(_topology), + coeff(_coeff), + weightUpdater(_weightUpdater), + c1 (_c1), + c2 (_c2), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen) + {} + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * 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) + * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r1; + VelocityType r2; + + VelocityType newVelocity; + + // cast the learning factors to VelocityType + r1 = (VelocityType) rng.uniform (1) * c1; + r2 = (VelocityType) rng.uniform (1) * c2; + + // need to resize the bounds even if there are dummy because of "isBounded" call + bounds.adjust_size(_po.size()); + + // update the inertia weight + weightUpdater(weight); + + // assign the new velocities + for (unsigned j = 0; j < _po.size (); j++) + { + newVelocity= coeff * (weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j])); + + /* modify the bounds */ + bndsModifier(bounds,j); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + + +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 + + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + VelocityType weight; + 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/deprecated/eo/src/eoConstrictedVelocity.h b/deprecated/eo/src/eoConstrictedVelocity.h new file mode 100644 index 000000000..45f6e03d6 --- /dev/null +++ b/deprecated/eo/src/eoConstrictedVelocity.h @@ -0,0 +1,199 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoConstrictedVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOCONSTRICTEDVELOCITY_H +#define EOCONSTRICTEDVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + +/** Constricted velocity performer for particle swarm optimization. Derivated from abstract eoVelocity, +* At step t+1 : v(t+1)= C * [ v(t) + c1*r1 * (xbest(t)-x(t)) + c2*r2 * (gbest(t) - x(t)) ] +* C is fixed for all the particles and all the generations. +* Default C = 2 * k / abs(2 - P - sqrt (P*(P-4))) +* (ci and C given;P=c1*r1 + c2*r2 ; Ri chosen at random * in [0;1]) +* +* @ingroup Variators +*/ +template < class POT > class eoConstrictedVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** 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. + * 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 + */ + eoConstrictedVelocity (eoTopology < POT > & _topology, + const VelocityType & _coeff, + const VelocityType & _c1, + const VelocityType & _c2 , + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + coeff(_coeff), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** 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. + * 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 + */ + eoConstrictedVelocity (eoTopology < POT > & _topology, + const VelocityType & _coeff, + const VelocityType & _c1, + const VelocityType & _c2, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + coeff(_coeff), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _gen - The eo random generator, default=rng + */ + eoConstrictedVelocity (eoTopology < POT > & _topology, + const VelocityType & _coeff, + const VelocityType & _c1, + const VelocityType & _c2, + eoRng & _gen = rng): + topology(_topology), + coeff(_coeff), + c1 (_c1), + c2 (_c2), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * 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) + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r1; + VelocityType r2; + + VelocityType newVelocity; + + // cast the learning factors to VelocityType + r1 = (VelocityType) rng.uniform (1) * c1; + r2 = (VelocityType) rng.uniform (1) * c2; + + // 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= coeff * (_po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j])); + + /* modify the bounds */ + bndsModifier(bounds,j); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood of a particle. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + //! 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 & coeff; // the fixed constriction coefficient + eoRng & gen; // the random generator + + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + // If the bound modifier doesn't need to be used, use the dummy instance + eoDummyRealBoundModifier dummyModifier; +}; + + +#endif /*EOCONSTRICTEDVELOCITY_H */ diff --git a/deprecated/eo/src/eoContinue.h b/deprecated/eo/src/eoContinue.h new file mode 100644 index 000000000..dbbf24805 --- /dev/null +++ b/deprecated/eo/src/eoContinue.h @@ -0,0 +1,70 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoContinue_h +#define _eoContinue_h + +#include +#include +#include + +/** @defgroup Continuators Stopping criteria + * + * 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 + */ + +/** Termination condition for the genetic algorithm + * Takes the population as input, returns true for continue, + * false for termination + * + * @ingroup Continuators + * @ingroup Core + */ +template< class EOT> +class eoContinue : public eoUF&, bool>, public eoPersistent +{ +public: + virtual std::string className(void) const { return "eoContinue"; } + + /** Read from a stream + * @param __is istream to read from + */ + void readFrom (std :: istream & __is) { + (void)__is; + /* It should be implemented by subclasses ! */ + } + + /** Print on a stream + * @param __os ostream to print on + */ + void printOn (std :: ostream & __os) const { + (void)__os; + /* It should be implemented by subclasses ! */ + } +}; + +#endif diff --git a/deprecated/eo/src/eoCounter.h b/deprecated/eo/src/eoCounter.h new file mode 100644 index 000000000..afd7fd2ee --- /dev/null +++ b/deprecated/eo/src/eoCounter.h @@ -0,0 +1,221 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 _eoCounter_h +#define _eoCounter_h + +#include +#include +#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. + + It is derived from eoValueParam so you can add it to a monitor. + + @ingroup Utilities +*/ +template +class eoProcedureCounter : public Procedure, public eoValueParam +{ + public: + + 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. + + 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 + 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 Procedure::result_type operator()(void) + { + value()++; +#ifdef _MSC_VER + proc(); +#else + return proc(); +#endif + } + + private : + + Procedure& proc; +}; + +/** + 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 + number of evaluations, just define: + + eoUnaryFunctorCounter evalCounter(myeval); + + and use evalCounter now instead of myeval. +*/ + +template +class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam +{ + public: + 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. + + 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 + 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 UnaryFunctor::result_type operator() + (typename UnaryFunctor::first_argument_type _arg1) + { + value()++; +#ifdef _MSC_VER + func(_arg1); +#else + return func(_arg1); +#endif + } + + private : + + UnaryFunctor& func; +}; + +/** + Generic counter class that counts the number of times + a binary function is used. Add a binary function through its ctor and + use this class instead of it. + + It is derived from eoValueParam so you can add it to a monitor. + +*/ +template +class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam +{ + public: + 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. + + 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 + 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::second_argument_type _arg2) + { + value()++; +#ifdef _MSC_VER + func(_arg1, _arg2); +#else + return func(_arg1, _arg2); +#endif + } + + private : + + BinaryFunctor& func; +}; + +/** make_counter: overloaded function to make a counter out of a function + + how it works... + + by using the xxx_function_tag structure defined in eoFunctionBase, you + can easily create a counter from a general class (say eoEval), by + simply stating: + + eoEval& myCounted = make_counter(functor_category(myEval), myEval, store) + + @see eoFunctorBase, functor_category, eoFunctorStore + +*/ +template +eoProcedureCounter& make_counter(eoFunctorBase::procedure_tag, Procedure& _proc, eoFunctorStore& store, std::string _name = "proc_counter") +{ + eoProcedureCounter* result = new eoProcedureCounter(_proc, _name); + store.storeFunctor(result); + return *result; +} + +template +eoUnaryFunctorCounter& make_counter(eoFunctorBase::unary_function_tag, UnaryFunctor& _proc, eoFunctorStore& store, std::string _name = "uf_counter") +{ + eoUnaryFunctorCounter* result = new eoUnaryFunctorCounter(_proc, _name); + store.storeFunctor(result); + return *result; +} + +template +eoBinaryFunctorCounter& make_counter(eoFunctorBase::binary_function_tag, BinaryFunctor& _proc, eoFunctorStore& store, std::string _name = "uf_counter") +{ + eoBinaryFunctorCounter* result = new eoBinaryFunctorCounter(_proc, _name); + store.storeFunctor(result); + return *result; +} + +#endif diff --git a/deprecated/eo/src/eoCtrlCContinue.cpp b/deprecated/eo/src/eoCtrlCContinue.cpp new file mode 100644 index 000000000..b7ee7fea3 --- /dev/null +++ b/deprecated/eo/src/eoCtrlCContinue.cpp @@ -0,0 +1,62 @@ +// -*- 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 +/* + This library is free software; you 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 +*/ +//----------------------------------------------------------------------------- +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include + +#include +#include + +/** + * @addtogroup Continuators + * @{ + */ + +// --- Global variables - but don't know what else to do - MS --- +bool ask_for_stop = false; +bool existCtrlCContinue = false; + +// +// The signal handler - installed in the eoCtrlCContinue Ctor +// +void signal_handler( int sig ) +// --------------------------- +{ + // --- On veut la paix, jusqu'a la fin --- +#ifndef _WINDOWS + #ifdef SIGQUIT + signal( SIGINT, SIG_IGN ); + signal( SIGQUIT, SIG_IGN ); + eo::log << eo::logging << "Ctrl C entered ... closing down" << std::endl ; + ask_for_stop = true; + #endif +#endif +} + +/** @} */ diff --git a/deprecated/eo/src/eoCtrlCContinue.h b/deprecated/eo/src/eoCtrlCContinue.h new file mode 100644 index 000000000..e239f7367 --- /dev/null +++ b/deprecated/eo/src/eoCtrlCContinue.h @@ -0,0 +1,86 @@ +// -*- 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 +/* + This library is free software; you 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 +*/ +//----------------------------------------------------------------------------- +// the same thing can probably be done in MS environement, but I hoave no way +// to test it so at the moment it is commented out when in MSVC + + +#ifndef eoCtrlCContinue_h +#define eoCtrlCContinue_h + +#include +#include + +/** + * @addtogroup Continuators + * @{ + */ + +extern bool ask_for_stop, existCtrlCContinue; + +extern void signal_handler( int sig ); + + +/** + Ctrl C handling: this eoContinue tells whether the user pressed Ctrl C +*/ +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 ); + signal( SIGQUIT, signal_handler ); + existCtrlCContinue = true; + #endif + #endif + + } + + /** Returns false when Ctrl C has been typed in + * reached */ + virtual bool operator() ( const eoPop& _vEO ) + { + (void)_vEO; + if (ask_for_stop) + return false; + return true; + } + + virtual std::string className(void) const { return "eoCtrlCContinue"; } +}; + + +#endif +/** @} */ diff --git a/deprecated/eo/src/eoDetSelect.h b/deprecated/eo/src/eoDetSelect.h new file mode 100644 index 000000000..4a0858b6a --- /dev/null +++ b/deprecated/eo/src/eoDetSelect.h @@ -0,0 +1,91 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoDetSelect_h +#define _eoDetSelect_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +//----------------------------------------------------------------------------- + +/** eoDetSelect selects many individuals determinisctically + * + * @ingroup Selectors +*/ +template +class eoDetSelect : public eoSelect +{ + public: + /// init + eoDetSelect(double _rate = 1.0, bool _interpret_as_rate = true) + : howMany(_rate, _interpret_as_rate) {} + + /** + @param _source the source population + @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) + */ + virtual void operator()(const eoPop& _source, eoPop& _dest) + { + unsigned int pSize = _source.size(); + 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; + } + + _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 // accumulate + +#include +#include +#include +#include + +/** eoDetTournamentSelect: a selection method that selects ONE individual by + deterministic tournament + -MS- 24/10/99 + + @ingroup Selectors + */ +template class eoDetTournamentSelect: public eoSelectOne +{ + public: + /* (Default) Constructor - + @param _tSize tournament size + */ + eoDetTournamentSelect(unsigned _tSize = 2 ):eoSelectOne(), tSize(_tSize) { + // consistency check + if (tSize < 2) { + eo::log << eo::warnings << "Tournament size should be >= 2, adjusted to 2" << std::endl; + tSize = 2; + } + } + + /* Perform deterministic tournament calling the appropriate fn + see selectors.h + */ + virtual const EOT& operator()(const eoPop& _pop) + { + return deterministic_tournament(_pop, tSize); + } + + private: + unsigned tSize; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/eoDistribUpdater.h b/deprecated/eo/src/eoDistribUpdater.h new file mode 100644 index 000000000..79b22814a --- /dev/null +++ b/deprecated/eo/src/eoDistribUpdater.h @@ -0,0 +1,50 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoDistribUpdater_H +#define _eoDistribUpdater_H + +#include + +#include +#include + +/** + * Base class for Distribution Evolution Algorithms within EO: + * the update rule of distribution + * + * It takes one distribution and updates it according to one population + * + * @ingroup Core +*/ +template +class eoDistribUpdater : + public eoBF &, eoPop &, void> +{ +public: + virtual void operator()(eoDistribution &, eoPop &)=0; +}; + +#endif diff --git a/deprecated/eo/src/eoDistribution.h b/deprecated/eo/src/eoDistribution.h new file mode 100644 index 000000000..6ca90fe42 --- /dev/null +++ b/deprecated/eo/src/eoDistribution.h @@ -0,0 +1,54 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoDistribution_H +#define _eoDistribution_H + +#include + +#include +#include + +/** + * Abstract class for Distribution Evolution Algorithms within EO: + * the distribution itself + * + * It basically IS AN eoInit - operator()(EOT &) generates new indis + * + * The instances will probably be eoValueParam of some kind + * see eoPBILDistrib.h + * + * @ingroup Core +*/ + +template +class eoDistribution : public eoInit, + public eoPersistent, public eoObject +{ +public: + virtual void operator()(EOT &) = 0; // DO NOT FORGET TO INVALIDATE the EOT +}; + +#endif diff --git a/deprecated/eo/src/eoDualFitness.h b/deprecated/eo/src/eoDualFitness.h new file mode 100644 index 000000000..674fe075c --- /dev/null +++ b/deprecated/eo/src/eoDualFitness.h @@ -0,0 +1,328 @@ +/* + +(c) 2010 Thales group + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; version 2 + of the License. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: + Johann Dréo + +*/ + +#ifndef _eoDualFitness_h_ +#define _eoDualFitness_h_ + +#include +#include +#include // for std::pair +#include + +#include +#include + +/** @addtogroup Evaluation + * @{ + */ + +//! 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 + * 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 + * maximizing (using less, @see eoMaximizingDualFitness) + * or minimizing (using greater, @see eoMinimizingDualFitness). + * + * Suitable constructors, assignments and casts are defined to work + * with those quantities as if they were a pair of: a BaseType and a boolean. + * + * 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. + * + * This class overrides operator<() to use the Compare template argument and handle feasibility. + * Over operators are coded using this sole function. + * + * Standard arithmetic operators are provided to add or substract dual fitnesses. + * They behave as expected for the fitness value and gives priority to unfeasible fitness + * (i.e. when adding or substracting dual fitness, the only case when the result will be + * a feasible fitness is when both are feasible, else the result is an unfeasibe fitness) +*/ +template +class eoDualFitness +{ +protected: + //! Scalar type of the fitness (generally a double) + BaseType _value; + + //! Flag that marks if the individual is feasible + bool _is_feasible; + +public: + + //! Empty initialization + /*! + * Unfeasible by default + */ + eoDualFitness() : + _value(), + _is_feasible(false) + {} + + //! Copy constructor + eoDualFitness(const eoDualFitness& other) : + _value(other._value), + _is_feasible(other._is_feasible) + {} + + //! Constructor from explicit value/feasibility + eoDualFitness(const BaseType& v, const bool& is_feasible) : + _value(v), + _is_feasible(is_feasible) + {} + + //! From a std::pair (first element is the value, second is the feasibility) + eoDualFitness(const std::pair& dual) : + _value(dual.first), + _is_feasible(dual.second) + {} + + // FIXME is it a good idea to include implicit conversion here? + /** Conversion operator: it permits to use a fitness instance as its scalar + * type, if needed. For example, this is possible: + * eoDualFitness > fit; + * double val = 1.0; + * fit = val; + * val = fit; + */ + operator BaseType(void) const { return _value; } + + + inline bool is_feasible() const + { + return _is_feasible; + } + + inline BaseType value() const + { + return _value; + } + + //! Copy operator from a std::pair + eoDualFitness& operator=(const std::pair& v) + { + _value = v.first; + _is_feasible = v.second; + return *this; + } + + //! Copy operator from another eoDualFitness + template + eoDualFitness & operator=(const eoDualFitness& other ) + { + if (this != &other) { + this->_value = other._value; + this->_is_feasible = other._is_feasible; + } + return *this; + } + + //! Comparison that separate feasible individuals from unfeasible ones. Feasible are always better + /*! + * 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 + if( this->_is_feasible && !other._is_feasible ) { + // no, the other has a better fitness + return false; + + } else if( !this->_is_feasible && other._is_feasible ) { + // yes, a feasible fitness is always better than an unfeasible one + return true; + + } else { + // the two fitness are of the same type + // lets rely on the comparator + return Compare()(_value, other._value); + } + } + + //! Greater: if the other is lesser than me + bool operator>( const eoDualFitness& other ) const { return other < *this; } + + //! Less or equal: if the other is not lesser than me + bool operator<=( const eoDualFitness& other ) const { return !(other < *this); } + + //! Greater or equal: if the other is not greater than me + bool operator>=(const eoDualFitness& other ) const { return !(*this < other); } + + //! Equal: if the other is equal to me + bool operator==(const eoDualFitness& other) const { return ( _is_feasible == other._is_feasible ) && ( _value == other._value ); } + +public: + + //! Add a given fitness to the current one + template + friend + eoDualFitness & operator+=( eoDualFitness & from, const eoDualFitness & that ) + { + from._value += that._value; + + // true only if the two are feasible, else false + from._is_feasible = from._is_feasible && that._is_feasible; + + return from; + } + + //! Substract a given fitness to the current one + template + friend + eoDualFitness & operator-=( eoDualFitness & from, const eoDualFitness & that ) + { + from._value -= that._value; + + // true only if the two are feasible, else false + from._is_feasible = from._is_feasible && that._is_feasible; + + return from; + } + + // Add this fitness's value to that other, and return a _new_ instance with the result. + template + eoDualFitness operator+(const eoDualFitness & that) + { + eoDualFitness from( *this ); + return from += that; + } + + // Add this fitness's value to that other, and return a _new_ instance with the result. + template + eoDualFitness operator-(const eoDualFitness & that) + { + eoDualFitness from( *this ); + return from -= that; + } + + //! Print an eoDualFitness instance as a pair of numbers, separated by a space + template + friend + std::ostream& operator<<(std::ostream& os, const eoDualFitness& f) + { + os << f._value << " " << f._is_feasible; + return os; + } + + //! Read an eoDualFitness instance as a pair of numbers, separated by a space + template + friend + std::istream& operator>>(std::istream& is, eoDualFitness& f) + { + F value; + is >> value; + + bool feasible; + is >> feasible; + + f = std::make_pair( value, feasible ); + return is; + } +}; + +//! Compare dual fitnesses as if we were maximizing +typedef eoDualFitness > eoMaximizingDualFitness; + +//! Compare dual fitnesses as if we were minimizing +typedef eoDualFitness > eoMinimizingDualFitness; + +//! A predicate that returns the feasibility of a given dual fitness +/** Use this in STL algorithm that use binary predicates (e.g. count_if, find_if, etc.) + */ +template< class EOT> +bool eoIsFeasible ( const EOT & sol ) { return sol.fitness().is_feasible(); } + + +/** Embed two eoStat and call the first one on the feasible individuals and + * the second one on the unfeasible ones, merge the two resulting value in + * a string, separated by a given marker. + */ +//template +template +class eoDualStatSwitch : public eoStat< EOT, std::string > +{ +public: + using eoStat::value; + +// 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(sep) + { } + + virtual void operator()( const eoPop & pop ) + { + eoPop pop_feasible; + pop_feasible.reserve(pop.size()); + + eoPop pop_unfeasible; + pop_unfeasible.reserve(pop.size()); + + for( typename eoPop::const_iterator ieot=pop.begin(), iend=pop.end(); ieot!=iend; ++ieot ) { + /* + if( ieot->invalid() ) { + eo::log << eo::errors << "ERROR: trying to access to an invalid fitness" << std::endl; + } + */ + if( ieot->fitness().is_feasible() ) { + pop_feasible.push_back( *ieot ); + } else { + pop_unfeasible.push_back( *ieot ); + } + } + + _stat_feasible( pop_feasible ); + _stat_unfeasible( pop_unfeasible ); + + std::ostringstream out; + out << _stat_feasible.value() << _sep << _stat_unfeasible.value(); + + value() = out.str(); + } + +protected: +// eoStat & _stat_feasible; +// eoStat & _stat_unfeasible; + EOSTAT & _stat_feasible; + EOSTAT & _stat_unfeasible; + + std::string _sep; +}; + +/** @} */ +#endif // _eoDualFitness_h_ diff --git a/deprecated/eo/src/eoEDA.h b/deprecated/eo/src/eoEDA.h new file mode 100644 index 000000000..553b751f3 --- /dev/null +++ b/deprecated/eo/src/eoEDA.h @@ -0,0 +1,46 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoEDA_h +#define _eoEDA_h + +//----------------------------------------------------------------------------- + +#include + +/** 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. + * + * @ingroup Algorithms +*/ + +template class eoEDA: public eoUF&, void> +{ +}; + +#endif diff --git a/deprecated/eo/src/eoEasyEA.h b/deprecated/eo/src/eoEasyEA.h new file mode 100644 index 000000000..2c7c5474c --- /dev/null +++ b/deprecated/eo/src/eoEasyEA.h @@ -0,0 +1,322 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoEasyEA.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoEasyEA_h +#define _eoEasyEA_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +template class eoIslandsEasyEA ; + +template class eoDistEvalEasyEA ; + +/** An easy-to-use evolutionary algorithm; you can use any chromosome, + and any selection transformation, merging and evaluation + algorithms; you can even change in runtime parameters of those + sub-algorithms + +Change (MS, July 3. 2001): + Replaced the eoEvalFunc by an eoPopEvalFunc: this immediately + allows many useful constructs, such as co-evolution (e.g. game players), + parisian approach (the solution to the problem is the whole population) + or simple distribution of evaluations on a cluster. + In case an eoEvalFunc is passed, it is embedded on an eoPopLoopEval + This makes things a little uglier (required an additional "dummy" member + +Note: it looks ugly only because we wanted to authorize many different + constructors. Please only look at the operator() and there shall be light + + @ingroup Algorithms +*/ +template class eoEasyEA: public eoAlgo + { + public: + + /** Ctor taking a breed and merge */ + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoBreed& _breed, + eoReplacement& _replace + ) : continuator(_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + selectTransform(dummySelect, dummyTransform), + breed(_breed), + mergeReduce(dummyMerge, dummyReduce), + replace(_replace), + isFirstCall(true) + {} + + /** 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), + isFirstCall(true) + { + offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. + } + + /* + eoEasyEA(eoContinue & _continuator, + eoPopEvalFunc & _pop_eval, + eoBreed & _breed, + eoReplacement & _replace + ) : + continuator (_continuator), + eval (dummyEval), + loopEval(dummyEval), + popEval (_pop_eval), + selectTransform (dummySelect, dummyTransform), + breed (_breed), + mergeReduce (dummyMerge, dummyReduce), + replace (_replace), + isFirstCall(true) + { + + } + */ + + /** NEW Ctor taking a breed and merge and an eoPopEval */ + eoEasyEA( + eoContinue& _continuator, + eoPopEvalFunc& _eval, + eoBreed& _breed, + eoReplacement& _replace + ) : continuator(_continuator), + eval (dummyEval), + loopEval(dummyEval), + popEval(_eval), + selectTransform(dummySelect, dummyTransform), + breed(_breed), + mergeReduce(dummyMerge, dummyReduce), + replace(_replace), + isFirstCall(true) + {} + + + /// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval + eoEasyEA( + eoContinue& _continuator, + eoPopEvalFunc& _eval, + eoSelect& _select, + eoTransform& _transform, + eoReplacement& _replace + ) : continuator(_continuator), + eval (dummyEval), + loopEval(dummyEval), + popEval(_eval), + selectTransform(_select, _transform), + breed(selectTransform), + mergeReduce(dummyMerge, dummyReduce), + replace(_replace), + isFirstCall(true) + {} + + /// Ctor eoBreed, eoMerge and eoReduce. + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoBreed& _breed, + eoMerge& _merge, + eoReduce& _reduce + ) : continuator(_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + selectTransform(dummySelect, dummyTransform), + breed(_breed), + mergeReduce(_merge, _reduce), + replace(mergeReduce), + isFirstCall(true) + {} + + /// Ctor eoSelect, eoTransform, and eoReplacement + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoSelect& _select, + eoTransform& _transform, + eoReplacement& _replace + ) : continuator(_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + selectTransform(_select, _transform), + breed(selectTransform), + mergeReduce(dummyMerge, dummyReduce), + replace(_replace), + isFirstCall(true) + {} + + /// Ctor eoSelect, eoTransform, eoMerge and eoReduce. + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoSelect& _select, + eoTransform& _transform, + eoMerge& _merge, + eoReduce& _reduce + ) : continuator(_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + selectTransform(_select, _transform), + breed(selectTransform), + mergeReduce(_merge, _reduce), + replace(mergeReduce), + isFirstCall(true) + {} + + + + + /// Apply a few generation of evolution to the population. + virtual void operator()(eoPop& _pop) + { + if (isFirstCall) + { + size_t total_capacity = _pop.capacity() + offspring.capacity(); + _pop.reserve(total_capacity); + offspring.reserve(total_capacity); + isFirstCall = false; + } + + eoPop empty_pop; + + popEval(empty_pop, _pop); // A first eval of pop. + + do + { + try + { + unsigned pSize = _pop.size(); + offspring.clear(); // new offspring + + breed(_pop, offspring); + + popEval(_pop, offspring); // eval of parents + offspring if necessary + + replace(_pop, offspring); // after replace, the new pop. is in _pop + + if (pSize > _pop.size()) + throw std::runtime_error("Population shrinking!"); + else if (pSize < _pop.size()) + throw std::runtime_error("Population growing!"); + + } + catch (std::exception& e) + { + std::string s = e.what(); + s.append( " in eoEasyEA"); + throw std::runtime_error( s ); + } + } + while ( continuator( _pop ) ); + } + + protected : + + // If selectTransform needs not be used, dummySelect and dummyTransform are used + // to instantiate it. + class eoDummySelect : public eoSelect + { + public : + void operator()(const eoPop&, eoPop&) + {} + } + dummySelect; + + class eoDummyTransform : public eoTransform + { + public : + void operator()(eoPop&) + {} + } + dummyTransform; + + class eoDummyEval : public eoEvalFunc + { + public: + void operator()(EOT &) + {} + } + dummyEval; + + eoContinue& continuator; + + eoEvalFunc & eval ; + eoPopLoopEval loopEval; + + eoPopEvalFunc& popEval; + + eoSelectTransform selectTransform; + eoBreed& breed; + + // If mergeReduce needs not be used, dummyMerge and dummyReduce are used + // to instantiate it. + eoNoElitism dummyMerge; + eoTruncate dummyReduce; + + eoMergeReduce mergeReduce; + eoReplacement& replace; + + eoPop offspring; + + bool isFirstCall; + + // Friend classes + friend class eoIslandsEasyEA ; + friend class eoDistEvalEasyEA ; +}; +/** +@example t-eoEasyEA.cpp +Example of a test program building an EA algorithm. +*/ + +#endif diff --git a/deprecated/eo/src/eoEasyPSO.h b/deprecated/eo/src/eoEasyPSO.h new file mode 100644 index 000000000..da071bc02 --- /dev/null +++ b/deprecated/eo/src/eoEasyPSO.h @@ -0,0 +1,196 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoEasyPSO.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOEASYPSO_H +#define _EOEASYPSO_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** 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 +* +* @ingroup Algorithms +*/ +template < class POT > class eoEasyPSO:public eoPSO < POT > +{ +public: + + /** Full constructor + * @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s) + * @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 + * to modify the positions according to the velocities + */ + eoEasyPSO ( + eoInitializerBase &_init, + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity, + eoFlight < POT > &_flight): + init(_init), + continuator (_continuator), + eval (_eval), + velocity (_velocity), + flight (_flight) + {} + + + /** Constructor without eoFlight. For special cases when the flight is performed withing the velocity. + * @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s) + * @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 + */ + eoEasyPSO ( + eoInitializerBase &_init, + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity): + init(_init), + continuator (_continuator), + eval (_eval), + velocity (_velocity), + flight (dummyFlight) + {} + + + /* 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 + * to modify the positions according to the velocities + */ + eoEasyPSO ( + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity, + eoFlight < POT > &_flight): + init(dummyInit), + continuator (_continuator), + eval (_eval), + velocity (_velocity), + flight (_flight) + {} + + + /** Constructor without eoFlight nor eoInitializerBase. For special cases when the flight is performed withing the velocity. + * @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 + */ + eoEasyPSO ( + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity): + init(dummyInit), + continuator (_continuator), + eval (_eval), + velocity (_velocity), + flight (dummyFlight) + {} + + /// Apply a few iteration of flight to the population (=swarm). + virtual void operator () (eoPop < POT > &_pop) + { + try + { + // initializes the topology, velocity, best particle(s) + init(); + do + { + // loop over all the particles for the current iteration + for (unsigned idx = 0; idx < _pop.size (); idx++) + { + // perform velocity evaluation + velocity (_pop[idx],idx); + + // apply the flight + flight (_pop[idx]); + + // evaluate the position + eval (_pop[idx]); + + // update the topology (particle and local/global best(s)) + velocity.updateNeighborhood(_pop[idx],idx); + } + + } + while (continuator (_pop)); + + } + catch (std::exception & e) + { + std::string s = e.what (); + s.append (" in eoEasyPSO"); + throw std::runtime_error (s); + } + + } + +protected: + eoInitializerBase &init; + eoContinue < POT > &continuator; + eoEvalFunc < POT > &eval; + 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; + +}; +/** + * @example t-eoEasyPSO.cpp + * Example of a test program building a PSO algorithm. + */ + +#endif /*_EOEASYPSO_H*/ diff --git a/deprecated/eo/src/eoEvalContinue.h b/deprecated/eo/src/eoEvalContinue.h new file mode 100644 index 000000000..ef74e0758 --- /dev/null +++ b/deprecated/eo/src/eoEvalContinue.h @@ -0,0 +1,69 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoEvalContinue_h +#define _eoEvalContinue_h + +#include +#include + +/** + * Continues until a number of evaluations has been made + * + * @ingroup Continuators +*/ +template< class EOT> +class eoEvalContinue: public eoContinue +{ +public: + /// Ctor + eoEvalContinue( eoEvalFuncCounter & _eval, unsigned long _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) + { + eo::log << eo::progress << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]" << std::endl; + return false; + } + return true; + } + + /** Returns the number of generations to reach*/ + virtual unsigned long totalEvaluations( ) + { + return repTotalEvaluations; + }; + + virtual std::string className(void) const { return "eoEvalContinue"; } +private: + eoEvalFuncCounter & eval; + unsigned long repTotalEvaluations; +}; + +#endif diff --git a/deprecated/eo/src/eoEvalCounterThrowException.h b/deprecated/eo/src/eoEvalCounterThrowException.h new file mode 100644 index 000000000..4eb4fccc4 --- /dev/null +++ b/deprecated/eo/src/eoEvalCounterThrowException.h @@ -0,0 +1,86 @@ +/* +(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 +Caner Candan + +*/ + +#ifndef __eoEvalCounterThrowException_h__ +#define __eoEvalCounterThrowException_h__ + +#include +#include +#include + +/*! +Wrap an evaluation function so that an exception may be thrown when the +algorithm have reached a maximum number of evaluations. + +This may be useful if you want to check this kind of stopping criterion +at each _evaluation_, instead of using continuators at each _iteration_. + +The class first call the evaluation function, then check the number of +times it has been called. If the maximum number of evaluation has been +reached, it throw an eoMaxEvalException. You can catch this exception +from your main function, so as to stop everything properly. + +@ingroup Evaluation +*/ +template < typename EOT > +class eoEvalCounterThrowException : public eoEvalFuncCounter< EOT > +{ +public : + eoEvalCounterThrowException( eoEvalFunc& func, unsigned long max_evals, std::string name = "Eval. ") + : eoEvalFuncCounter< EOT >( func, name ), _threshold( max_evals ) + {} + + using eoEvalFuncCounter< EOT >::value; + + //! Evaluate the individual, then throw an exception if it exceed the max number of evals. + virtual void operator()(EOT& eo) + { + // bypass already evaluated individuals + if (eo.invalid()) { + + // increment the value of the self parameter + // (eoEvalFuncCounter inherits from @see eoValueParam) + value()++; + + // if we have reached the maximum + if ( value() >= _threshold ) { + + // go back through the stack until catched + throw eoMaxEvalException(_threshold); + } + + // evaluate + func(eo); + + } // if invalid + } + + virtual std::string className() const {return "eoEvalCounterThrowException";} + +private : + unsigned long _threshold; +}; + +#endif // __eoEvalCounterThrowException_h__ diff --git a/deprecated/eo/src/eoEvalFunc.h b/deprecated/eo/src/eoEvalFunc.h new file mode 100644 index 000000000..b05b667b2 --- /dev/null +++ b/deprecated/eo/src/eoEvalFunc.h @@ -0,0 +1,55 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoEvalFunc_H +#define eoEvalFunc_H + +#include + +/** @defgroup Evaluation Evaluation + * @ingroup Operators + */ + +/** Evaluate: takes one EO and sets its "fitness" property + returning this fitness also. That is why EOT is passed by + non-const reference: it must be altered within evaluate.\\ + + 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 + EO, the requirements on this EO will depend on the evaluator. + + @ingroup Evaluation + @ingroup Core + */ +template class eoEvalFunc : public eoUF +{ + public : + typedef EOT EOType; + + typedef typename EOT::Fitness EOFitT; +}; + +#endif diff --git a/deprecated/eo/src/eoEvalFuncCounter.h b/deprecated/eo/src/eoEvalFuncCounter.h new file mode 100644 index 000000000..a63821d61 --- /dev/null +++ b/deprecated/eo/src/eoEvalFuncCounter.h @@ -0,0 +1,57 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoEvalFuncCounter_H +#define eoEvalFuncCounter_H + +#include +#include + +/** +Counts the number of evaluations actually performed. + +@ingroup Evaluation +*/ +template class eoEvalFuncCounter : public eoEvalFunc, public eoValueParam +{ + public : + eoEvalFuncCounter(eoEvalFunc& _func, std::string _name = "Eval. ") + : eoValueParam(0, _name), func(_func) {} + + virtual void operator()(EOT& _eo) + { + if (_eo.invalid()) + { + value()++; + func(_eo); + } + } + + protected : + eoEvalFunc& func; +}; + +#endif diff --git a/deprecated/eo/src/eoEvalFuncCounterBounder.h b/deprecated/eo/src/eoEvalFuncCounterBounder.h new file mode 100644 index 000000000..1c8a29b15 --- /dev/null +++ b/deprecated/eo/src/eoEvalFuncCounterBounder.h @@ -0,0 +1,67 @@ +#ifndef eoEvalFuncCounterBounder_H +#define eoEvalFuncCounterBounder_H + +#include +#include + +/** @addtogroup Evaluation + * @{ + */ + +/** The exception raised by eoEvalFuncCounterBounder + * when the maximum number of allowed evaluations is reached. + */ +class eoEvalFuncCounterBounderException : public std::exception +{ +public: + eoEvalFuncCounterBounderException(unsigned long threshold) : _threshold(threshold){} + + 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(); + } + +private: + unsigned long _threshold; +}; + +/** Counts the number of evaluations actually performed and throw an eoEvalFuncCounterBounderException + * 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, + * but want to stop after 95 evaluations. +*/ +template < typename EOT > +class eoEvalFuncCounterBounder : public eoEvalFuncCounter< EOT > +{ +public : + eoEvalFuncCounterBounder(eoEvalFunc& func, unsigned long threshold, std::string name = "Eval. ") + : eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold ) + {} + + using eoEvalFuncCounter< EOT >::value; + + virtual void operator()(EOT& eo) + { + if (eo.invalid()) + { + value()++; + + if (_threshold > 0 && value() >= _threshold) + { + throw eoEvalFuncCounterBounderException(_threshold); + } + + func(eo); + } + } + +private : + unsigned long _threshold; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoEvalFuncPtr.h b/deprecated/eo/src/eoEvalFuncPtr.h new file mode 100644 index 000000000..f4952c212 --- /dev/null +++ b/deprecated/eo/src/eoEvalFuncPtr.h @@ -0,0 +1,67 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +----------------------------------------------------------------------------- + eoEvalFuncPtr.h + Converts a classical C fitness evaluation function into a fitness + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOEVALFUNCPTR_H +#define EOEVALFUNCPTR_H + +#include + +/** EOEvalFuncPtr: This class + * takes an existing function pointer and converts it into a evaluation + * function class. That way, old style C or C++ functions can be adapted to EO + * function classes. + * + * @ingroup Evaluation + */ +#ifdef _MSC_VER +template< class EOT, class FitT = EOT::Fitness, class FunctionArg = const EOT& > +#else +template< class EOT, class FitT = typename EOT::Fitness, class FunctionArg = const EOT& > +#endif +struct eoEvalFuncPtr: public eoEvalFunc { + + /** Applies the function to the chromosome and sets the fitness of the + Chrom. Thus, the evaluation function need not be worried about that. + @param _eval pointer to the evaluation function, takes a EOT as an + argument and returns the fitness + @return the evaluated fitness for that object. + */ + eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) ) + : eoEvalFunc(), evalFunc( _eval ) {}; + + /// 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/deprecated/eo/src/eoEvalTimeThrowException.h b/deprecated/eo/src/eoEvalTimeThrowException.h new file mode 100644 index 000000000..be0e149a2 --- /dev/null +++ b/deprecated/eo/src/eoEvalTimeThrowException.h @@ -0,0 +1,59 @@ +/* +(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 + +/** Check at each evaluation if a given tie 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. + * + * @ingroup Evaluation + */ +template< class EOT > +class eoEvalTimeThrowException : public eoEvalFuncCounter< EOT > +{ +public: + eoEvalTimeThrowException( eoEvalFunc & func, time_t max ) : _max(max), _start( std::time(NULL) ), eoEvalFuncCounter( func, "Eval.") {} + + virtual void operator() ( EOT & eo ) + { + if( eo.invalid() ) { + + time_t elapsed = static_cast( std::difftime( std::time(NULL) , _start ) ); + + if( elapsed >= _max ) { + throw eoMaxTimeException(elapsed); + } else { + func(eo); + } + } + } + +protected: + time_t _max; + + time_t _start; +}; diff --git a/deprecated/eo/src/eoEvalUserTimeThrowException.h b/deprecated/eo/src/eoEvalUserTimeThrowException.h new file mode 100644 index 000000000..2cf72f6c1 --- /dev/null +++ b/deprecated/eo/src/eoEvalUserTimeThrowException.h @@ -0,0 +1,73 @@ +/* +(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 +*/ + + +#ifndef __unix__ +/*#warning "Warning: class 'eoEvalUserTimeThrowException' is only available under UNIX systems (defining 'rusage' in 'sys/resource.h'), contributions for other systems are welcomed."*/ +#else + +#ifndef __EOEVALUSERTIMETHROWEXCEPTION_H__ +#define __EOEVALUSERTIMETHROWEXCEPTION_H__ + +#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, const long max ) : eoEvalFuncCounter( func, "CPU-user"), _max(max) {} + + virtual void operator() ( EOT & eo ) + { + if( eo.invalid() ) { + + getrusage(RUSAGE_SELF,&_usage); + + long current = _usage.ru_utime.tv_sec; + if( current >= _max ) { + throw eoMaxTimeException( current ); + } else { + func(eo); + } + } + } + +protected: + const long _max; + struct rusage _usage; +}; + +#endif // __EOEVALUSERTIMETHROWEXCEPTION_H__ +#endif // __UNIX__ diff --git a/deprecated/eo/src/eoExceptions.h b/deprecated/eo/src/eoExceptions.h new file mode 100644 index 000000000..4d56ddb95 --- /dev/null +++ b/deprecated/eo/src/eoExceptions.h @@ -0,0 +1,132 @@ +/* +(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 +*/ + +#ifndef __eoExceptions_h__ +#define __eoExceptions_h__ + +#include +#include + +class eoMaxException : public std::exception {}; + + + +/*! +An error that signals that a maximum elapsed time has been reached. + +Thrown by @see eoEvalTimeThrowException + +@ingroup Evaluation +*/ +class eoMaxTimeException : public eoMaxException +{ +public: + eoMaxTimeException( time_t elapsed) : _elapsed(elapsed) {} + + virtual const char* what() const throw() + { + std::ostringstream ss; + ss << "STOP in eoMaxTimeException: the maximum number of allowed seconds has been reached (" << _elapsed << ")."; + return ss.str().c_str(); + } + +private: + time_t _elapsed; +}; + + +/*! +An error that signals that a maximum number of evaluations has been reached. + +Thrown by @see eoEvalEvalThrowException + +@ingroup Evaluation +*/ +class eoMaxEvalException : public eoMaxException +{ +public: + eoMaxEvalException(unsigned long threshold) : _threshold(threshold){} + + virtual const char* what() const throw() + { + std::ostringstream ss; + ss << "STOP in eoMaxEvalException: the maximum number of evaluation has been reached (" << _threshold << ")."; + return ss.str().c_str(); + } + +private: + unsigned long _threshold; +}; + + +/*! + * An error that signals a missing parameter + * + * Thrown by eoParser::getParam + * + * @ingroup Parameters + */ +class eoMissingParamException : public std::exception +{ +public: + eoMissingParamException(std::string name) : _name(name){} + + virtual const char* what() const throw() + { + std::ostringstream ss; + ss << "The command parameter " << _name << " has not been declared"; + return ss.str().c_str(); + } + + ~eoMissingParamException() throw() {} + +private: + std::string _name; +}; + +/*! + * An error that signals a bad parameter type + * + * Thrown by eoParser::valueOf + * + * @ingroup Parameters + */ +class eoWrongParamTypeException : public std::exception +{ +public: + eoWrongParamTypeException(std::string name) : _name(name){} + + virtual const char* what() const throw() + { + std::ostringstream ss; + ss << "You asked for the parameter " << _name << " but it has not been declared under this type"; + return ss.str().c_str(); + } + + ~eoWrongParamTypeException() throw() {} + +private: + std::string _name; +}; + +#endif // __eoExceptions_h__ diff --git a/deprecated/eo/src/eoExtendedVelocity.h b/deprecated/eo/src/eoExtendedVelocity.h new file mode 100644 index 000000000..e7667204c --- /dev/null +++ b/deprecated/eo/src/eoExtendedVelocity.h @@ -0,0 +1,213 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoExtendedVelocity.h +// (c) INRIA Dolphin 2008 +/* + This library is free software; you 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: thomas.legrand@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoExtendedVelocity_H +#define eoExtendedVelocity_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + +/** 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) ) +* It includes both a "topology" best and a global best in the social knowledge. Each topology +* provides a method to retrieve the global best <=> the best of all the neighborhood the topology contains. +* +* @ingroup Variators +*/ +template < class POT > class eoExtendedVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** 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 _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. + * 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 & _c1, + const VelocityType & _c2, + const VelocityType & _c3, + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + omega (_w), + c1 (_c1), + c2 (_c2), + c3 (_c3), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** 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 _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 _gen - The eo random generator, default=rng + */ + eoExtendedVelocity (eoTopology < POT > & _topology, + const VelocityType & _w, + const VelocityType & _c1, + const VelocityType & _c2, + const VelocityType & _c3, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + omega (_w), + c1 (_c1), + c2 (_c2), + c3 (_c3), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _c3 - Learning factor used for the global best + * @param _gen - The eo random generator, default=rng + */ + eoExtendedVelocity (eoTopology < POT > & _topology, + const VelocityType & _w, + const VelocityType & _c1, + const VelocityType & _c2, + const VelocityType & _c3, + eoRng & _gen = rng): + topology(_topology), + omega (_w), + c1 (_c1), + c2 (_c2), + c3 (_c3), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen) + {} + + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * into the topology. + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r1; + VelocityType r2; + 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; + + // 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]); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + //! eoTopology getTopology + //! @return topology + + eoTopology & getTopology () + { + return topology; + } + +protected: + eoTopology < POT > & topology; + 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; + + eoRng & gen; // the random generator + + // If the bound modifier doesn't need to be used, use the dummy instance + eoDummyRealBoundModifier dummyModifier; +}; +/** @todo this example does not appear in the doc for an unknown reason + * @example t-eoExtendedVelocity.cpp + * Example of a test program using this class: +*/ +#endif /*eoExtendedVelocity_H */ diff --git a/deprecated/eo/src/eoFactory.h b/deprecated/eo/src/eoFactory.h new file mode 100644 index 000000000..73a8faf1b --- /dev/null +++ b/deprecated/eo/src/eoFactory.h @@ -0,0 +1,75 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOFACTORY_H +#define _EOFACTORY_H + +//----------------------------------------------------------------------------- +#include + +//----------------------------------------------------------------------------- + +/** EO Factory. A factory is used to create other objects. In particular, +it can be used so that objects of that kind cant be created in any other +way. It should be instantiated with anything that needs a factory, like selectors +or whatever; but the instance class should be the parent class from which all the +object that are going to be created descend. This class basically defines an interface, +as usual. The base factory class for each hierarchy should be redefined every time a new +object is added to the hierarchy, which is not too good, but in any case, some code would +have to be modified + +@ingroup Utilities +*/ +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 eoObject methods + //@{ + /** Return the class id */ + virtual std::string className() const { return "eoFactory"; } + + /** Read and print are left without implementation */ + //@} + +}; + + +#endif diff --git a/deprecated/eo/src/eoFitContinue.h b/deprecated/eo/src/eoFitContinue.h new file mode 100644 index 000000000..2db88f80b --- /dev/null +++ b/deprecated/eo/src/eoFitContinue.h @@ -0,0 +1,69 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFitContinue.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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFitContinue_h +#define _eoFitContinue_h + +#include +#include + +/** +Continues until the optimum fitness level is reached. + +All types which derive from eoScalarFitness is able to compare well via the operator override ( <, >, <=, ...) + + @ingroup Continuators +*/ +template< class EOT> +class eoFitContinue: public eoContinue { +public: + + /// Define Fitness + typedef typename EOT::Fitness FitnessType; + + /// Ctor + eoFitContinue( const FitnessType _optimum) + : eoContinue (), optimum( _optimum ) {}; + + /** 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; + } + + virtual std::string className(void) const { return "eoFitContinue"; } + +private: + FitnessType optimum; +}; + +#endif diff --git a/deprecated/eo/src/eoFitnessScalingSelect.h b/deprecated/eo/src/eoFitnessScalingSelect.h new file mode 100644 index 000000000..c17532019 --- /dev/null +++ b/deprecated/eo/src/eoFitnessScalingSelect.h @@ -0,0 +1,55 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoFitnessScalingSelect_h +#define eoFitnessScalingSelect_h + +//----------------------------------------------------------------------------- + +#include +#include + +/** 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 +{ +public: + /** Ctor: + * @param _p the selective pressure, should be in [1,2] (2 is the default) + */ + eoFitnessScalingSelect(double _p = 2.0): + eoRouletteWorthSelect(scaling), scaling(_p) {} + +private : + eoLinearFitScaling scaling; // derived from eoPerf2Worth +}; + +#endif diff --git a/deprecated/eo/src/eoFixedInertiaWeightedVelocity.h b/deprecated/eo/src/eoFixedInertiaWeightedVelocity.h new file mode 100644 index 000000000..291c85a09 --- /dev/null +++ b/deprecated/eo/src/eoFixedInertiaWeightedVelocity.h @@ -0,0 +1,191 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFixedInertiaWeightedVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOFIXEDINERTIAWEIGHTEDVELOCITY_H +#define EOFIXEDINERTIAWEIGHTEDVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + +/** Inertia weight based velocity performer. Derivated from abstract eoVelocity, +* At step t+1 : v(t+1)= w * v(t) + c1*r1 * (xbest(t)-x(t)) + c2*r2 * (gbest(t) - x(t)) +* w is fixed for all the particles and all the generations. +* (ci and w given; Ri chosen at random * in [0;1]) +* +* @ingroup Variators +*/ +template < class POT > class eoFixedInertiaWeightedVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** 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. + * 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 + */ + eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology, + const VelocityType & _weight, + const VelocityType & _c1, + const VelocityType & _c2 , + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + weight(_weight), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** 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. + * 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 + */ + eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology, + const VelocityType & _weight, + const VelocityType & _c1, + const VelocityType & _c2, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + weight(_weight), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _gen - The eo random generator, default=rng + */ + eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology, + const VelocityType & _weight, + const VelocityType & _c1, + const VelocityType & _c2, + eoRng & _gen = rng): + topology(_topology), + weight(_weight), + c1 (_c1), + c2 (_c2), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen) + {} + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * 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) + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r1; + VelocityType r2; + + VelocityType newVelocity; + + // cast the learning factors to VelocityType + r1 = (VelocityType) rng.uniform (1) * c1; + r2 = (VelocityType) rng.uniform (1) * c2; + + // 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= weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]); + + /* modify the bounds */ + bndsModifier(bounds,j); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + + +protected: + eoTopology < POT > & topology; + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 + const VelocityType & weight; // the fixed weight + eoRng & gen; // the random generator + + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + // If the bound modifier doesn't need to be used, use the dummy instance + eoDummyRealBoundModifier dummyModifier; +}; + + +#endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */ diff --git a/deprecated/eo/src/eoFlOrBinOp.h b/deprecated/eo/src/eoFlOrBinOp.h new file mode 100644 index 000000000..bcdc9c5c1 --- /dev/null +++ b/deprecated/eo/src/eoFlOrBinOp.h @@ -0,0 +1,224 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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@inria.fr + mkeijzer@cs.vu.nl + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFlOrBinOp_h +#define _eoFlOrBinOp_h + +#include +#include + +/** @addtogroup Variators + * @{ + */ + +/** Generic eoBinOps on fixed length genotypes. + * Contains exchange crossovers (1pt and uniform) + * 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 + * could be implemented as resp. eoFlOr1ptBinOp and eoFlOrUniformBinOp +*/ + +////////////////////////////////////////////////////////////////////// +// eoFlOrAllAtomBinOp +////////////////////////////////////////////////////////////////////// +/** Bin Crossover using an Atom Crossover + * that is applied to a ALL components with given rate + */ +template +class eoFlOrAllAtomBinOp : public eoBinOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires an Atom BinOp */ + eoFlOrAllAtomBinOp( eoBinOp& _op, float _rate = 1.0): + op(_op), rate( _rate ) {} + + /** applies Atom crossover to ALL components with given rate */ + bool operator()(EOT & _eo1, const EOT & _eo2) + { + if (_eo1.size() != _eo2.size()) + { + 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; + } + } + return changed; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOrAllAtomBinOp"; } + +private: + double rate; + eoBinOp & op; +}; + +////////////////////////////////////////////////////////////////////// +// eoFlOrKAtomBinOp +////////////////////////////////////////////////////////////////////// +/** Bin Crossover using an Atom Crossover + * that is applied to a FIXED NB of components + */ +template +class eoFlOrKAtomBinOp : public eoBinOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires an Atom BinOp and an unsigned */ + eoFlOrAtomBinOp( eoBinOp& _op, unsigned _k = 1): + op(_op), k( _k ) {} + + /** applies the Atom BinOp to some components */ + bool operator()(EOT & _eo1, const EOT & _eo2) + { + if (_eo1.size() != _eo2.size()) + { + 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; + } + return changed; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOrKAtomBinOp"; } + +private: + unsigned k; + eoBinOp & op; +}; + + +////////////////////////////////////////////////////////////////////// +// eoFlOrUniformBinOp +////////////////////////////////////////////////////////////////////// + +/** The uniform crossover - exchanges atoms uniformly ! */ +template +class eoFlOrUniformBinOp : public eoBinOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires a rate - 0.5 by default */ + eoFlOrUniformBinOp(double _rate=0.5) : eoBinOp(_size), + rate(_rate) {} + + /** excahnges atoms at given rate */ + bool operator()(EOT & _eo1, const EOT & _eo2) + { + unsigned i; + Atom tmp; + if (_eo1.size() != _eo2.size()) + { + 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; + } + } + return hasChanged; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOrUniformBinOp"; } + +private: + double rate; +}; + +////////////////////////////////////////////////////////////////////// +// eoFlOr1ptBinOp +////////////////////////////////////////////////////////////////////// + +/** The 1pt crossover (just in case someone wants it some day!) */ +template +class eoFlOr1ptBinOp : public eoBinOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: no argument */ + eoVlUniformBinOp() {} + + /** exchanges first and second parts of the vectors of Atoms */ + bool operator()(EOT & _eo1, EOT & _eo2) + { + unsigned i; + Atom tmp; + if (_eo1.size() != _eo2.size()) + { + 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; + } + } + return hasChanged; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOr1ptBinOp"; } + +}; + +/** @} */ + +#endif diff --git a/deprecated/eo/src/eoFlOrMonOp.h b/deprecated/eo/src/eoFlOrMonOp.h new file mode 100644 index 000000000..63dae9cba --- /dev/null +++ b/deprecated/eo/src/eoFlOrMonOp.h @@ -0,0 +1,123 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFlOrMonOp.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 + 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 + mkeijzer@cs.vu.nl + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFlOrMonOp_h +#define _eoFlOrMonOp_h + +#include +#include +#include + +/** @addtogroup Variators + * @{ + */ + +/** Base classes for generic mutations on fixed length chromosomes. + * Contains 2 classes that both use an atomic mutation + * 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 + * with atom mutation == bitflipping + */ + +/** applies an atomic mutation to all the components with a given rate + */ +template +class eoFlOrAllMutation : public eoMonOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires an Atom mutation and a rate */ + eoFlOrAllMutation(eoMonOp & _atomMutation, double _rate=1.0) : + atomMutation(_atomMutation), rate(_rate) {} + + /** applies the atom mutation to all components with given rate */ + bool operator()(EOT & _eo) + { + bool modified=false; + for (unsigned i=0; i<_eo.size(); i++) + if (eo::rng.flip(rate)) + if (atomMutation(_eo[i])) + modified = true; + + return modified; + } + + /** inherited className() */ + virtual std::string className() const + { + return "eoFlOrAllMutation(" + atomMutation.className() + ")"; + } + +private: + eoMonOp & atomMutation; // the atom mutation + double rate; // the mutation rate PER ATOM +}; + +/** Applies an atomic mutation to a fixed + number of components (1 by default) + */ +template +class eoFlOrKMutation : public eoMonOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires an Atom mutation */ + eoFlOrKMutation(eoMonOp & _atomMutation, unsigned _nb=1) : + nb(_nb), atomMutation(_atomMutation) {} + + + /** applies the atom mutation to K randomly selected components */ + bool operator()(EOT & _eo) + { + bool modified=false; + for (unsigned k=0; k & atomMutation; // the atom mutation +}; + +/** @} */ + +#endif diff --git a/deprecated/eo/src/eoFlOrQuadOp.h b/deprecated/eo/src/eoFlOrQuadOp.h new file mode 100644 index 000000000..91618aa53 --- /dev/null +++ b/deprecated/eo/src/eoFlOrQuadOp.h @@ -0,0 +1,218 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mkeijzer@cs.vu.nl + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFlOrQuadOp_h +#define _eoFlOrQuadOp_h + +#include +#include + +/** @addtogroup Variators + * @{ + */ + +/** Generic eoQuadOps on fixed length genotypes. + * Contains exchange crossovers (1pt and uniform) + * and crossovers that applies an Atom crossover + * to all components with given rate, or + * to a fixed prescribed nb of components +*/ + +////////////////////////////////////////////////////////////////////// +// eoFlOrAllAtomQuadOp +////////////////////////////////////////////////////////////////////// + +/** Quad Crossover using an Atom Crossover + */ +template +class eoFlOrAllAtomQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires an Atom QuadOp */ + eoFlOrAllAtomQuadOp( eoQuadOp& _op, double _rate = 1): + op(_op), rate( _rate ) {} + + /** applies Atom crossover to ALL components with given rate */ + bool operator()(EOT & _eo1, EOT & _eo2) + { + bool changed = false; + for ( unsigned i = 0; i < _eo1.size(); i++ ) { + if ( rng.flip( rate ) ) { + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; + } + } + return changed; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOrAllAtomQuadOp"; } + +private: + double rate; + eoQuadOp & op; +}; + +////////////////////////////////////////////////////////////////////// +// eoFlOrKAtomQuadOp +////////////////////////////////////////////////////////////////////// +/** Quad Crossover using an Atom Crossover + * that is applied to a FIXED NB of components + */ +template +class eoFlOrKAtomQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires an Atom QuadOp and an unsigned */ + eoFlOrAtomQuadOp( eoQuadOp& _op, unsigned _k = 1): + op(_op), k( _k ) {} + + /** applies the Atom QuadOp to some components */ + bool operator()(EOT & _eo1, const EOT & _eo2) + { + if (_eo1.size() != _eo2.size()) + { + 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; + } + return changed; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOrKAtomQuadOp"; } + +private: + unsigned k; + eoQuadOp & op; +}; + + +////////////////////////////////////////////////////////////////////// +// eoFlOrUniformQuadOp +////////////////////////////////////////////////////////////////////// +/** The uniform crossover - exchanges atoms uniformly ! */ +template +class eoFlOrUniformQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires a rate - 0.5 by default */ + eoVlUniformQuadOp(double _rate=0.5) : eoQuadOp(_size), + rate(_rate) {} + + /** excahnges atoms at given rate */ + bool operator()(EOT & _eo1, EOT & _eo2) + { + unsigned i; + Atom tmp; + if (_eo1.size() != _eo2.size()) + { + 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; + } + } + return hasChanged; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOrUniformQuadOp"; } + +private: + double rate; +}; + +////////////////////////////////////////////////////////////////////// +// eoFlOr1ptQuadOp +////////////////////////////////////////////////////////////////////// +/** The 1pt crossover (just in case someone wants it some day!) */ +template +class eoFlOr1ptQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: no argument */ + eoVlUniformQuadOp() {} + + /** exchanges first and second parts of the vectors of Atoms */ + bool operator()(EOT & _eo1, EOT & _eo2) + { + unsigned i; + Atom tmp; + if (_eo1.size() != _eo2.size()) + { + 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; + } + } + return hasChanged; + } + + /** inherited className()*/ + virtual string className() const { return "eoFlOr1ptQuadOp"; } + +}; + +/** @} */ + +#endif diff --git a/deprecated/eo/src/eoFlight.h b/deprecated/eo/src/eoFlight.h new file mode 100644 index 000000000..4c46d8e94 --- /dev/null +++ b/deprecated/eo/src/eoFlight.h @@ -0,0 +1,55 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFlight.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOFLIGHT_H +#define EOFLIGHT_H + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + +/** Abstract class for particle swarm optimization flight. +* All the flights must derivated from eoFlight. +* +* @ingroup Variators +*/ +template < class POT > class eoFlight:public eoUF < POT &, void > +{ +public: + + /** + * Apply the flight to a whole population. + */ + virtual void apply (eoPop < POT > &_pop) + { + for (unsigned i = 0; i < _pop.size (); i++) + { + this->operator ()(_pop[i]); + } + + } +}; + +#endif /*EOFLIGHT_H */ diff --git a/deprecated/eo/src/eoFunctor.h b/deprecated/eo/src/eoFunctor.h new file mode 100644 index 000000000..465f0bc46 --- /dev/null +++ b/deprecated/eo/src/eoFunctor.h @@ -0,0 +1,184 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + 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 $ + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFunctor_h +#define _eoFunctor_h + +#include + +/** @addtogroup Core + * @{ + */ + +/** Base class for functors to get a nice hierarchy diagram + + That's actually quite an understatement as it does quite a bit more than + just that. By having all functors derive from the same base class, we can + do some memory management that would otherwise be very hard. + + The memory management base class is called eoFunctorStore, and it supports + a member add() to add a pointer to a functor. When the functorStore is + destroyed, it will delete all those pointers. So beware: do not delete + the functorStore before you are done with anything that might have been allocated. + + @see eoFunctorStore + +*/ +class eoFunctorBase +{ +public : + /// virtual dtor here so there is no need to define it in derived classes + virtual ~eoFunctorBase() {} + + /// tag to identify a procedure in compile time function selection @see functor_category + struct procedure_tag {}; + /// tag to identify a unary function in compile time function selection @see functor_category + struct unary_function_tag {}; + /// tag to identify a binary function in compile time function selection @see functor_category + struct binary_function_tag {}; +}; +/** @example t-eoFunctor.cpp + */ + +/** + Basic Function. Derive from this class when defining + any procedure. It defines a result_type that can be used + to determine the return type + Argument and result types can be any type including void for + result_type +**/ +template +class eoF : public eoFunctorBase +{ +public : + + /// virtual dtor here so there is no need to define it in derived classes + virtual ~eoF() {} + + /// the return type - probably useless .... + typedef R result_type; + + /// The pure virtual function that needs to be implemented by the subclass + virtual R operator()() = 0; + + /// tag to identify a procedure in compile time function selection @see functor_category + static eoFunctorBase::procedure_tag functor_category() + { + return eoFunctorBase::procedure_tag(); + } +}; + +/** + Overloaded function that can help in the compile time detection + of the type of functor we are dealing with + + @see eoCounter, make_counter +*/ +template +eoFunctorBase::procedure_tag functor_category(const eoF&) +{ + return eoFunctorBase::procedure_tag(); +} + +/** + 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 + result_type +**/ +template +class eoUF : public eoFunctorBase, public std::unary_function +{ +public : + + /// virtual dtor here so there is no need to define it in derived classes + virtual ~eoUF() {} + + /// The pure virtual function that needs to be implemented by the subclass + virtual R operator()(A1) = 0; + + /// 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(); + } +}; + +/** + Overloaded function that can help in the compile time detection + of the type of functor we are dealing with + @see eoCounter, make_counter +*/ +template +eoFunctorBase::unary_function_tag functor_category(const eoUF&) +{ + return eoFunctorBase::unary_function_tag(); +} + + +/** + 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 + result_type +**/ +template +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; + + /// The pure virtual function that needs to be implemented by the subclass + virtual R operator()(A1, A2) = 0; + + /// 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(); + } +}; + +/** + Overloaded function that can help in the compile time detection + of the type of functor we are dealing with + @see eoCounter, make_counter +*/ +template +eoFunctorBase::binary_function_tag functor_category(const eoBF&) +{ + return eoFunctorBase::binary_function_tag(); +} + +/** @} */ + +#endif diff --git a/deprecated/eo/src/eoFunctorStore.cpp b/deprecated/eo/src/eoFunctorStore.cpp new file mode 100644 index 000000000..43cd778cd --- /dev/null +++ b/deprecated/eo/src/eoFunctorStore.cpp @@ -0,0 +1,18 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include + +#include +#include + + +/// clears the memory +eoFunctorStore::~eoFunctorStore() +{ + for( std::size_t i = 0; i < vec.size(); ++i) { + delete vec[i]; + } +} diff --git a/deprecated/eo/src/eoFunctorStore.h b/deprecated/eo/src/eoFunctorStore.h new file mode 100644 index 000000000..c609637b4 --- /dev/null +++ b/deprecated/eo/src/eoFunctorStore.h @@ -0,0 +1,73 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFunctorStore.h +// (c) Maarten Keijzer 2000, GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk +*/ +//----------------------------------------------------------------------------- + +#ifndef _eoFunctorStore_h +#define _eoFunctorStore_h + +#include + +class eoFunctorBase; + +/** + eoFunctorStore is a class that stores functors that are allocated on the + heap. This class can be used in factories to store allocated memory for + dynamically created functors. + + @ingroup Utilities +*/ +class eoFunctorStore +{ +public: + + /// Default Ctor + eoFunctorStore() {} + + // virtual destructor so we don't need to define it in derived classes + virtual ~eoFunctorStore(); + + /// Add an eoFunctorBase to the store + template + Functor& storeFunctor(Functor* r) + { + // If the compiler complains about the following line, + // check if you really are giving it a pointer to an + // eoFunctorBase derived object + vec.push_back(r); + return *r; + } + +private : + + /** no copying allowed */ + eoFunctorStore(const eoFunctorStore&); + + /** no assignment allowed */ + eoFunctorStore operator=(const eoFunctorStore&); + + std::vector vec; +}; + +#endif diff --git a/deprecated/eo/src/eoG3Replacement.h b/deprecated/eo/src/eoG3Replacement.h new file mode 100644 index 000000000..a235244f8 --- /dev/null +++ b/deprecated/eo/src/eoG3Replacement.h @@ -0,0 +1,86 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + 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@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoG3Replacement_h +#define _eoG3Replacement_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** +eoG3Replacement is an eoReplacement: +- no strong elitism (is suppposed to be within a steady-state engine) +- choose N (2) parents RANDOMLY - remove them from the parent population +- merge offspring and the N removed parents +- select best N of this merged population +- put them back into parent population + +@ingroup Replacors +*/ +template +class eoG3Replacement : public eoReplacement +{ +public: + eoG3Replacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false)) : + // split truncates the parents and returns eliminated parents + split(_howManyEliminatedParents, true), + // reduce truncates the offpsring and does not return eliminated guys + 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!) + + // reduce merged + 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"); + } + // and put back into _parents + plus(_offspring, _parents); + } + +private: + eoLinearTruncateSplit split; // few parents to truncate -> linear + eoTruncateSplit reduce; // supposedly many offspring to truncate + eoPlus plus; +}; + +#endif diff --git a/deprecated/eo/src/eoGaussRealWeightUp.h b/deprecated/eo/src/eoGaussRealWeightUp.h new file mode 100644 index 000000000..47edc321b --- /dev/null +++ b/deprecated/eo/src/eoGaussRealWeightUp.h @@ -0,0 +1,71 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGaussRealWeightUp.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOGAUSSREALWEIGHTUP_H +#define EOGAUSSREALWEIGHTUP_H + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + + +/** + * Update an inertia weight by assigning it a Gaussian randomized value + * (used for the velocity in particle swarm optimization). + * + * @ingroup Variators + */ +class eoGaussRealWeightUp:public eoWeightUpdater +{ +public: + + /** + * Default constructor + * @param _mean - Mean for Gaussian distribution + * @param _stdev - Standard deviation for Gaussian distribution + */ + eoGaussRealWeightUp( + double _mean=0, + double _stdev=1.0 + ):mean(_mean),stdev(_stdev){} + + /** + * Assign Gaussian deviation to _weight + * @param _weight - The modified weight as a double + */ + void operator() (double & _weight) + { + _weight=rng.normal(mean,stdev); + } + + +protected: + double mean,stdev; + +}; + + + +#endif/*EOGAUSSREALWEIGHTUP_H*/ diff --git a/deprecated/eo/src/eoGenContinue.h b/deprecated/eo/src/eoGenContinue.h new file mode 100644 index 000000000..0d01bb0a1 --- /dev/null +++ b/deprecated/eo/src/eoGenContinue.h @@ -0,0 +1,114 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoGenContinue_h +#define _eoGenContinue_h + +#include +#include +#include + +/** + Generational continuator: continues until a number of generations is reached + + @ingroup Continuators +*/ +template< class EOT> +class eoGenContinue: public eoContinue, public eoValueParam +{ +public: + + /// Ctor for setting a + eoGenContinue( unsigned long _totalGens) + : 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) + {}; + + /** Returns false when a certain number of generations is + * reached */ + virtual bool operator() ( const eoPop& _vEO ) { + (void)_vEO; + thisGeneration++; + value() = thisGeneration; + + if (thisGeneration >= repTotalGenerations) + { + 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 + */ + virtual void totalGenerations( unsigned long _tg ) { + repTotalGenerations = _tg; + thisGeneration = 0; + }; + + /** Returns the number of generations to reach*/ + 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 */ + } + +private: + unsigned long repTotalGenerations; + unsigned long thisGenerationPlaceHolder; + unsigned long& thisGeneration; +}; + +#endif diff --git a/deprecated/eo/src/eoGenOp.h b/deprecated/eo/src/eoGenOp.h new file mode 100644 index 000000000..f0d70c7ba --- /dev/null +++ b/deprecated/eo/src/eoGenOp.h @@ -0,0 +1,229 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenOp.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 + 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: mak@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoGenOp_H +#define _eoGenOp_H + +#include +#include +#include +#include + +/** @name General variation operators + +a class that allows to use i->j operators for any i and j +thanks to the friend class eoPopulator + +@author Maarten Keijzer +@version 0.0 + +@ingroup Core +@ingroup Variators +*/ + +//@{ + +/** The base class for General Operators +Subclass this operator is you want to define an operator that falls +outside of the eoMonOp, eoBinOp, eoQuadOp classification. The argument +the operator will receive is an eoPopulator, which is a wrapper around +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 +the object if necessary + */ +template +class eoGenOp : public eoOp, public eoUF &, void> +{ + public : + /// Ctor that honors its superclass + eoGenOp(): eoOp( eoOp::general ) {} + + /** 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 std::string className() const = 0; + + void operator()(eoPopulator& _pop) + { + _pop.reserve( max_production() ); + apply(_pop); + } + + //protected : + /** the function that will do the work + */ + virtual void apply(eoPopulator& _pop) = 0; +}; +/** @example t-eoGenOp.cpp + */ + + +/** Wrapper for eoMonOp */ +template +class eoMonGenOp : public eoGenOp +{ + public: + eoMonGenOp(eoMonOp& _op) : op(_op) {} + + unsigned max_production(void) { return 1; } + + void apply(eoPopulator& _it) + { + if (op(*_it)) + (*_it).invalidate(); // look how simple + + } + virtual std::string className() const {return op.className();} + private : + eoMonOp& op; +}; + +/** Wrapper for binop: here we use select method of eoPopulator + * but we could also have an embedded selector to select the second parent + */ +template +class eoBinGenOp : public eoGenOp +{ + public: + eoBinGenOp(eoBinOp& _op) : op(_op) {} + + unsigned max_production(void) { return 1; } + + /** do the work: get 2 individuals from the population, modifies + only one (it's a eoBinOp) + */ + void apply(eoPopulator& _pop) + { + EOT& a = *_pop; + const EOT& b = _pop.select(); + + if (op(a, b)) + a.invalidate(); + } + virtual std::string className() const {return op.className();} + + private : + eoBinOp& op; +}; + +/** wrapper for eoBinOp with a selector */ +template +class eoSelBinGenOp : public eoGenOp +{ + public: + eoSelBinGenOp(eoBinOp& _op, eoSelectOne& _sel) : + op(_op), sel(_sel) {} + + unsigned max_production(void) { return 1; } + + void apply(eoPopulator& _pop) + { // _pop.source() gets the original population, an eoVecOp can make use of this as well + if (op(*_pop, sel(_pop.source()))) + (*_pop).invalidate(); + } + virtual std::string className() const {return op.className();} + + private : + eoBinOp& op; + eoSelectOne& sel; +}; + + +/** Wrapper for quadop: easy as pie + */ +template +class eoQuadGenOp : public eoGenOp +{ + public: + eoQuadGenOp(eoQuadOp& _op) : op(_op) {} + + unsigned max_production(void) { return 2; } + + void apply(eoPopulator& _pop) + { + EOT& a = *_pop; + EOT& b = *++_pop; + + + if(op(a, b)) + { + a.invalidate(); + b.invalidate(); + } + + } + virtual std::string className() const {return op.className();} + + private : + eoQuadOp& op; +}; + + /** + Factory function for automagically creating references to an + eoGenOp object. Useful when you are too lazy to figure out + which wrapper belongs to which operator. The memory allocated + in the wrapper will be stored in a eoFunctorStore (eoState derives from this). + Therefore the memory will only be freed when the eoFunctorStore is deleted. + Make very sure that you are not using these wrappers after this happens. + + You can use this function 'wrap_op' in the following way. Suppose you've + created an eoQuadOp called my_quad, and you want to feed it to an eoTransform + derived class that expects an eoGenOp. If you have an eoState lying around + (which is generally a good idea) you can say: + + eoDerivedTransform trans(eoGenOp::wrap_op(my_quad, state), ...); + + And as long as your state is not destroyed (by going out of scope for example, + your 'trans' functor will be usefull. + + As a final note, you can also enter an eoGenOp as the argument. It will + not allocate memory then. This to make it even easier to use the wrap_op function. + For an example of how this is used, check the eoOpContainer class. + + @see eoOpContainer + */ + template + eoGenOp& wrap_op(eoOp& _op, eoFunctorStore& _store) + { + switch(_op.getType()) + { + case eoOp::unary : return _store.storeFunctor(new eoMonGenOp(static_cast&>(_op))); + case eoOp::binary : return _store.storeFunctor(new eoBinGenOp(static_cast&>(_op))); + case eoOp::quadratic : return _store.storeFunctor(new eoQuadGenOp(static_cast&>(_op))); + case eoOp::general : return static_cast&>(_op); + } + + assert(false); + return static_cast&>(_op); + } + +#endif + +//@} diff --git a/deprecated/eo/src/eoGeneralBreeder.h b/deprecated/eo/src/eoGeneralBreeder.h new file mode 100644 index 000000000..dc598ba7e --- /dev/null +++ b/deprecated/eo/src/eoGeneralBreeder.h @@ -0,0 +1,107 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoGeneralBreeder_h +#define eoGeneralBreeder_h + +//----------------------------------------------------------------------------- + +/***************************************************************************** + * eoGeneralBreeder: transforms a population using the generalOp construct. + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +/** + Base class for breeders using generalized operators. + + @ingroup Combination +*/ +template +class eoGeneralBreeder: public eoBreed +{ + public: + /** Ctor: + * + * @param _select a selectoOne, to be used for all selections + * @param _op a general operator (will generally be an eoOpContainer) + * @param _rate pour howMany, le nbre d'enfants a generer + * @param _interpret_as_rate explanation + */ + eoGeneralBreeder( + eoSelectOne& _select, + eoGenOp& _op, + double _rate=1.0, + bool _interpret_as_rate = true) : + select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {} + + /** Ctor: + * + * @param _select a selectoOne, to be used for all selections + * @param _op a general operator (will generally be an eoOpContainer) + * @param _howMany an eoHowMany explanation + */ + eoGeneralBreeder( + eoSelectOne& _select, + eoGenOp& _op, + eoHowMany _howMany ) : + select( _select ), op(_op), howMany(_howMany) {} + + /** The breeder: simply calls the genOp on a selective populator! + * + * @param _parents the initial population + * @param _offspring the resulting population (content -if any- is lost) + */ + void operator()(const eoPop& _parents, eoPop& _offspring) + { + unsigned target = howMany(_parents.size()); + + _offspring.clear(); + eoSelectivePopulator it(_parents, _offspring, select); + + while (_offspring.size() < target) + { + op(it); + ++it; + } + + _offspring.resize(target); // you might have generated a few more + } + + /// The class name. + virtual std::string className() const { return "eoGeneralBreeder"; } + + private: + eoSelectOne& select; + eoGenOp& op; + eoHowMany howMany; +}; + +#endif diff --git a/deprecated/eo/src/eoInit.h b/deprecated/eo/src/eoInit.h new file mode 100644 index 000000000..7b460d94b --- /dev/null +++ b/deprecated/eo/src/eoInit.h @@ -0,0 +1,214 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoInit.h +// (c) Maarten Keijzer 2000, GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoInit_H +#define _eoInit_H + +#include + +#include +#include +#include +#include // for shuffle method + + +/** + @defgroup Initializators Initialization operators + @ingroup Operators + + Initializators are operators that creates initial individuals and populations. +*/ +/** @{*/ +/** + 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 +*/ +template +class eoInit : public eoUF +{ +public: + + /** 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 + * probably we should only use genrators - and suppress eoInit ??? + * MS - July 2001 + */ +template +class eoInitGenerator : public eoF +{ +public: + + /** Ctor from a plain eoInit */ + eoInitGenerator(eoInit & _init):init(_init) {} + + virtual EOT operator()() + { + EOT p; + init(p); + return (p); + } +private: + eoInit & init; +}; + +/** + Initializer for fixed length representations with a single type +*/ +template +class eoInitFixedLength: public eoInit +{ + public: + + typedef typename EOT::AtomType AtomType; + + eoInitFixedLength(unsigned _combien, eoRndGenerator& _generator) + : combien(_combien), generator(_generator) {} + + virtual void operator()(EOT& chrom) + { + chrom.resize(combien); + std::generate(chrom.begin(), chrom.end(), generator); + chrom.invalidate(); + } + + private : + unsigned combien; + /// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics + eoSTLF generator; +}; + +/** + Initializer for variable length representations with a single type +*/ +template +class eoInitVariableLength: public eoInit +{ +public: +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) +// { +// if (_minSize >= _maxSize) +// throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize"); +// } + + /** Ctor from an eoInit */ + eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoInit & _init) + : offset(_minSize), extent(_maxSize - _minSize), init(_init) + { + if (_minSize >= _maxSize) + throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize"); + } + + + virtual void operator()(EOT& _chrom) + { + _chrom.resize(offset + rng.random(extent)); + typename std::vector::iterator it; + for (it=_chrom.begin(); it<_chrom.end(); it++) + init(*it); + _chrom.invalidate(); + } + + // accessor to the atom initializer (needed by operator constructs sometimes) + eoInit & atomInit() {return init;} + +private : + unsigned offset; + unsigned extent; + eoInit & init; +}; + + +/** + Initializer for permutation (integer-based) representations. +*/ +template +class eoInitPermutation: public eoInit +{ + public: + + typedef typename EOT::AtomType AtomType; + + eoInitPermutation(unsigned _chromSize, unsigned _startFrom=0) + : chromSize(_chromSize), startFrom(_startFrom){} + + virtual void operator()(EOT& chrom) + { + chrom.resize(chromSize); + for(unsigned idx=0;idx gen; +}; +/** @example t-eoInitPermutation.cpp + */ + + +/** + eoInitAdaptor changes the place in the hierarchy + from eoInit to eoMonOp. This is mainly a type conversion, + nothing else + + @see eoInit, eoMonOp +*/ +template +class eoInitAdaptor : public eoMonOp +{ + public : + eoInitAdaptor(eoInit& _init) : init(_init) {} + + bool operator()(EOT& _eot) + { + init(_eot); + return true; + } + private : + + eoInit& init; +}; + +#endif +/** @}*/ diff --git a/deprecated/eo/src/eoInitializer.h b/deprecated/eo/src/eoInitializer.h new file mode 100644 index 000000000..9e5cd5caf --- /dev/null +++ b/deprecated/eo/src/eoInitializer.h @@ -0,0 +1,147 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoInitializer.h +// (c) OPAC Team, INRIA, 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 + 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: clive.canape@inria.fr + + + */ +//----------------------------------------------------------------------------- + +#ifndef _eoInitializer_H +#define _eoInitializer_H + +#include +#include +#include +#include +#include + +/** + @addtogroup Initializators + @{ + */ + + +/** + * Abstract class for initialization of algorithm PSO + */ +template class eoInitializerBase : public eoFunctorBase +{ +public : + + virtual ~eoInitializerBase() + {} + + virtual void operator()() + {}; +}; + +/** + Base (name) class for Initialization of algorithm PSO + + @see eoInitializerBase eoUF apply +*/ +template class eoInitializer : public eoInitializerBase +{ +public: + + //! Constructor + //! @param _proc Evaluation function + //! @param _initVelo Initialization of the velocity + //! @param _initBest Initialization of the best + //! @param _topology the topology to use + //! @param _pop Population + eoInitializer( + eoUF& _proc, + eoVelocityInit < POT > &_initVelo, + eoParticleBestInit &_initBest, + eoTopology &_topology, + eoPop < POT > &_pop + ) : proc(_proc), initVelo(_initVelo), procPara(dummyEval), initBest(_initBest), topology(_topology), pop(_pop) + {} + + //! Constructor for parallel evaluation + //! @param _proc Evaluation function + //! @param _initVelo Initialization of the velocity + //! @param _initBest Initialization of the best + //! @param _topology the topology to use + //! @param _pop Population + eoInitializer( + eoPopEvalFunc & _proc, + eoVelocityInit < POT > &_initVelo, + eoParticleBestInit &_initBest, + eoTopology &_topology, + eoPop < POT > &_pop + ) : proc(dummy), initVelo(_initVelo), procPara(_proc), initBest(_initBest), topology(_topology), pop(_pop) + {} + + + //! Give the name of the class + //! @return The name of the class + virtual std::string className (void) const + { + return "eoInitializer"; + } + + + + virtual void operator() () + { + eoPop empty_pop; + apply(proc, pop); + procPara(empty_pop, pop); + apply < POT > (initVelo, pop); + apply < POT > (initBest, pop); + topology.setup(pop); + } + +private : + + /* + @param proc First evaluation + @param initVelo Initialization of the velocity + @param initBest Initialization of the best + */ + eoUF& proc; + eoVelocityInit < POT > & initVelo; + eoPopEvalFunc & procPara; + eoParticleBestInit & initBest; + eoTopology & topology; + eoPop < POT > & pop; + +class eoDummyEval : public eoPopEvalFunc + { + public: + void operator()(eoPop &,eoPop &/*_pop*/) + {} + } + dummyEval; +class eoDummy : public eoUF + { + public: + void operator()(POT &) + {} + + } + dummy; +}; +#endif + +/** @} */ diff --git a/deprecated/eo/src/eoInt.h b/deprecated/eo/src/eoInt.h new file mode 100644 index 000000000..41c877247 --- /dev/null +++ b/deprecated/eo/src/eoInt.h @@ -0,0 +1,63 @@ +/* + eoInt.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: thomas.legrand@lifl.fr + todos@geneura.ugr.es, http://geneura.ugr.es + mkeijzer@dhi.dk +*/ + +#ifndef eoInt_h +#define eoInt_h + +//----------------------------------------------------------------------------- + +#include // std::ostream, std::istream +#include // std::string + +#include + +/** eoInt: implementation of simple integer-valued chromosome. + * based on eoVector class + * + * @ingroup Representations +*/ +template class eoInt: public eoVector +{ + public: + + /** + * (Default) Constructor. + * @param size Size of the std::vector + * @param value fill the vector with this value + */ + eoInt(unsigned size = 0, int value = 0): + eoVector(size, value) {} + + /// My class name. + virtual std::string className() const + { + return "eoInt"; + } + +}; +/** @example t-eoInt.cpp + */ + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/eoIntegerVelocity.h b/deprecated/eo/src/eoIntegerVelocity.h new file mode 100644 index 000000000..b00b17bf3 --- /dev/null +++ b/deprecated/eo/src/eoIntegerVelocity.h @@ -0,0 +1,195 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoIntegerVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOINTEGERVELOCITY_H +#define EOINTEGERVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + +/** Integer velocity performer for particle swarm optimization. Derivated from abstract eoVelocity, +* At step t: v(t+1)= c1 * v(t) + c2 * r2 * ( xbest(t)-x(t) ) + c3 * r3 * ( gbest(t) - x(t) ) +* v(t) is an INT for any time step +* (ci given and Ri chosen at random in [0;1]). +* +* @ingroup Variators +*/ +template < class POT > class eoIntegerVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** 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. + * 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 & _c2, + const VelocityType & _c3, + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + c1 (_c1), + c2 (_c2), + c3 (_c3), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** 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. + * 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 + */ + eoIntegerVelocity (eoTopology < POT > & _topology, + const VelocityType & _c1, + const VelocityType & _c2, + const VelocityType & _c3, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + c1 (_c1), + c2 (_c2), + c3 (_c3), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _gen - The eo random generator, default=rng + */ + eoIntegerVelocity (eoTopology < POT > & _topology, + const VelocityType & _c1, + const VelocityType & _c2, + const VelocityType & _c3, + eoRng & _gen = rng): + topology(_topology), + c1 (_c1), + c2 (_c2), + c3 (_c3), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen) + {} + + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * into the topology. + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r2; + VelocityType r3; + + VelocityType newVelocity; + + // cast the learning factors to VelocityType + r2 = (VelocityType) rng.uniform (1) * c2; + 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= round (c1 * _po.velocities[j] + r2 * (_po.bestPositions[j] - _po[j]) + r3 * (topology.best (_indice)[j] - _po[j])); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + //! 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; + + 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/deprecated/eo/src/eoInvalidateOps.h b/deprecated/eo/src/eoInvalidateOps.h new file mode 100644 index 000000000..97dd39f55 --- /dev/null +++ b/deprecated/eo/src/eoInvalidateOps.h @@ -0,0 +1,135 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoInvalidateOps.h +// (c) 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoInvalidateOps_h +#define _eoInvalidateOps_h + +#include + +/** @addtogroup Utilities + +One of the invalidator operators. Use this one as a 'hat' on an operator +that is defined to work on a generic datatype. This functor will then check +the return type of the operator and invalidate the fitness of the individual. + +This functor is used in algorithms that work with straight eoMonOp, eoBinOp +or eoQuadOp operators, for instance eoSGA. Note that eoGenOp derived operators +generally do invalidate the fitness of the objects they have changed. + +Return value means "Has_Changed" and not "Needs_To_Be_Invalidated" +as successive invalidation are not really a problem +*/ + +template +class eoInvalidateMonOp : public eoMonOp +{ + public: + eoInvalidateMonOp(eoMonOp& _op) : op(_op) {} + + bool operator()(EOT& _eo) + { + if (op(_eo)) + { + _eo.invalidate(); + return true; + } + + return false; + } + + private: + eoMonOp& op; +}; + +/** +One of the invalidator operators. Use this one as a 'hat' on an operator +that is defined to work on a generic datatype. This functor will then check +the return type of the operator and invalidate the fitness of the individual. + +This functor is used in algorithms that work with straight eoMonOp, eoBinOp +or eoQuadOp operators, for instance eoSGA. Note that eoGenOp derived operators +generally do invalidate the fitness of the objects they have changed. + +Return value means "Has_Changed" and not "Needs_To_Be_Invalidated" +as successive invalidation are not really a problem +*/ + +template +class eoInvalidateBinOp : public eoBinOp +{ + public: + eoInvalidateBinOp(eoBinOp& _op) : op(_op) {} + + bool operator()(EOT& _eo, const EOT& _eo2) + { + if (op(_eo, _eo2)) + { + _eo.invalidate(); + return true; + } + + return false; + } + + private: + eoBinOp& op; +}; + +/** +One of the invalidator operators. Use this one as a 'hat' on an operator +that is defined to work on a generic datatype. This functor will then check +the return type of the operator and invalidate the fitness of the individual. + +This functor is used in algorithms that work with straight eoMonOp, eoBinOp +or eoQuadOp operators, for instance eoSGA. Note that eoGenOp derived operators +generally do invalidate the fitness of the objects they have changed. + +Return value means "Has_Changed" and not "Needs_To_Be_Invalidated" +as successive invalidation are not really a problem +*/ + +template +class eoInvalidateQuadOp : public eoQuadOp +{ + public: + eoInvalidateQuadOp(eoQuadOp& _op) : op(_op) {} + + bool operator()(EOT& _eo1, EOT& _eo2) + { + if (op(_eo1, _eo2)) + { + _eo1.invalidate(); + _eo2.invalidate(); + return true; + } + return false; + } + + private: + eoQuadOp& op; +}; + +#endif diff --git a/deprecated/eo/src/eoLinearDecreasingWeightUp.h b/deprecated/eo/src/eoLinearDecreasingWeightUp.h new file mode 100644 index 000000000..87f489423 --- /dev/null +++ b/deprecated/eo/src/eoLinearDecreasingWeightUp.h @@ -0,0 +1,77 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoLinearDecreasingWeightUp.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOLINEARDECREASINGWEIGHTUP_H +#define EOLINEARDECREASINGWEIGHTUP_H + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + + +/** + * Linear (inertia) weight updater for particle swarm optimization. Update a weight according to: + * w(t)=(w(0)-w(Nt))*(Nt -t)/Nt + w(Nt) where + * t is the current generation/event + * Nt is the total number of generations/event + * w(0) is the initial weight + * w(Nt) is the last inertia weight + * + * @ingroup Variators + */ +template class eoLinearDecreasingWeightUp:public eoWeightUpdater +{ +public: + + /** + * Ctor + */ + eoLinearDecreasingWeightUp( + const StopCriteriaType & _stop, + const WeightType & _initialValue, + const WeightType & _finalValue, + eoValueParam & _counter): + stop(_stop), + initialValue(_initialValue), + finalValue(_finalValue), + counter(_counter){} + + /** + * Update the given weight + */ + void operator() (WeightType & _weight) + { + _weight=(initialValue-finalValue)* (WeightType)(stop-counter.value())/(WeightType)stop + finalValue; + + } + +protected: + const StopCriteriaType & stop; + const WeightType & initialValue,finalValue; + eoValueParam & counter; // a counter of the number of past events (should say "generations") +}; + + + +#endif/*EOLINEARDECREASINGWEIGHTUP_H*/ diff --git a/deprecated/eo/src/eoLinearFitScaling.h b/deprecated/eo/src/eoLinearFitScaling.h new file mode 100644 index 000000000..75598c934 --- /dev/null +++ b/deprecated/eo/src/eoLinearFitScaling.h @@ -0,0 +1,94 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoLinearFitScaling.h + (c) GeNeura Team, 1998, Maarten Keijzer, Marc Schoenauer, 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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 + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoLinearFitScaling_h +#define eoLinearFitScaling_h + +#include +#include + +/** An instance of eoPerf2Worth + * COmputes the linearly scaled fitnesses + * with given selective pressure + * Pselect(Best) == pressure/sizePop + * Pselect(average) == 1.0/sizePop + * truncate negative values to 0 - + * + * to be used within an eoSelectFromWorth object + * + * @ingroup Selectors + */ +template +class eoLinearFitScaling : public eoPerf2Worth // false: do not cache fitness +{ +public: + + using eoPerf2Worth::value; + + /* Ctor: + @param _p selective pressure (in (1,2]) + @param _e exponent (1 == linear) + */ + eoLinearFitScaling(double _p=2.0) + : pressure(_p) {} + + /* COmputes the ranked fitness: fitnesses range in [m,M] + with m=2-pressure/popSize and M=pressure/popSize. + in between, the progression depends on exponent (linear if 1). + */ + virtual void operator()(const eoPop& _pop) { + unsigned pSize =_pop.size(); + // value() refers to the vector of worthes (we're in an eoParamvalue) + value().resize(pSize); + + // best and worse fitnesses + double bestFitness = static_cast (_pop.best_element().fitness()); + // double worstFitness = static_cast (_pop.worse_element().fitness()); + + // average fitness + double sum=0.0; + unsigned i; + for (i=0; i(_pop[i].fitness()); + double averageFitness = sum/pSize; + + // the coefficients for linear scaling + double denom = pSize*(bestFitness - averageFitness); + double alpha = (pressure-1)/denom; + double beta = (bestFitness - pressure*averageFitness)/denom; + + for (i=0; i +#include +#include +//----------------------------------------------------------------------------- + + +/** + * One of the local best strategies for particle swarm optimization. Each particle has a fixed number of neighbours, ans + * the neighborhood is social. + * The topology is never modified during the flight. + * + * @ingroup Selectors + */ +template < class POT > class eoLinearTopology:public eoTopology < + POT > +{ + +public: + + /** + * Build the topology made of _neighborhoodSize neighborhoods. + * @param _neighborhoodSize - The size of each neighborhood. + */ + eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} + + + /** + * Build the neighborhoods contained in the topology. + * @param _pop - The population used to build the neighborhoods. + * If it remains several particle (because _pop.size()%neighborhoodSize !=0), there are inserted + * in the last neighborhood. So it may be possible to have a bigger neighborhood. + */ + void setup(const eoPop & _pop) + { + if (!isSetup) + { + // consitency check + if (neighborhoodSize >= _pop.size()){ + std::string s; + s.append (" Invalid neighborhood size in eoLinearTopology "); + throw std::runtime_error (s); + } + + unsigned howManyNeighborhood=_pop.size()/ neighborhoodSize; + + // build all the neighborhoods + for (unsigned i=0;i< howManyNeighborhood;i++) + { + eoSocialNeighborhood currentNghd; + + currentNghd.best(_pop[i*neighborhoodSize]); + for (unsigned k=i*neighborhoodSize;k < neighborhoodSize*(i+1);k++) + { + currentNghd.put(k); + if (_pop[k].fitness() > currentNghd.best().fitness()) + currentNghd.best(_pop[k]); + } + neighborhoods.push_back(currentNghd); + } + + // assign the last neighborhood to the remaining particles + if (_pop.size()%neighborhoodSize !=0) + { + for (unsigned z=_pop.size()-1;z >= (_pop.size()-_pop.size()%neighborhoodSize);z--){ + neighborhoods.back().put(z); + + if (_pop[z].fitness() > neighborhoods.back().best().fitness()) + neighborhoods.back().best(_pop[z]); + } + } + + isSetup=true; + } + else + { + // Should activate this part ? + /* + std::string s; + s.append (" Linear topology already setup in eoLinearTopology"); + throw std::runtime_error (s); + */ + } + + } + + + /** + * Retrieve the neighboorhood of a particle. + * @return _indice - The particle indice (in the population) + */ + unsigned retrieveNeighborhoodByIndice(unsigned _indice) + { + unsigned i=0; + for (i=0;i< neighborhoods.size();i++) + { + if (neighborhoods[i].contains(_indice)) + { + return i; + } + } + return i; + } + + /** + * Update the neighborhood: update the particle's best fitness and the best particle + * of the corresponding neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + // 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]; + } + + // update the best in its neighborhood + unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); + if (_po.fitness() > neighborhoods[theGoodNhbd].best().fitness()) + { + neighborhoods[theGoodNhbd].best(_po); + } + } + + /** + * Return the best informative of a particle. Could be itself. + * @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) + { + unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); + + return (neighborhoods[theGoodNhbd].best()); + } + + + /* + * 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; // the size of each neighborhood + + bool isSetup; + +}; + +#endif /*EOLINEARTOPOLOGY_H_ */ diff --git a/deprecated/eo/src/eoMGGReplacement.h b/deprecated/eo/src/eoMGGReplacement.h new file mode 100644 index 000000000..e2eebbfa5 --- /dev/null +++ b/deprecated/eo/src/eoMGGReplacement.h @@ -0,0 +1,104 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + 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@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoMGGReplacement_h +#define _eoMGGReplacement_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** +eoMGGReplacement is an eoReplacement: +- choose N (2) parents RANDOMLY - remove them from the parent population +- select best offspring, add to parents +- merge (other?) offspring and the N removed parents +- select best N-1 of this merged population (detTournament only at the moment) +- put them back into parent population + +@ingroup Replacors +*/ + +template +class eoMGGReplacement : public eoReplacement +{ +public: + eoMGGReplacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false), + unsigned _tSize=2) : + // split truncates the parents and returns eliminated parents + split(_howManyEliminatedParents, true), + tSize(_tSize) + { + if (tSize < 2) + { + eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; + tSize = 2; + } + } + + void operator()(eoPop & _parents, eoPop & _offspring) + { + eoPop temp; + split(_parents, temp); + 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"); + + // select best offspring + typename eoPop::iterator it = _offspring.it_best_element(); + // add to parents + _parents.push_back(*it); + // remove from offspring + _offspring.erase(it); + + // merge temp into offspring + plus(temp, _offspring); + + // repeatedly add selected offspring to parents + for (unsigned i=0; i split; // few parents to truncate -> linear + eoPlus plus; + unsigned int tSize; +}; + +#endif diff --git a/deprecated/eo/src/eoMerge.h b/deprecated/eo/src/eoMerge.h new file mode 100644 index 000000000..31da70f08 --- /dev/null +++ b/deprecated/eo/src/eoMerge.h @@ -0,0 +1,142 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoMerge_h +#define eoMerge_h + +//----------------------------------------------------------------------------- + +#include + +// EO includes +#include // eoPop +#include // eoMerge +#include + +/** + * 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 + * two populations into one (the second argument). + * Note that the algorithms assume that the second argument denotes the + * next generation. + * + * @ingroup Core + * @ingroup Replacors +*/ + +template class eoMerge: public eoBF&, eoPop&, void> +{}; + +/** +Straightforward elitism class, specify the number of individuals to copy +into new geneneration or the rate w.r.t. pop size + +@ingroup Replacors +*/ +template class eoElitism : public eoMerge +{ +public : + eoElitism(double _rate, bool _interpret_as_rate = true): + rate(0), combien(0) + { + if (_interpret_as_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; + } + } + + void operator()(const eoPop& _pop, eoPop& _offspring) + { + if ((combien == 0) && (rate == 0.0)) + return; + unsigned combienLocal; + 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]); + } + } + +private : + double rate; + unsigned combien; +}; + +/** +No elite +@ingroup Replacors +*/ +template class eoNoElitism : public eoElitism +{ + public : + eoNoElitism() : eoElitism(0) {} +}; + +/** +Very elitist class, copies entire population into next gen +@ingroup Replacors +*/ +template class eoPlus : public eoMerge +{ + public : + void operator()(const eoPop& _pop, eoPop& _offspring) + { + _offspring.reserve(_offspring.size() + _pop.size()); + + for (size_t i = 0; i < _pop.size(); ++i) + { + _offspring.push_back(_pop[i]); + } + } + + private : +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/eoMergeReduce.h b/deprecated/eo/src/eoMergeReduce.h new file mode 100644 index 000000000..b3cb5b990 --- /dev/null +++ b/deprecated/eo/src/eoMergeReduce.h @@ -0,0 +1,119 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoMergeReduce_h +#define _eoMergeReduce_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- +/** +Replacement strategies that combine en eoMerge and an eoReduce. + +@class eoMergeReduce, the base (pure abstract) class +@class eoPlusReplacement the ES plus strategy +@class eoCommaReplacement the ES comma strategy +*/ + +/** +eoMergeReduce: abstract replacement strategy that is just an application of +an embedded merge, followed by an embedded reduce +@ingroup Replacors +*/ +template +class eoMergeReduce : public eoReplacement +{ + public: + eoMergeReduce(eoMerge& _merge, eoReduce& _reduce) : + merge(_merge), reduce(_reduce) + {} + + void operator()(eoPop& _parents, eoPop& _offspring) + { + merge(_parents, _offspring); // parents untouched, result in offspring + reduce(_offspring, _parents.size()); + _parents.swap(_offspring); + } + + private : + eoMerge& merge; + eoReduce& reduce; +}; + +/** +ES type of replacement strategy: first add parents to population, then truncate +@ingroup Replacors +*/ +template +class eoPlusReplacement : public eoMergeReduce +{ + public : + eoPlusReplacement() : eoMergeReduce(plus, truncate) {} + + private : + eoPlus plus; + eoTruncate truncate; +}; + +/** +ES type of replacement strategy: ignore parents, truncate offspring +@ingroup Replacors +*/ +template +class eoCommaReplacement : public eoMergeReduce +{ + public : + eoCommaReplacement() : eoMergeReduce(no_elite, truncate) {} + + private : + eoNoElitism no_elite; + eoTruncate truncate; +}; + +/** +EP type of replacement strategy: first add parents to population, + then truncate using EP tournament +@ingroup Replacors +*/ +template +class eoEPReplacement : public eoMergeReduce +{ +public : + eoEPReplacement(int _tSize) : eoMergeReduce(plus, truncate), truncate(_tSize) + // {truncate.setSize(_tSize);} + {} +private : + eoPlus plus; + eoEPReduce truncate; +}; + + + +#endif diff --git a/deprecated/eo/src/eoNDSorting.h b/deprecated/eo/src/eoNDSorting.h new file mode 100644 index 000000000..6ab86c177 --- /dev/null +++ b/deprecated/eo/src/eoNDSorting.h @@ -0,0 +1,496 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoNDSorting.h + (c) Maarten Keijzer, Marc Schoenauer, 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoNDSorting_h +#define eoNDSorting_h + +#include +#include +#include +#include +#include + +/** + Non dominated sorting, it *is a* std::vector of doubles, the integer part is the rank (to which front it belongs), + the fractional part the niching penalty or distance penalty or whatever penalty you want to squeeze into + the bits. +*/ +template +class eoNDSorting : public eoPerf2WorthCached +{ + public : + + using eoPerf2WorthCached::value; + eoNDSorting(bool nasty_flag_ = false) + : nasty_declone_flag_that_only_is_implemented_for_two_objectives(nasty_flag_) + {} + + + eoNDSorting() + : nasty_declone_flag_that_only_is_implemented_for_two_objectives(false) + {} + + /** Pure virtual function that calculates the 'distance' for each element in the current front + Implement to create your own nondominated sorting algorithm. The size of the returned std::vector + should be equal to the size of the current_front. + */ + virtual std::vector niche_penalty(const std::vector& current_front, const eoPop& _pop) = 0; + + void calculate_worths(const eoPop& _pop) + { + // resize the worths beforehand + value().resize(_pop.size()); + + 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); + } + } + } + +private : + + /** used in fast nondominated sorting + DummyEO is just a storage place for fitnesses and + to store the original index + */ + class DummyEO : public EO + { + public: unsigned index; + }; + + void one_objective(const eoPop& _pop) + { + unsigned i; + std::vector tmp_pop; + tmp_pop.resize(_pop.size()); + + // copy pop to dummy population (only need the fitnesses) + for (i = 0; i < _pop.size(); ++i) + { + tmp_pop[i].fitness(_pop[i].fitness()); + tmp_pop[i].index = i; + } + + 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 + } + + /** + * Optimization for two objectives. Makes the algorithm run in + * complexity O(n log n) where n is the population size + * + * This is the same complexity as for a single objective + * or truncation selection or sorting. + * + * It will perform a sort on the two objectives seperately, + * and from the information on the ranks of the individuals on + * these two objectives, the non-dominated sorting rank is determined. + * There are then three nlogn operations in place: one sort per objective, + * plus a binary search procedure to combine the information about the + * ranks. + * + * After that it is a simple exercise to calculate the distance + * penalty + */ + + void two_objectives(const eoPop& _pop) + { + 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 + + for (i = 0; i < _pop.size(); ++i) + { + sort1[i] = i; + } + + std::sort(sort1.begin(), sort1.end(), Sorter(_pop)); + + // Ok, now the meat of the algorithm + + unsigned last_front = 0; + + double max1 = -1e+20; + for (i = 0; i < _pop.size(); ++i) + { + max1 = std::max(max1, _pop[i].fitness()[1]); + } + + max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound + + unsigned prev_front = 0; + std::vector d; + d.resize(_pop.size(), max1); // initialize with the value max1 everywhere + + std::vector > fronts(_pop.size()); // to store indices into the front + + for (i = 0; i < _pop.size(); ++i) + { + unsigned index = sort1[i]; + + // check for clones and delete them + 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; + } + } + + double value2 = _pop[index].fitness()[1]; + + if (traits::maximizing(1)) + value2 = max1 - value2; + + // perform binary search using std::upper_bound, a log n operation for each member + std::vector::iterator it = + std::upper_bound(d.begin(), d.begin() + last_front, value2); + + unsigned front = unsigned(it - d.begin()); + if (front == last_front) ++last_front; + + assert(it != d.end()); + + *it = value2; //update d + fronts[front].push_back(index); // add it to the front + + prev_front = front; + } + + // ok, and finally the niche penalty + + for (i = 0; i < fronts.size(); ++i) + { + if (fronts[i].size() == 0) continue; + + // 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"); + } + + 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 + } + + } + + // invert ranks to obtain a 'bigger is better' score + rank_to_worth(); + } + + class Sorter + { + public: + Sorter(const eoPop& _pop) : pop(_pop) {} + + bool operator()(unsigned i, unsigned j) const + { + typedef typename EOT::Fitness::fitness_traits traits; + + double diff = pop[i].fitness()[0] - pop[j].fitness()[0]; + + if (fabs(diff) < traits::tol()) + { + diff = pop[i].fitness()[1] - pop[j].fitness()[1]; + + if (fabs(diff) < traits::tol()) + return false; + + if (traits::maximizing(1)) + return diff > 0.; + return diff < 0.; + } + + if (traits::maximizing(0)) + return diff > 0.; + return diff < 0.; + } + + const eoPop& pop; + }; + + void m_objectives(const eoPop& _pop) + { + unsigned i; + + typedef typename EOT::Fitness::fitness_traits traits; + + std::vector > S(_pop.size()); // which individuals does guy i dominate + std::vector n(_pop.size(), 0); // how many individuals dominate guy i + + unsigned j; + for (i = 0; i < _pop.size(); ++i) + { + for (j = 0; j < _pop.size(); ++j) + { + if (_pop[i].fitness().dominates(_pop[j].fitness())) + { // i dominates j + S[i].push_back(j); // add j to i's domination std::list + + //n[j]++; // as i dominates j + } + else if (_pop[j].fitness().dominates(_pop[i].fitness())) + { // j dominates i, increment count for i, add i to the domination std::list of j + n[i]++; + + //S[j].push_back(i); + } + } + } + + std::vector current_front; + current_front.reserve(_pop.size()); + + // get the first front out + for (i = 0; i < _pop.size(); ++i) + { + if (n[i] == 0) + { + current_front.push_back(i); + } + } + + std::vector next_front; + next_front.reserve(_pop.size()); + + unsigned front_index = 0; // which front are we processing + while (!current_front.empty()) + { + // Now we have the indices to the current front in current_front, do the niching + std::vector niche_count = niche_penalty(current_front, _pop); + + // Check whether the derived class was nice + if (niche_count.size() != current_front.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()); + + for (i = 0; i < current_front.size(); ++i) + { + value()[current_front[i]] = front_index + niche_count[i] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next + } + + // Calculate which individuals are in the next front; + + for (i = 0; i < current_front.size(); ++i) + { + for (j = 0; j < S[current_front[i]].size(); ++j) + { + unsigned dominated_individual = S[current_front[i]][j]; + n[dominated_individual]--; // As we remove individual i -- being part of the current front -- it no longer dominates j + + if (n[dominated_individual] == 0) // it should be in the current front + { + next_front.push_back(dominated_individual); + } + } + } + + front_index++; // go to the next front + swap(current_front, next_front); // make the next front current + next_front.clear(); // clear it for the next iteration + } + + rank_to_worth(); + } + + void rank_to_worth() + { + // now all that's left to do is to transform lower rank into higher worth + double max_fitness = *std::max_element(value().begin(), value().end()); + + // but make sure it's an integer upper bound, so that all ranks inside the highest integer are the front + max_fitness = ceil(max_fitness); + + for (unsigned i = 0; i < value().size(); ++i) + { + value()[i] = max_fitness - value()[i]; + } + + } + public : bool nasty_declone_flag_that_only_is_implemented_for_two_objectives; +}; + +/** + The original Non Dominated Sorting algorithm from Srinivas and Deb +*/ +template +class eoNDSorting_I : public eoNDSorting +{ +public : + eoNDSorting_I(double _nicheSize, bool nasty_flag_ = false) : eoNDSorting(nasty_flag_), nicheSize(_nicheSize) {} + + std::vector niche_penalty(const std::vector& current_front, const eoPop& _pop) + { + std::vector niche_count(current_front.size(), 0.); + + for (unsigned i = 0; i < current_front.size(); ++i) + { // calculate whether the other points lie within the nice + for (unsigned j = 0; j < current_front.size(); ++j) + { + if (i == j) + continue; + + double dist = 0.0; + + for (unsigned k = 0; k < _pop[current_front[j]].fitness().size(); ++k) + { + double d = _pop[current_front[i]].fitness()[k] - _pop[current_front[j]].fitness()[k]; + dist += d*d; + } + + if (dist < nicheSize) + { + niche_count[i] += 1.0 - pow(dist / nicheSize,2.); + } + } + } + + return niche_count; + } + + private : + + double nicheSize; +}; + +/** @brief Fast Elitist Non-Dominant Sorting Genetic Algorithm + + Adapted from Deb, Agrawal, Pratab and Meyarivan: A Fast Elitist + Non-Dominant Sorting Genetic Algorithm for MultiObjective + Optimization: NSGA-II KanGAL Report No. 200001 + + Note that this class does not do the sorting per se, but the sorting + of it worth_std::vector will give the right order + + The crowding distance is calculated as the sum of the distances to + the nearest neighbours. As we need to return the penalty value, we + have to invert that and invert it again in the base class, but such + is life, sigh +*/ +template +class eoNDSorting_II : public eoNDSorting +{ + public: + + eoNDSorting_II(bool nasty_flag_ = false) : eoNDSorting(nasty_flag_) {} + + typedef std::pair double_index_pair; + + class compare_nodes + { + public : + bool operator()(const double_index_pair& a, const double_index_pair& b) const + { + return a.first < b.first; + } + }; + + /// _cf points into the elements that consist of the current front + std::vector niche_penalty(const std::vector& _cf, const eoPop& _pop) + { + typedef typename EOT::Fitness::fitness_traits traits; + unsigned i; + std::vector niche_count(_cf.size(), 0.); + + + unsigned nObjectives = traits::nObjectives(); //_pop[_cf[0]].fitness().size(); + + for (unsigned o = 0; o < nObjectives; ++o) + { + + std::vector > performance(_cf.size()); + for (i =0; i < _cf.size(); ++i) + { + performance[i].first = _pop[_cf[i]].fitness()[o]; + performance[i].second = i; + } + + std::sort(performance.begin(), performance.end(), compare_nodes()); // a lambda operator would've been nice here + + std::vector nc(niche_count.size(), 0.0); + + for (i = 1; i < _cf.size()-1; ++i) + { // calculate distance + nc[performance[i].second] = performance[i+1].first - performance[i-1].first; + } + + double max_dist = *std::max_element(nc.begin(), nc.end()); + + // set boundary at max_dist + 1 (so it will get chosen over all the others + nc[performance[0].second] += max_dist + 1; + nc[performance.back().second] += max_dist + 1; + + for (i = 0; i < nc.size(); ++i) + { + niche_count[i] += (max_dist + 1 - nc[i]); + } + } + + return niche_count; + } +}; + +#endif diff --git a/deprecated/eo/src/eoNeighborhood.h b/deprecated/eo/src/eoNeighborhood.h new file mode 100644 index 000000000..804dc1075 --- /dev/null +++ b/deprecated/eo/src/eoNeighborhood.h @@ -0,0 +1,57 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoNeighborhood.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EONEIGHBORHOOD_H_ +#define EONEIGHBORHOOD_H_ + + +/** + * Abstract class for neighborboods. Used for particle swarm optimization + * topology strategies. Can be social or physical. + * + * @ingroup Selectors + */ +template < class POT > class eoNeighborhood +{ +public: + + virtual void put(unsigned _oneIndice)=0; + + virtual bool contains(unsigned _oneIndice)=0; + + virtual unsigned size()=0; + + virtual unsigned get(unsigned _index)=0; + + virtual POT & best()=0; + + virtual void best(POT _particle)=0; + + /// Virtual dtor + virtual ~eoNeighborhood() {}; + +}; + + +#endif /* EONEIGHBORHOOD_H_ */ diff --git a/deprecated/eo/src/eoObject.h b/deprecated/eo/src/eoObject.h new file mode 100644 index 000000000..bac2f4737 --- /dev/null +++ b/deprecated/eo/src/eoObject.h @@ -0,0 +1,75 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoObject.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOOBJECT_H +#define EOOBJECT_H + +//----------------------------------------------------------------------------- + +#include // For limits definition +#include // std::istream, std::ostream +#include // std::string + +#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. + +Previously, this object also defined a print and read +interface, but its been moved to eoPrintable and eoPersistent. +*/ + +/** Defines a name (#className#), used when loading or saving a state. + +It is recommended that you only derive from eoObject in concrete classes. +Some parts of EO do not implement this yet, but that will change in the future. +eoObject, together with eoPersistent and eoPrintable provide a simple persistence +framework that is only needed when the classes have state that changes at runtime. + + @see eoPersistent eoPrintable, eoState + + @ingroup Core + */ +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. + 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 + className (like classname), which would print eoObject instead of + their own. Having it pure will force the implementor to provide a + name. + */ + virtual std::string className() const = 0; + +}; + +#endif diff --git a/deprecated/eo/src/eoOneToOneBreeder.h b/deprecated/eo/src/eoOneToOneBreeder.h new file mode 100644 index 000000000..a4c18c0b4 --- /dev/null +++ b/deprecated/eo/src/eoOneToOneBreeder.h @@ -0,0 +1,121 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoOneToOneBreeder_h +#define eoOneToOneBreeder_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** 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 + * G3 can be built on this + * + * @ingroup Combination + */ +template +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 _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 ), + pReplace(_pReplace), howMany(_howMany) {} + + + /** The breeder: iteratively calls the genOp ONCE on a selective populator + * after having recorded the parent + * Then does the replacement + * + * @param _parents the initial population + * @param _offspring the resulting population (content -if any- is lost) + */ + 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; + } + } + + /// The class name. + virtual std::string className() const { return "eoOneToOneBreeder"; } + + private: + eoGenOp& op; + eoEvalFunc & eval; + eoSequentialSelect select; + double pReplace; + eoHowMany howMany; +}; + +#endif diff --git a/deprecated/eo/src/eoOp.h b/deprecated/eo/src/eoOp.h new file mode 100644 index 000000000..b6ad783c2 --- /dev/null +++ b/deprecated/eo/src/eoOp.h @@ -0,0 +1,189 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +//----------------------------------------------------------------------------- +// eoOp.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + 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 $ + */ +//----------------------------------------------------------------------------- + +#ifndef _eoOp_H +#define _eoOp_H + +#include +#include +#include +#include + +/** +@defgroup Operators Evolutionary Operators + +in EO, an operator is any functors that modifies objects and inherits from an eoOp. + +Typically, a mutation is an operator that modifies an individual, and an algorithm is an operator that modifies a population. + +In EO, there is a genetic operator hierarchy, with eoOp as father and +eoMonOp (monary or unary operator), eoBinOp and eoQuadOp (binary operators) +and eoGenOp (any number of inputs and outputs, see eoGenOp.h) +as subclasses. +Nobody should subclass eoOp, you should subclass eoGenOp, eoBinOp, eoQuadOp +or eoMonOp, those are the ones actually used here. + +#eoOp#s are only printable objects, so if you want to build them +from a file, it has to be done in another class, namely factories. +Each hierarchy of #eoOp#s should have its own factory, which know +how to build them from a description in a file. + +@author GeNeura Team, Marten Keijzer and Marc Schoenauer +@version 0.9 +@see eoGenOp.h eoOpFactory +*/ +//@{ + +/** +@defgroup Variators Variation operators +Variators are operators that modify individuals. + +@defgroup Selectors Selection operators + +Selectors are operators that select a subset of a population. + +Example: +@include t-eoSelect.cpp + + +@defgroup Replacors Replacement operators + +Replacors are operators that replace a subset of a population by another set of individuals. + +Here is an example with several replacement operators: +@include t-eoReplacement.cpp +*/ + +/** Abstract data types for EO operators. + Genetic operators act on chromosomes, changing them. + The type to use them on is problem specific. If your genotype + is a std::vector, there are operators that work specifically + on std::vector, but you might also find that generic operators + working on std::vector are what you need. + +*/ +template +class eoOp +{ +public: + //@{ + enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3}; + /// + + /// Ctor + eoOp(OpType _type) + :opType( _type ) {}; + + /// Copy Ctor + eoOp( const eoOp& _eop ) + :opType( _eop.opType ) {}; + + /// Needed virtual destructor + virtual ~eoOp(){}; + + /// getType: number of operands it takes and individuals it produces + OpType getType() const {return opType;}; + +private: + + /// OpType is the type of the operator: how many operands it takes and how many it produces + OpType opType; +}; + +/** +eoMonOp is the monary operator: genetic operator that takes only one EO. +When defining your own, make sure that you return a boolean value +indicating that you have changed the content. +*/ +template +class eoMonOp: public eoOp, public eoUF +{ +public: + /// Ctor + eoMonOp() + : eoOp( eoOp::unary ) {}; + virtual std::string className() const {return "eoMonOp";}; +}; + + +/** Binary genetic operator: subclasses eoOp, and defines basically the + * operator() with two operands, only the first one can be modified +When defining your own, make sure that you return a boolean value +indicating that you have changed the content. + */ +template +class eoBinOp: public eoOp, public eoBF +{ +public: + /// Ctor + eoBinOp() + :eoOp( eoOp::binary ) {}; + virtual std::string className() const {return "eoBinOp";}; +}; + +/** Quad genetic operator: subclasses eoOp, and defines basically the + operator() with two operands, both can be modified. +When defining your own, make sure that you return a boolean value +indicating that you have changed the content. +*/ +template +class eoQuadOp: public eoOp, public eoBF { +public: + /// Ctor + eoQuadOp() + :eoOp( eoOp::quadratic ) {}; + virtual std::string className() const {return "eoQuadOp";}; +}; + +/** Turning an eoQuadOp into an eoBinOp: simply don't touch the second arg! + */ +template +class eoQuad2BinOp: public eoBinOp +{ +public: + /** Ctor + * @param _quadOp the eoQuadOp to be transformed + */ + eoQuad2BinOp(eoQuadOp & _quadOp) : quadOp(_quadOp) {} + + /** Operator() simply calls embedded quadOp operator() with dummy second arg + */ + bool operator()(EOT & _eo1, const EOT & _eo2) + { + 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 + else + return quadOp(eoTmp, _eo1); // both are modified - that's all + } + +private: + eoQuadOp & quadOp; +}; + +#endif + +//@} diff --git a/deprecated/eo/src/eoOpContainer.h b/deprecated/eo/src/eoOpContainer.h new file mode 100644 index 000000000..e1f43bdf6 --- /dev/null +++ b/deprecated/eo/src/eoOpContainer.h @@ -0,0 +1,168 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOpContainer.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 + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoOpContainer_H +#define _eoOpContainer_H + +#include + +/** eoOpContainer is a base class for the sequential and proportional selectors + * It takes care of wrapping the other operators, + * and deleting stuff that it has allocated + * + * Warning: all operators are added together with a rate (double) + * However, the meaning of this rate will be different in + * the differnet instances of eoOpContainer: + * an ***absolute*** probability in the sequential version, and + * a ***relative*** weight in the proportional version + * + * @ingroup Combination + */ +template +class eoOpContainer : public eoGenOp +{ + public : + /** Ctor: nothing much to do */ + eoOpContainer() : max_to_produce(0) {} + + /** Dtor: delete all the GenOps created when wrapping simple ops + */ + virtual ~eoOpContainer(void) {} + + /** for memory management (doesn't have to be very precise */ + virtual unsigned max_production(void) + { + return max_to_produce; + } + + /** + Add an operator to the container, also give it a rate + + (sidenote, it's much less hairy since I added the wrap_op is used) + */ + void add(eoOp& _op, double _rate) + { + ops.push_back(&wrap_op(_op, store)); + rates.push_back(_rate); + max_to_produce = std::max(max_to_produce,ops.back()->max_production()); + } + + virtual std::string className() const = 0; + + protected : + + std::vector rates; + std::vector*> ops; + + private : + eoFunctorStore store; + unsigned max_to_produce; +}; + +/** Sequential selection: + * note the mark, rewind, unmark cycle + * here operators are repeatedly applied on the same individual(s) + * not all too elegant, but it sort of works... + * + * @ingroup Combination + */ +template +class eoSequentialOp : public eoOpContainer +{ +public: + + using eoOpContainer::ops; + using eoOpContainer::rates; + + typedef unsigned position_type; + + + 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); + do { + if (eo::rng.flip(rates[i])) { + // try + // { + // apply it to all the guys in the todo std::list + + //(*ops[i])(_pop); + + ops[i]->apply(_pop); + + // } + // 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()) + ++_pop; + } + while (!_pop.exhausted()); + } + } + virtual std::string className() const {return "SequentialOp";} + +private: + + std::vector to_apply; + std::vector production; +}; + + + +/** The proportional versions: easy! */ +template +class eoProportionalOp : public eoOpContainer +{ +public: + + using eoOpContainer< EOT >::ops; + using eoOpContainer< EOT >::rates; + + void apply(eoPopulator& _pop) + { + unsigned i = eo::rng.roulette_wheel(rates); + + try + { + (*ops[i])(_pop); + ++_pop; + } + catch( typename eoPopulator::OutOfIndividuals&) + {} + } + virtual std::string className() const {return "ProportionalOp";} +}; + + +#endif diff --git a/deprecated/eo/src/eoOpSelMason.h b/deprecated/eo/src/eoOpSelMason.h new file mode 100644 index 000000000..577b5b56f --- /dev/null +++ b/deprecated/eo/src/eoOpSelMason.h @@ -0,0 +1,108 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef _EOOPSELMASON_H +#define _EOOPSELMASON_H + +#include // for eoFactory and eoOpFactory + +#include + + +/** EO Mason, or builder, for operator selectors. A builder must allocate memory +to the objects it builds, and then deallocate it when it gets out of scope + +@ingroup Utilities +*/ +template +class eoOpSelMason: public eoFactory > { + +public: + typedef std::vector* > vOpP; + typedef map*, vOpP > MEV; + + /// @name ctors and dtors + //{@ + /// constructor + eoOpSelMason( eoOpFactory& _opFact): operatorFactory( _opFact ) {}; + + /// destructor + virtual ~eoOpSelMason() {}; + //@} + + /** 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 cant do it itself. The objects built must be destroyed + from outside, using the "destroy" method + */ + virtual eoOpSelector* make(std::istream& _is) { + + std::string opSelName; + _is >> opSelName; + eoOpSelector* opSelectorP; + // Build the operator selector + if ( opSelName == "eoProportionalOpSel" ) { + opSelectorP = new eoProportionalOpSel(); + } + + // 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, dont pay attention to the IDs + opSelectorP->addOp( *op, rate ); + // Keep it in the store, to destroy later + tmpPVec.push_back( op ); + } // if + } // while + + // 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; +}; + + +#endif diff --git a/deprecated/eo/src/eoOrderXover.h b/deprecated/eo/src/eoOrderXover.h new file mode 100644 index 000000000..daaf52e0c --- /dev/null +++ b/deprecated/eo/src/eoOrderXover.h @@ -0,0 +1,92 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +//----------------------------------------------------------------------------- +// eoOrderXover.h +//----------------------------------------------------------------------------- + +#ifndef eoOrderXover_h +#define eoOrderXover_h + +//----------------------------------------------------------------------------- + +#include +#include +#include + +/** + * apply orderXover on two chromosomes. + * Example: + * With 2 parents p1= [1,2,4,3,6,5], p2= [4,5,3,1,6,2] + * It applies a random cut between ("|") two indices. Example: the second element and the fourth: + * p1 : [1|2,4,3|6,5] and p2 : [4|5,3,1|6,2] generate two children: + * c1 = [2,4,3,6,5,1] 2,4,3 taken from p1 and 6,5,1 from p2 + * c2 = [5,3,1,6,2,4] 5,3,1 taken from p2 and 6,2,4 from p1 + * + * @ingroup Variators + */ +template class eoOrderXover: public eoQuadOp +{ + public: + /// 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; + } + + 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 +//----------------------------------------------------------------------------- + +/** + This is a generic class for particle swarm algorithms. There + is only one operator defined, which takes a population and does stuff to + it. It needn't be a complete algorithm, can be also a step of an + algorithm. Only used for mono-objective cases. + + @ingroup Algorithms +*/ +template < class POT > class eoPSO:public eoAlgo < POT >{}; + +#endif /*_EOPSO_H*/ diff --git a/deprecated/eo/src/eoParticleBestInit.h b/deprecated/eo/src/eoParticleBestInit.h new file mode 100644 index 000000000..b203c8246 --- /dev/null +++ b/deprecated/eo/src/eoParticleBestInit.h @@ -0,0 +1,82 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoParticleBestInit.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOPARTICLEBESTINIT_H +#define _EOPARTICLEBESTINIT_H + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + +/** + @addtogroup Initializators + @{ + */ + +/** + * Abstract class for particle best position initialization. + */ +template < class POT > class eoParticleBestInit:public eoUF < POT &, void > +{ +public: + + /** Apply the initialization to a whole given population */ + virtual void apply (eoPop < POT > &_pop) + { + for (unsigned i = 0; i < _pop.size (); i++) + { + this->operator ()(_pop[i]); + } + + } + +}; + +/** + * Initializes the best positions of a particle as its current positions and set the + * particle best fitness. + */ +template < class POT > class eoFirstIsBestInit:public eoParticleBestInit +{ + +public: + + /** Default CTor */ + eoFirstIsBestInit (){} + + void operator () (POT & _po1) + { + //Set the bestPositions + _po1.bestPositions = _po1 ; + + + // set the fitness + _po1.best(_po1.fitness()); + } + +}; + +#endif /*_EOPARTICLEBESTINIT_H */ + +/** @} */ diff --git a/deprecated/eo/src/eoParticleFullInitializer.h b/deprecated/eo/src/eoParticleFullInitializer.h new file mode 100644 index 000000000..96bebb579 --- /dev/null +++ b/deprecated/eo/src/eoParticleFullInitializer.h @@ -0,0 +1,155 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoParticleFullInitializer.h +// (c) OPAC Team, INRIA, 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 + 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: clive.canape@inria.fr + + + */ +//----------------------------------------------------------------------------- + +#ifndef _eoParticleFullInitializer_H +#define _eoParticleFullInitializer_H + +#include +#include +#include +#include +#include + +/** + @addtogroup Initializators + @{ + */ + + +/* + * Abstract class for initialization of algorithm PSO + */ +template class eoInitializerBase : public eoFunctorBase + { + public : + + virtual ~eoInitializerBase() + {} + + virtual void operator()() + {}; + }; + +/** + Base (name) class for Initialization of algorithm PSO + + @see eoInitializerBase eoUF apply +*/ +template class eoParticleInitializer : public eoInitializerBase + { + public: + + //! Constructor + //! @param _proc Evaluation function + //! @param _initVelo Initialization of the velocity + //! @param _initBest Initialization of the best + //! @param _topology Topology to use + //! @param _pop Population + eoParticleFullInitializer( + eoUF& _proc, + eoVelocityInit < POT > &_initVelo, + eoParticleBestInit &_initBest, + eoTopology &_topology, + eoPop < POT > &_pop + ) : proc(_proc), procPara(dummyEval), initVelo(_initVelo), initBest(_initBest), topology(_topology), pop(_pop) {} + + + //! Constructor for parallel evaluation + //! @param _proc Evaluation function + //! @param _initVelo Initialization of the velocity + //! @param _initBest Initialization of the best + //! @param _topology Topology to use + //! @param _pop Population + eoParticleFullInitializer( + eoPopEvalFunc & _proc, + eoVelocityInit < POT > &_initVelo, + eoParticleBestInit &_initBest, + eoTopology &_topology, + eoPop < POT > &_pop + ) : proc(dummy), procPara(_proc), initVelo(_initVelo), initBest(_initBest), topology(_topology), pop(_pop) + {} + + + //! Give the name of the class + //! @return The name of the class + virtual std::string className (void) const + { + return "eoInitializer"; + } + + + + virtual void operator () () + { + 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); + } + + private : + + /* + @param proc First evaluation + @param initVelo Initialization of the velocity + @param initBest Initialization of the best + + */ + eoPop < POT > & pop; + eoUF& proc; + eoPopEvalFunc & procPara; + eoVelocityInit < POT > & initVelo; + eoParticleBestInit & initBest; + eoTopology & topology; + class eoDummyEval : public eoPopEvalFunc + { + public: + void operator()(eoPop &,eoPop &_pop) + {} + } + dummyEval; + class eoDummy : public eoUF + { + public: + void operator()(POT &) + {} + + } + dummy; + }; +#endif /*_eoParticleFullInitializer_H*/ + +/** @} */ diff --git a/deprecated/eo/src/eoPerf2Worth.h b/deprecated/eo/src/eoPerf2Worth.h new file mode 100644 index 000000000..9f1746ecf --- /dev/null +++ b/deprecated/eo/src/eoPerf2Worth.h @@ -0,0 +1,255 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoPerf2Worth.h + (c) Maarten Keijzer, Marc Schoenauer, 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoPerf2Worth_h +#define eoPerf2Worth_h + +#include +#include +#include + +#include +#include +#include + +/** @brief Base class to transform raw fitnesses into fitness for selection + +@see eoSelectFromWorth + +@ingroup Selectors +@ingroup Utilities +*/ +template +class eoPerf2Worth : public eoUF&, void>, public eoValueParam > +{ +public: + + using eoValueParam >::value; + + /** @brief default constructor */ + eoPerf2Worth(std::string _description = "Worths") + : eoValueParam >(std::vector(0), _description) + {} + + /** Sort population according to worth, will keep the worths and + fitness_cache in sync with the population. */ + virtual void sort_pop(eoPop& _pop) + { // start with a std::vector of indices + std::vector indices(_pop.size()); + + unsigned i; + for (i = 0; i < _pop.size();++i) + { // could use generate, but who cares + indices[i] = i; + } + + std::sort(indices.begin(), indices.end(), compare_worth(value())); + + eoPop tmp_pop; + tmp_pop.resize(_pop.size()); + std::vector tmp_worths(value().size()); + + for (i = 0; i < _pop.size(); ++i) + { + tmp_pop[i] = _pop[indices[i]]; + tmp_worths[i] = value()[indices[i]]; + } + + std::swap(_pop, tmp_pop); + std::swap(value(), tmp_worths); + } + + /** helper class used to sort indices into populations/worths */ + class compare_worth + { + public: + + compare_worth(const std::vector& _worths) : worths(_worths) {} + + bool operator()(unsigned a, unsigned b) const { + return worths[b] < worths[a]; // sort in descending (!) order + } + + private: + + const std::vector& worths; + }; + + + + virtual void resize(eoPop& _pop, unsigned sz) { + _pop.resize(sz); + value().resize(sz); + }; + +}; + +/** +Perf2Worth with fitness cache +@ingroup Selectors +@ingroup Utilities +*/ +template +class eoPerf2WorthCached : public eoPerf2Worth +{ +public: + + using eoPerf2Worth::value; + + eoPerf2WorthCached(std::string _description = "Worths") : eoPerf2Worth(_description) {} + + + /** + Implementation of the operator(), updating a cache of fitnesses. Calls the virtual function + calculate_worths when one of the fitnesses has changed. It is not virtual, but derived classes + can remove the fitness caching trough the third template element + */ + void operator()(const eoPop& _pop) + { + unsigned i; + if (fitness_cache.size() == _pop.size()) + { + bool in_sync = true; + for (i = 0; i < _pop.size(); ++i) + { + if (fitness_cache[i] != _pop[i].fitness()) + { + in_sync = false; + fitness_cache[i] = _pop[i].fitness(); + } + } + + if (in_sync) + { // worths are up to date + return; + } + } + else // just cache the fitness + { + fitness_cache.resize(_pop.size()); + for (i = 0; i < _pop.size(); ++i) + { + fitness_cache[i] = _pop[i].fitness(); + } + } + + // call derived implementation of perf2worth mapping + calculate_worths(_pop); + } + + /** The actual virtual function the derived classes should implement*/ + virtual void calculate_worths(const eoPop& _pop) = 0; + + /** + Sort population according to worth, will keep the worths and fitness_cache in sync with the population. + */ + virtual void sort_pop(eoPop& _pop) + { // start with a std::vector of indices + std::vector indices(_pop.size()); + + unsigned i; + for (i = 0; i < _pop.size();++i) + { // could use generate, but who cares + indices[i] = i; + } + + std::sort(indices.begin(), indices.end(), compare_worth(value())); + + eoPop tmp_pop; + tmp_pop.resize(_pop.size()); + std::vector tmp_worths(value().size()); + +#ifdef _MSC_VER + std::vector tmp_cache(_pop.size()); +#else + std::vector tmp_cache(_pop.size()); +#endif + for (i = 0; i < _pop.size(); ++i) + { + tmp_pop[i] = _pop[indices[i]]; + tmp_worths[i] = value()[indices[i]]; + + tmp_cache[i] = fitness_cache[indices[i]]; + } + + std::swap(_pop, tmp_pop); + std::swap(value(), tmp_worths); + std::swap(fitness_cache, tmp_cache); + } + + /** helper class used to sort indices into populations/worths + */ + class compare_worth + { + public : + compare_worth(const std::vector& _worths) : worths(_worths) {} + + bool operator()(unsigned a, unsigned b) const + { + return worths[b] < worths[a]; // sort in descending (!) order + } + + private : + + const std::vector& worths; + }; + + virtual void resize(eoPop& _pop, unsigned sz) + { + _pop.resize(sz); + value().resize(sz); + fitness_cache.resize(sz); + } + + private : + std::vector fitness_cache; +}; + + + +/** A dummy perf2worth, just in case you need it +@ingroup Selectors +@ingroup Utilities +*/ +template +class eoNoPerf2Worth : public eoPerf2Worth +{ +public: + + using eoValueParam< EOT >::value; + + // default behaviour, just copy fitnesses + void operator()(const eoPop& _pop) { + unsigned i; + value().resize(_pop.size()); + for (i = 0; i < _pop.size(); ++i) + value()[i]=_pop[i]; + } +}; + + + +#endif diff --git a/deprecated/eo/src/eoPeriodicContinue.h b/deprecated/eo/src/eoPeriodicContinue.h new file mode 100644 index 000000000..1a3f9d0de --- /dev/null +++ b/deprecated/eo/src/eoPeriodicContinue.h @@ -0,0 +1,55 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +// (c) OPAC Team, LIFL, Feb. 2006 + +/* This library is free software; you 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: cahon@lifl.fr +*/ + +#ifndef __eoPeriodicContinue_h +#define __eoPeriodicContinue_h + +#include +#include + +/** A continue that becomes true periodically. + */ +template class eoPeriodicContinue: public eoContinue { + +public: + + /** 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. */ + bool operator () (const eoPop & /*pop*/) + { + return ((++ counter) % period) != 0 ; + } + + +private: + + unsigned period; + + unsigned counter; + +}; +#endif diff --git a/deprecated/eo/src/eoPersistent.cpp b/deprecated/eo/src/eoPersistent.cpp new file mode 100644 index 000000000..c1334ebc4 --- /dev/null +++ b/deprecated/eo/src/eoPersistent.cpp @@ -0,0 +1,14 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include + +//Implementation of these objects + + +std::istream & operator >> ( std::istream& _is, eoPersistent& _o ) { + _o.readFrom(_is); + return _is; +} diff --git a/deprecated/eo/src/eoPersistent.h b/deprecated/eo/src/eoPersistent.h new file mode 100644 index 000000000..ed3f581ec --- /dev/null +++ b/deprecated/eo/src/eoPersistent.h @@ -0,0 +1,66 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + + +//----------------------------------------------------------------------------- + +// eoPersistent.h +// (c) GeNeura Team, 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOPERSISTENT_H +#define EOPERSISTENT_H + + +#include // std::istream, std::ostream +#include // para std::string + +#include "eoPrintable.h" + +/** + @addtogroup Core + @{ +*/ + +/** +An persistent object that knows how to write (through functions inherited from +#eoPrintable#) and read itself + */ +class eoPersistent: public eoPrintable +{ + public: + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoPersistent() {} + + /** + * Read object. + * @param _is A 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 +std::istream & operator >> ( std::istream& _is, eoPersistent& _o ); + +#endif + +/** @} */ diff --git a/deprecated/eo/src/eoPop.h b/deprecated/eo/src/eoPop.h new file mode 100644 index 000000000..3ea53f466 --- /dev/null +++ b/deprecated/eo/src/eoPop.h @@ -0,0 +1,339 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPop.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOPOP_H +#define _EOPOP_H + +#include +#include +#include // needed for GCC 3.2 +#include + +// EO includes +#include // for eoInit +#include +#include +#include // for shuffle method + +/** 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 + * interface be provided. + * + * 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 + * + * @ingroup Core + */ +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 + */ + eoPop( unsigned _popSize, eoInit& _chromInit ) + :std::vector() + { + resize(_popSize); + for ( unsigned i = 0; i < _popSize; 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 + */ + 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; + } + if (_newPopSize == oldSize) + return; + resize(_newPopSize); // adjust the size + for ( unsigned i = oldSize; i < _newPopSize; 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 + */ + eoPop( std::istream& _is ) :std::vector() { + readFrom( _is ); + } + + /** Empty Dtor */ + virtual ~eoPop() {} + + + /// helper struct for getting a pointer + struct Ref { const EOT* operator()(const EOT& eot) { return &eot;}}; + /// helper struct for comparing on pointers + struct Cmp { + 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 + of descending Fitness, so the first individual is the best! + */ + void sort(void) + { + std::sort(begin(), end(), Cmp2()); + } + + /** creates a std::vector pointing to the individuals in descending order */ + void sort(std::vector& result) const + { + result.resize(size()); + + std::transform(begin(), end(), result.begin(), Ref()); + + std::sort(result.begin(), result.end(), Cmp()); + } + + /** + shuffle the population. Use this member to put the population + in random order + */ + void shuffle(void) + { + UF_random_generator gen; + std::random_shuffle(begin(), end(), gen); + } + + /** creates a std::vector pointing to the individuals in random order */ + void shuffle(std::vector& result) const + { + result.resize(size()); + + std::transform(begin(), end(), result.begin(), Ref()); + + UF_random_generator gen; + std::random_shuffle(result.begin(), result.end(), gen); + } + + /** returns an iterator to the best individual DOES NOT MOVE ANYBODY */ +#if defined(__CUDACC__) + eoPop::iterator it_best_element() + { + eoPop:: iterator it = std::max_element(begin(), end()); +#else + typename eoPop::iterator it_best_element() { + typename eoPop::iterator it = std::max_element(begin(), end()); +#endif + return it; + } + + /** returns an iterator to the best individual DOES NOT MOVE ANYBODY */ + const EOT & best_element() const + { +#if defined(__CUDACC__) + eoPop::const_iterator it = std::max_element(begin(), end()); +#else + typename eoPop::const_iterator it = std::max_element(begin(), end()); +#endif + return (*it); + } + + /** returns a const reference to the worse individual DOES NOT MOVE ANYBODY */ + const EOT & worse_element() const + { +#if defined(__CUDACC__) + eoPop::const_iterator it = std::min_element(begin(), end()); +#else + typename eoPop::const_iterator it = std::min_element(begin(), end()); +#endif + return (*it); + } + + /** returns an iterator to the worse individual DOES NOT MOVE ANYBODY */ +#if defined(__CUDACC__) + eoPop::iterator it_worse_element() + { + eoPop::iterator it = std::min_element(begin(), end()); +#else + typename eoPop::iterator it_worse_element() + { + typename eoPop::iterator it = std::min_element(begin(), end()); +#endif + return it; + } + + /** + 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__) + eoPop::iterator nth_element(int nth) + { + eoPop::iterator it = begin() + nth; +#else + typename eoPop::iterator nth_element(int 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()); + + typename std::vector::iterator it = fitness.begin() + which; + std::nth_element(fitness.begin(), it, fitness.end(), std::greater()); + return *it; + } + + /** 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()); + } + + /** does STL swap with other pop */ + void swap(eoPop& other) + { + std::swap(static_cast& >(*this), static_cast& >(other)); + } + + /** + * Prints sorted pop but does NOT modify it! + * + * @param _os A std::ostream. + */ + 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; + } + } + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << size() << '\n'; + std::copy( begin(), end(), std::ostream_iterator( _os, "\n") ); + } + + /** @name Methods from eoObject */ + //@{ + /** + * Read object. The EOT class must have a ctor from a stream; + * @param _is A std::istream. + */ + virtual void readFrom(std::istream& _is) + { + size_t sz; + _is >> sz; + + resize(sz); + + for (size_t i = 0; i < sz; ++i) { + operator[](i).readFrom( _is ); + } + } + + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual std::string className() const {return "eoPop";}; + //@} + + virtual void invalidate() + { + for (unsigned i=0; ioperator[](i).invalidate(); + } +}; + +#endif diff --git a/deprecated/eo/src/eoPopEvalFunc.h b/deprecated/eo/src/eoPopEvalFunc.h new file mode 100644 index 000000000..aba74d9ab --- /dev/null +++ b/deprecated/eo/src/eoPopEvalFunc.h @@ -0,0 +1,107 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +----------------------------------------------------------------------------- + eoPopEvalFunc.h + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoPopEvalFunc_H +#define eoPopEvalFunc_H + +#include +#include + +/** 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 + * + * 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): + * call the slaves and wait for the results + * + * @ingroup Evaluation + */ +template +class eoPopEvalFunc : public eoBF & , eoPop &, void> +{}; + +///////////////////////////////////////////////////////////// +// eoPopLoopEval +///////////////////////////////////////////////////////////// + +/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies + * a private eoEvalFunc to all offspring + * + * @ingroup Evaluation + */ +template +class eoPopLoopEval : public eoPopEvalFunc { +public: + /** Ctor: set value of embedded eoEvalFunc */ + eoPopLoopEval(eoEvalFunc & _eval) : eval(_eval) {} + + /** Do the job: simple loop over the offspring */ + void operator()(eoPop & _parents, eoPop & _offspring) + { + (void)_parents; + apply(eval, _offspring); + } + +private: + eoEvalFunc & eval; +}; + +///////////////////////////////////////////////////////////// +// eoTimeVaryingLoopEval +///////////////////////////////////////////////////////////// + +/** 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 + * + * @ingroup Evaluation + */ +template +class eoTimeVaryingLoopEval : public eoPopEvalFunc { +public: + /** Ctor: set value of embedded eoEvalFunc */ + eoTimeVaryingLoopEval(eoEvalFunc & _eval) : eval(_eval) {} + + /** Do the job: simple loop over the offspring */ + void operator()(eoPop & _parents, eoPop & _offspring) + { + apply(eval, _parents); + apply(eval, _offspring); + } + +private: + eoEvalFunc & eval; +}; + +#endif diff --git a/deprecated/eo/src/eoPopulator.h b/deprecated/eo/src/eoPopulator.h new file mode 100644 index 000000000..104aafe5e --- /dev/null +++ b/deprecated/eo/src/eoPopulator.h @@ -0,0 +1,211 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPopulator.h +// (c) Maarten Keijzer and Marc Schoenauer, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoPopulator_H +#define _eoPopulator_H + +#include +#include + +/** eoPopulator is a helper class for general operators eoGenOp + It is an eoPop but also behaves like an eoPop::iterator + as far as operator* and operator++ are concerned + + @see eoGenOp + @see eoOpContainer + + @ingroup Core + @ingroup Utilities +*/ +template +class eoPopulator +{ +public : + + eoPopulator(const eoPop& _src, eoPop& _dest) : dest(_dest), current(dest.end()), src(_src) + { + dest.reserve(src.size()); // we don't know this, but wth. + current = dest.end(); + } + + /** @brief Virtual Constructor */ + virtual ~eoPopulator() {}; + + struct OutOfIndividuals {}; + + /** a populator behaves like an iterator. Hence the operator* + * it returns the current individual -- eventually getting + * a new one through the operator++ if at the end + */ + EOT& operator*(void) + { + if (current == dest.end()) + get_next(); // get a new individual + + return *current; + } + + /** only prefix increment defined + Does not add a new element when at the end, use operator* for that + If not on the end, increment the pointer to the next individual + */ + eoPopulator& operator++() + { + if (current == dest.end()) + { // keep the pointer there + return *this; + } + // else + ++current; + return *this; + } + + /** mandatory for operators that generate more offspring than parents + * if such a thing exists ? + */ + void insert(const EOT& _eo) + { /* not really efficient, but its nice to have */ + current = dest.insert(current, _eo); + } + + /** just to make memory mangement more efficient + */ + void reserve(int how_many) + { + size_t sz = current - dest.begin(); + if (dest.capacity() < dest.size() + how_many) + { + dest.reserve(dest.size() + how_many); + } + + current = dest.begin() + sz; + } + + /** can be useful for operators with embedded selectors + * e.g. your brain and my beauty -type + */ + const eoPop& source(void) { return src; } + + /** Get the offspring population. + Can be useful when you want to do some online niching kind of thing + */ + eoPop& offspring(void) { return dest; } + + typedef unsigned position_type; + + /** this is a direct access container: tell position */ + position_type tellp() { return current - dest.begin(); } + /** this is a direct access container: go to position */ + void seekp(position_type pos) { current = dest.begin() + pos; } + /** no more individuals */ + bool exhausted(void) { return current == dest.end(); } + + /** the pure virtual selection method - will be instanciated in + * eoSeqPopulator and eoSelectivePopulator + */ + virtual const EOT& select() = 0; + +protected: + eoPop& dest; + typename eoPop::iterator current; + const eoPop& src; + +private: + + void get_next() { + if(current == dest.end()) + { // get new individual from derived class select() + dest.push_back(select()); + current = dest.end(); + --current; + return; + } + // else + ++current; + return; + } + +}; + + +/** SeqPopulator: an eoPopulator that sequentially goes through the + population is supposed to be used after a batch select of a whole + bunch or genitors +*/ +template +class eoSeqPopulator : public eoPopulator +{ +public: + + using eoPopulator< EOT >::src; + + eoSeqPopulator(const eoPop& _pop, eoPop& _dest) : + eoPopulator(_pop, _dest), current(0) {} + + /** the select method simply returns next individual in the src pop */ + const EOT& select(void) { + if(current >= eoPopulator< EOT >::src.size()) { + throw OutOfIndividuals(); + } + + const EOT& res = src[current++]; + return res; + } + + +private: + + struct OutOfIndividuals {}; + + unsigned current; +}; + + +/** SelectivePopulator an eoPoplator that uses an eoSelectOne to select guys. +Supposedly, it is passed the initial population. + */ +template +class eoSelectivePopulator : public eoPopulator +{ +public : + + using eoPopulator< EOT >::src; + + eoSelectivePopulator(const eoPop& _pop, eoPop& _dest, eoSelectOne& _sel) + : eoPopulator(_pop, _dest), sel(_sel) + { sel.setup(_pop); }; + + /** the select method actually selects one guy from the src pop */ + const EOT& select() { + return sel(src); + } + + +private: + + eoSelectOne& sel; +}; + +#endif diff --git a/deprecated/eo/src/eoPrintable.cpp b/deprecated/eo/src/eoPrintable.cpp new file mode 100644 index 000000000..ec6e32462 --- /dev/null +++ b/deprecated/eo/src/eoPrintable.cpp @@ -0,0 +1,21 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +//----------------------------------------------------------------------------- +// eoPrintable.cpp +//----------------------------------------------------------------------------- + +#include + +//----------------------------------------------------------------------------- +//Implementation of these objects +//----------------------------------------------------------------------------- + +std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ) { + _o.printOn(_os); + return _os; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/src/eoPrintable.h b/deprecated/eo/src/eoPrintable.h new file mode 100644 index 000000000..1f2404a89 --- /dev/null +++ b/deprecated/eo/src/eoPrintable.h @@ -0,0 +1,62 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPrintable.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOPRINTABLE_H +#define EOPRINTABLE_H + +//----------------------------------------------------------------------------- + +#include // std::istream, std::ostream +#include // para std::string + +/* +This functionality was separated from eoObject, since it makes no sense to print +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; +if the objects define printOn there's no need to define "operator<<". + + @ingroup Core + */ +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. + */ + virtual void printOn(std::ostream& _os) const = 0; +}; + +//----------------------------------------------------------------------------- +///Standard output for all objects in the EO hierarchy +std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ); + +#endif diff --git a/deprecated/eo/src/eoPropGAGenOp.h b/deprecated/eo/src/eoPropGAGenOp.h new file mode 100644 index 000000000..5d2fd79cd --- /dev/null +++ b/deprecated/eo/src/eoPropGAGenOp.h @@ -0,0 +1,89 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPropGAGenOp.h +// (c) Marc.Schoenauer 2005 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@inria.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoPropGAGenOp_h +#define _eoPropGAGenOp_h + +#include "eoGenOp.h" +#include "eoInvalidateOps.h" +/////////////////////////////////////////////////////////////////////////////// +// class eoSGAGenOp +/////////////////////////////////////////////////////////////////////////////// + +/** + * eoPropGAGenOp (for Simple GA, but Proportional) + * choice between Crossover, mutation or cloining + * with respect to given relatve weights + * + * @ingroup Combination + */ +template +class eoPropGAGenOp : public eoGenOp +{ + public: + + /** Ctor from + * * weight of clone + * * crossover (with weight) + * * mutation (with weight) + */ + eoPropGAGenOp(double _wClone, eoQuadOp& _cross, double _wCross, + eoMonOp& _mut, double _wMut) + : wClone(_wClone), + cross(_cross), + wCross(_wCross), + 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) + { + propOp.apply(_pop); + } + + /** inherited from eoGenOp */ + virtual unsigned max_production(void) {return 2;} + + virtual std::string className() const {return "eoPropGAGenOp";} + + + private: + double wClone; + eoQuadOp ✗ // eoInvalidateXXX take the boolean output + double wCross; + eoMonOp & mut; // of the XXX op and invalidate the EOT + double wMut; + eoProportionalOp propOp; + eoMonCloneOp monClone; +}; + + +#endif diff --git a/deprecated/eo/src/eoProportionalCombinedOp.h b/deprecated/eo/src/eoProportionalCombinedOp.h new file mode 100644 index 000000000..60c478903 --- /dev/null +++ b/deprecated/eo/src/eoProportionalCombinedOp.h @@ -0,0 +1,234 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoCombinedOp_H +#define _eoCombinedOp_H + +#include +#include +#include +#include +#include +#include + +/** +\defgroup Utilities Utilities + +Classes that may help you write elegant code. +*/ + +/** +@defgroup Combination Operators combination + +Classes that permits to combine several operators in a single one. + +@ingroup Utilities +@{ +*/ + +/** @name PropCombined Genetic operators + +Combination of same-type Genetic Operators. + +This files contains the classes eoPropCombinedXXXOp (XXX in {Mon, Bin, Quad}) +that allow to use more than a single operator of a specific class +into an algorithm, chosing by a roulette wheel based on user-defined rates + +@author Marc Schoenauer +@version 0.1 +*/ + + +////////////////////////////////////////////////////// +//// combined MonOp +////////////////////////////////////////////////////// + +/** eoMonOp is the monary operator: genetic operator that takes only one EO + + * now accepts generic operators +*/ + +template +class eoPropCombinedMonOp: public eoMonOp +{ +public: + /// Ctor from a "true" operator + eoPropCombinedMonOp(eoMonOp & _first, const double _rate) + { + ops.push_back(&_first); + rates.push_back(_rate); + } + + virtual std::string className() const { return "eoPropCombinedMonOp"; } + + virtual void add(eoMonOp & _op, const double _rate, bool _verbose=false) + { + ops.push_back(&_op); + rates.push_back(_rate); + // compute the relative rates in percent - to warn the user! + if (_verbose) + printOn( eo::log << eo::logging ); + } + + // outputs the operators and percentages + virtual void printOn(std::ostream & _os) + { + double total = 0; + unsigned i; + for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %\n"; + } + + virtual bool operator()(EOT & _indi) + { + unsigned what = rng.roulette_wheel(rates); // choose one op + return (*ops[what])(_indi); // apply it + } +protected: +std::vector*> ops; +std::vector rates; +}; + +////////////////////////////////////////////////////// +//// combined BinOp +////////////////////////////////////////////////////// + +/** COmbined Binary genetic operator: + * operator() has two operands, only the first one can be modified + */ +template +class eoPropCombinedBinOp: public eoBinOp +{ +public: + /// Ctor + eoPropCombinedBinOp(eoBinOp & _first, const double _rate) + { + ops.push_back(&_first); + rates.push_back(_rate); + } + +virtual std::string className() const { return "eoPropCombinedBinOp"; } + +virtual void add(eoBinOp & _op, const double _rate, bool _verbose=false) + { + ops.push_back(&_op); + rates.push_back(_rate); + // 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; + } + } + + 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 + } +private: +std::vector*> ops; +std::vector rates; +}; + + +////////////////////////////////////////////////////// +//// combined QuadOp +////////////////////////////////////////////////////// + +/** Quad genetic operator: subclasses eoOp, and defines basically the + operator() with two operands, both can be modified. +*/ +/** Combined quad genetic operator: + * operator() has two operands, both can be modified + + * generic operators are now allowed: there are imbedded into + * the corresponding "true" operator + */ +template +class eoPropCombinedQuadOp: public eoQuadOp +{ +public: + /// Ctor from a true operator + eoPropCombinedQuadOp(eoQuadOp & _first, const double _rate) + { + ops.push_back(&_first); + rates.push_back(_rate); + } + + virtual std::string className() const { return "eoPropCombinedQuadOp"; } + + virtual void add(eoQuadOp & _op, const double _rate, bool _verbose) + { +#ifndef DEPRECATED_MESSAGES +#pragma message "The use of the verbose parameter in eoPropCombinedQuadOp::add is deprecated and will be removed in the next release." + eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoPropCombinedQuadOp::add is deprecated and will be removed in the next release." << std::endl; +#endif // !DEPRECATED_MESSAGES + + add(_op,_rate); + } + + // addition of a true operator + virtual void add(eoQuadOp & _op, const double _rate) + { + ops.push_back(&_op); + rates.push_back(_rate); + // compute the relative rates in percent - to warn the user! + printOn( eo::log << eo::logging ); + } + + // outputs the operators and percentages + virtual void printOn(std::ostream & _os) + { + double total = 0; + unsigned i; + for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %\n"; + } + + virtual bool operator()(EOT & _indi1, EOT & _indi2) + { + unsigned what = rng.roulette_wheel(rates); // choose one op index + return (*ops[what])(_indi1, _indi2); // apply it + } +private: +std::vector*> ops; +std::vector rates; +}; + + +// for General Ops, it's another story - see eoOpContainer +#endif + +/** @} */ diff --git a/deprecated/eo/src/eoProportionalSelect.h b/deprecated/eo/src/eoProportionalSelect.h new file mode 100644 index 000000000..ec1243cee --- /dev/null +++ b/deprecated/eo/src/eoProportionalSelect.h @@ -0,0 +1,87 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoProportionalSelect_h +#define eoProportionalSelect_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +/** eoProportionalSelect: select an individual proportional to her stored fitness + 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 +{ +public: + /// Sanity check + eoProportionalSelect(const eoPop& /*pop*/ = eoPop()) + { + if (minimizing_fitness()) + throw std::logic_error("eoProportionalSelect: minimizing fitness"); + } + + 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) + { + cumulative[i] = _pop[i].fitness() + cumulative[i-1]; + } + } + + /** do the selection, + */ + const EOT& operator()(const eoPop& _pop) + { + if (cumulative.size() == 0) setup(_pop); + + double fortune = rng.uniform() * cumulative.back(); + typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune); + return _pop[result - cumulative.begin()]; + } + +private : + + typedef std::vector FitVec; + FitVec cumulative; +}; +/** @example t-eoRoulette.cpp + */ + +#endif diff --git a/deprecated/eo/src/eoRandomRealWeightUp.h b/deprecated/eo/src/eoRandomRealWeightUp.h new file mode 100644 index 000000000..81521b512 --- /dev/null +++ b/deprecated/eo/src/eoRandomRealWeightUp.h @@ -0,0 +1,80 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRandomRealWeightUp.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EORANDOMREALWEIGHTUP_H +#define EORANDOMREALWEIGHTUP_H + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + +/** + * 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. + * + * @ingroup Variators + */ +class eoRandomRealWeightUp:public eoWeightUpdater +{ +public: + + /** + * Default constructor + * @param _min - The minimum bound for the weight + * @param _max - The maximum bound for the weight + */ + eoRandomRealWeightUp( + double _min, + double _max + ):min(_min),max(_max) + { + // consistency check + if (min > max) + { + std::string s; + s.append (" min > max in eoRandomRealWeightUp"); + throw std::runtime_error (s); + } + } + + /** + * Generate an real random number in [min,max] and assign it to _weight + * @param _weight - The assigned (real) weight + */ + void operator() (double & _weight) + { + _weight=rng.uniform(max-min)+min; + } + + +protected: + double min,max; + +}; + + + +#endif/*EORANDOMREALWEIGHTUP_H*/ diff --git a/deprecated/eo/src/eoRandomSelect.h b/deprecated/eo/src/eoRandomSelect.h new file mode 100644 index 000000000..065f050f9 --- /dev/null +++ b/deprecated/eo/src/eoRandomSelect.h @@ -0,0 +1,93 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRandomSelect.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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ + +#ifndef eoRandomSelect_h +#define eoRandomSelect_h + +/** This file contains straightforward selectors: + * eoRandomSelect returns an individual uniformly selected + * eoBestSelect always return the best individual + * eoSequentialSelect returns all individuals in turn + */ + +#include +#include + +/** eoRandomSelect: a selection method that selects ONE individual randomly + * + * @ingroup Selectors + */ +template class eoRandomSelect: public eoSelectOne +{ + public: + + /// not a big deal!!! + virtual const EOT& operator()(const eoPop& _pop) + { + return _pop[eo::rng.random(_pop.size())] ; + } +}; + +/** eoBestSelect: a selection method that always return the best + * (mainly for testing purposes) + * + * @ingroup Selectors + */ +template class eoBestSelect: public eoSelectOne +{ + public: + + /// not a big deal!!! + virtual const EOT& operator()(const eoPop& _pop) + { + return _pop.best_element() ; + } +}; + +/** eoNoSelect: returns all individual in order WITHOUT USING FITNESS!!! + * looping back to the beginning when exhasuted + * + * @ingroup Selectors + */ +template class eoNoSelect: public eoSelectOne +{ + public: + /** Ctor + */ + eoNoSelect(): current(0) {} + + virtual const EOT& operator()(const eoPop& _pop) + { + if (current >= _pop.size()) + current=0; + + current++; + return _pop[current-1] ; + } +private: + unsigned current; +}; + +#endif diff --git a/deprecated/eo/src/eoRanking.h b/deprecated/eo/src/eoRanking.h new file mode 100644 index 000000000..5e7342911 --- /dev/null +++ b/deprecated/eo/src/eoRanking.h @@ -0,0 +1,112 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoRanking.h + (c) Maarten Keijzer, Marc Schoenauer, 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoRanking_h +#define eoRanking_h + +#include + +/** An instance of eoPerfFromWorth + * COmputes the ranked fitness: fitnesses range in [m,M] + * with m=2-pressure/popSize and M=pressure/popSize. + * in between, the progression depstd::ends on exponent (linear if 1). + * + * @ingroup Selectors + */ +template +class eoRanking : public eoPerf2Worth // false: do not cache fitness +{ +public: + + using eoPerf2Worth::value; + + /* Ctor: + @param _p selective pressure (in (1,2] + @param _e exponent (1 == linear) + */ + eoRanking(double _p=2.0, double _e=1.0): + pressure(_p), exponent(_e) {} + + /* helper function: finds index in _pop of _eo, an EOT * */ + int lookfor(const EOT *_eo, const eoPop& _pop) + { + typename eoPop::const_iterator it; + for (it=_pop.begin(); it<_pop.end(); it++) + { + if (_eo == &(*it)) + return it-_pop.begin(); + } + throw std::runtime_error("Not found in eoLinearRanking"); + } + + /* COmputes the ranked fitness: fitnesses range in [m,M] + with m=2-pressure/popSize and M=pressure/popSize. + in between, the progression depstd::ends on exponent (linear if 1). + */ + virtual void operator()(const eoPop& _pop) + { + std::vector rank; + _pop.sort(rank); + unsigned pSize =_pop.size(); + unsigned int pSizeMinusOne = pSize-1; + + if (pSize <= 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 +#include + +/** eoRankingSelect: select an individual by roulette wheel on its rank + * is an eoRouletteWorthSelect, i.e. a selector using a std::vector of worthes + * rather than the raw fitness (see eoSelectFromWorth.h) + * uses an internal eoRanking object which is an eoPerf2Worth + * + * @ingroup Selectors +*/ +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): + eoRouletteWorthSelect(ranking), ranking(_p, _e) {} + +private : + eoRanking ranking; // derived from eoPerf2Worth +}; + +#endif diff --git a/deprecated/eo/src/eoRealBoundModifier.h b/deprecated/eo/src/eoRealBoundModifier.h new file mode 100644 index 000000000..9a9e032bc --- /dev/null +++ b/deprecated/eo/src/eoRealBoundModifier.h @@ -0,0 +1,109 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRealBoundModifier.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ + +#ifndef EOREALBOUNDMODIFIER_H +#define EOREALBOUNDMODIFIER_H + +#include +#include + +/** @defgroup Bounds Bounds management + * + * Bounds are a set of utilities that permits to manage ranges of existence + * for variables. For example to restrain vectors or parameters to a given domain. + * + * @ingroup Utilities + */ + +/** + * Abstract class for eoRealVectorBounds modifier. + * Used to modify the bounds included into the eoRealVectorBounds object. + * + * @ingroup Bounds + */ +class eoRealBoundModifier: public eoBF < eoRealBaseVectorBounds &,unsigned,void > {}; + + +/** + * An eoRealBoundModifier that modify nothing ! + * @ingroup Bounds + */ +class eoDummyRealBoundModifier: public eoRealBoundModifier +{ +public: + + eoDummyRealBoundModifier (){} + + void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) + { + (void)_bnds; + (void)_i; + } +}; + + + +/** + * Modify an eoReal(Base)VectorBounds : + * At iteration t, the interval I(t)=[min,max] is updated as: + * I(t)=[min,(1-(t/Nt)^alpha)*max] where + * - 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 + */ + eoExpDecayingBoundModifier (unsigned _stopCriteria, + double _alpha, + eoValueParam & _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); + + // should delete the old eoRealBounds ? + _bnds[_i]=new eoRealInterval(_bnds.minimum(_i),std::max(_bnds.minimum(_i),newMaxBound)); + } + + +protected: + unsigned stopCriteria; + double alpha; + eoValueParam & genCounter; + +}; + +#endif/*EOREALBOUNDMODIFIER_H*/ diff --git a/deprecated/eo/src/eoRealParticle.h b/deprecated/eo/src/eoRealParticle.h new file mode 100644 index 000000000..14326558c --- /dev/null +++ b/deprecated/eo/src/eoRealParticle.h @@ -0,0 +1,50 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRealParticle.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOREALPARTICLE_H +#define _EOREALPARTICLE_H + + +#include + + +/** eoRealParticle: Implementation of a real-coded particle for + * particle swarm optimization. Positions, velocities and best positions are real-coded. + * + * @ingroup Real +*/ +template < class FitT> class eoRealParticle: public eoVectorParticle + +{ +public: + + eoRealParticle(unsigned size = 0, double positions = 0.0,double velocities = 0.0,double bestPositions = 0.0): eoVectorParticle (size, positions,velocities,bestPositions) {} + + virtual std::string className() const + { + return "eoRealParticle"; + } +}; + +#endif /*_EOREALPARTICLE_H*/ diff --git a/deprecated/eo/src/eoReduce.h b/deprecated/eo/src/eoReduce.h new file mode 100644 index 000000000..7f0c17729 --- /dev/null +++ b/deprecated/eo/src/eoReduce.h @@ -0,0 +1,306 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoReduce_h +#define eoReduce_h + +//----------------------------------------------------------------------------- + +#include + +// EO includes +#include // eoPop +#include // eoReduce +#include +#include + +/** + * 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 + the worst. Ideally, we should be able to choose at run-time!!! + + @ingroup Replacors +*/ +template class eoReduce: public eoBF&, unsigned, void> +{}; + +/** truncation method using sort + @ingroup Replacors + */ +template class eoTruncate : public eoReduce +{ + void operator()(eoPop& _newgen, unsigned _newsize) + { + if (_newgen.size() == _newsize) + return; + if (_newgen.size() < _newsize) + throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); + + _newgen.sort(); + _newgen.resize(_newsize); + } +}; + +/** random truncation + @ingroup Replacors + * */ +template class eoRandomReduce : public eoReduce +{ + void operator()(eoPop& _newgen, unsigned _newsize) + { + if (_newgen.size() == _newsize) + return; + 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); + } +}; + +/** +EP truncation method (some global stochastic tournament + sort) +Softer selective pressure than pure truncate + @ingroup Replacors +*/ +template class eoEPReduce : public eoReduce +{ +public: + 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; + } + } + + /// helper struct for comparing on std::pairs + // compares the scores + // uses the fitness if scores are equals ???? + 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; + } + }; + + + 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; + } + } + + // 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; jsecond); + } +private: + unsigned t_size; + eoPop tmPop; +}; + +/** a truncate class that does not sort, but repeatidely kills the worse. +To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement) + @ingroup Replacors +*/ +template +class eoLinearTruncate : public eoReduce +{ + void operator()(eoPop& _newgen, unsigned _newsize) + { + unsigned oldSize = _newgen.size(); + if (oldSize == _newsize) + return; + if (oldSize < _newsize) + 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); + } + } +}; + +/** a truncate class based on a repeated deterministic (reverse!) tournament +To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) + @ingroup Replacors +*/ +template +class eoDetTournamentTruncate : public eoReduce +{ +public: + eoDetTournamentTruncate(unsigned _t_size): + t_size(_t_size) + { + if (t_size < 2) + { + eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncate adjusted to 2" << std::endl; + t_size = 2; + } + } + + void operator()(eoPop& _newgen, unsigned _newsize) + { + unsigned oldSize = _newgen.size(); + if (_newsize == 0) + { + _newgen.resize(0); + return; + } + if (oldSize == _newsize) + return; + if (oldSize < _newsize) + throw std::logic_error("eoDetTournamentTruncate: Cannot truncate to a larger size!\n"); + + + // Now OK to erase some losers + std::cout << "oldSize - _newsize: " << oldSize - _newsize << std::endl; + 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) ); + + } + } +private: + unsigned t_size; +}; + +/** a truncate class based on a repeated deterministic (reverse!) tournament +To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) + @ingroup Replacors +*/ +template +class eoStochTournamentTruncate : public eoReduce +{ +public: + eoStochTournamentTruncate(double _t_rate): + 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; + } + if (t_rate > 1) + { + eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 1" << std::endl; + t_rate = 1; + } + } + + void operator()(eoPop& _newgen, unsigned _newsize) + { + unsigned oldSize = _newgen.size(); + if (_newsize == 0) + { + _newgen.resize(0); + return; + } + if (oldSize == _newsize) + return; + if (oldSize < _newsize) + throw std::logic_error("eoStochTournamentTruncate: Cannot truncate to a larger size!\n"); + // 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) ); + + + } + } + +private: + double t_rate; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/eoReduceMerge.h b/deprecated/eo/src/eoReduceMerge.h new file mode 100644 index 000000000..02933b404 --- /dev/null +++ b/deprecated/eo/src/eoReduceMerge.h @@ -0,0 +1,124 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoReduceMerge_h +#define _eoReduceMerge_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** @addtogroup Replacors + * @{ + */ + +/** +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 +even if it is worse than anybody else. + +@see eoReduceMerge +@see eoSSGAWorseReplacement +@see eoSSGADetTournamentReplacement +@see eoSSGAStochTournamentReplacement +*/ +template +class eoReduceMerge : public eoReplacement +{ + public: + eoReduceMerge(eoReduce& _reduce, eoMerge& _merge) : + reduce(_reduce), merge(_merge) + {} + + 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); + } + + private : + eoReduce& reduce; + eoMerge& merge; +}; + +/** +SSGA replace worst. Is an eoReduceMerge. +*/ +template +class eoSSGAWorseReplacement : public eoReduceMerge +{ + public : + eoSSGAWorseReplacement() : eoReduceMerge(truncate, plus) {} + + private : + eoLinearTruncate truncate; + eoPlus plus; +}; + +/** +SSGA deterministic tournament replacement. Is an eoReduceMerge. +*/ +template +class eoSSGADetTournamentReplacement : public eoReduceMerge +{ + public : + eoSSGADetTournamentReplacement(unsigned _t_size) : + eoReduceMerge(truncate, plus), truncate(_t_size) {} + + private : + eoDetTournamentTruncate truncate; + eoPlus plus; +}; + +/** 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 +So what the heck ! */ +template +class eoSSGAStochTournamentReplacement : public eoReduceMerge +{ + public : + eoSSGAStochTournamentReplacement(double _t_rate) : + eoReduceMerge(truncate, plus), truncate(_t_rate) {} + + private : + eoStochTournamentTruncate truncate; + eoPlus plus; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoReduceMergeReduce.h b/deprecated/eo/src/eoReduceMergeReduce.h new file mode 100644 index 000000000..17721f733 --- /dev/null +++ b/deprecated/eo/src/eoReduceMergeReduce.h @@ -0,0 +1,143 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + 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@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoReduceMergeReduce_h +#define _eoReduceMergeReduce_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** +eoReduceMergeReduce is an eoReplacement: +- saves possible elite parents +- reduces rest of parents +- reduces offspring +- merges reduced populations +- reduces resulting merged pop if necessary + + @ingroup Replacors +*/ +template +class eoReduceMergeReduce : public eoReplacement +{ +public: + eoReduceMergeReduce(eoHowMany _howManyElite, + bool _strongElitism, + eoHowMany _howManyReducedParents, + eoReduce & _reduceParents, + eoHowMany _howManyReducedOffspring, + eoReduce & _reduceOffspring, + eoReduce & _reduceFinal) : + howManyElite(_howManyElite), + strongElitism(_strongElitism), + howManyReducedParents(_howManyReducedParents), + howManyReducedOffspring (_howManyReducedOffspring), + reduceParents(_reduceParents), + reduceOffspring(_reduceOffspring), + reduceFinal(_reduceFinal) + {} + + void operator()(eoPop & _parents, eoPop & _offspring) + { + eoPop temp; + unsigned int finalPopSize = _parents.size(); + 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); + } + + // the reduce steps. First the parents + unsigned reducedParentSize = howManyReducedParents(_parents.size()); + if (!reducedParentSize) + _parents.clear(); + else if (reducedParentSize != _parents.size()) + reduceParents(_parents, reducedParentSize); + + // then the offspring + unsigned reducedOffspringSize = howManyReducedOffspring(offSize); + if (!reducedOffspringSize) + throw std::runtime_error("No offspring left after reduction!"); + if (reducedOffspringSize != offSize) // need reduction + reduceOffspring(_offspring, reducedOffspringSize); + + // now merge reduced populations + _parents.resize(reducedParentSize + _offspring.size()); + 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 weak estd::listism + eoHowMany howManyReducedParents; // if 0, no parent in final replacement + eoHowMany howManyReducedOffspring; // if 0, std::runtime_error + // the reducers + eoReduce & reduceParents; + eoReduce & reduceOffspring; + eoReduce & reduceFinal; +}; + +#endif diff --git a/deprecated/eo/src/eoReduceSplit.h b/deprecated/eo/src/eoReduceSplit.h new file mode 100644 index 000000000..4b21aa25e --- /dev/null +++ b/deprecated/eo/src/eoReduceSplit.h @@ -0,0 +1,328 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoReduceSplit_h +#define eoReduceSplit_h + +//----------------------------------------------------------------------------- + +#include + +// EO includes +#include // eoPop +#include // eoReduce +#include + +/** @addtogroup Replacors + * @{ + */ + +/** + * eoReduceSplit: reduce the pop to the specified size + * AND eventually returns the eliminated guys +*/ +template class eoReduceSplit: public eoBF&, eoPop &, void > +{}; + +/** deterministic truncation method using sort */ +template +class eoTruncateSplit : public eoReduceSplit +{ +public: + /** 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) + { + unsigned popSize = _newgen.size(); + unsigned eliminated = howMany(popSize); + if (!eliminated) // nothing to do + return ; + 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 +class eoLinearTruncateSplit : public eoReduceSplit +{ +public: + /** 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) + { + unsigned popSize = _newgen.size(); + unsigned eliminated = howMany(popSize); + if (!eliminated) // nothing to do + return ; + long newsize = static_cast(popSize) - static_cast(eliminated); + if (newsize < 0) + throw std::logic_error("eoLinearTruncateSplit: Cannot truncate to a larger size!\n"); + + _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); + } + } + +private: + eoHowMany howMany; + bool returnEliminated; +}; + +/** random truncation - batch version */ +template +class eoRandomSplit : public eoReduceSplit +{ +public: + /** 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) + { + unsigned popSize = _newgen.size(); + unsigned eliminated = howMany(popSize); + if (!eliminated) // nothing to do + return ; + unsigned newsize = popSize - eliminated; + if (newsize < 0) + throw std::logic_error("eoRandomSplit: Cannot truncate to a larger size!\n"); + + _newgen.shuffle(); + + // save poor losers if necessary + if (returnEliminated) + for (unsigned i=0; i +class eoLinearRandomSplit : public eoReduceSplit +{ +public: + /** 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) + { + unsigned popSize = _newgen.size(); + unsigned eliminated = howMany(popSize); + if (!eliminated) // nothing to do + return ; + unsigned newsize = popSize - eliminated; + if (newsize < 0) + throw std::logic_error("eoLinearRandomSplit: Cannot truncate to a larger size!\n"); + + _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); + } + return ; + } + +private: + eoHowMany howMany; + bool returnEliminated; +}; + + +/** a ReduceSplit class based on a repeated deterministic (reverse!) tournament +To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) +*/ +template +class eoDetTournamentTruncateSplit : public eoReduceSplit +{ +public: + /** 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) + { + if (t_size < 2) + { + eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; + t_size = 2; + } + } + + /** Performs repeated inverse_deterministic_tournament on the pop */ + void operator()(eoPop& _newgen, eoPop & _eliminated) + // BUG??? void operator()(eoPop& _newgen, unsigned _newsize) + { + unsigned popSize = _newgen.size(); + unsigned eliminated = howMany(popSize); + if (!eliminated) // nothing to do + return ; + unsigned newsize = popSize - eliminated; + if (newsize < 0) + throw std::logic_error("eoDetTournamentTruncateSplit: Cannot truncate to a larger size!\n"); + + + _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); + } + } + +private: + unsigned t_size; + eoHowMany howMany; + bool returnEliminated; +}; + +/** a ReduceSplit class based on a repeated deterministic (reverse!) tournament +To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) +*/ +template +class eoStochTournamentTruncateSplit : public eoReduce +{ +public: + /** 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) + { + if (t_rate <= 0.5) + { + eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51" << std::endl; + t_rate = 0.51; + } + if (t_rate > 1) + { + eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 1" << std::endl; + t_rate = 1; + } + } + + /** Performs repeated inverse_stochastic_tournament on the pop */ + void operator()(eoPop& _newgen, eoPop & _eliminated) + //BUG??? void operator()(eoPop& _newgen, unsigned _newsize) + { + /* old version + if (!_eliminated.size()) // nothing to do + return; + unsigned oldSize = _newgen.size(); + unsigned newSize = oldSize - _eliminated.size(); + unsigned eliminated = howMany(popSize); + if (newSize < 0) + throw std::logic_error("eoStochTournamentTruncateSplit: Cannot truncate to a larger size!\n"); + +end of old version */ + + unsigned popSize = _newgen.size(); + unsigned eliminated = howMany(popSize); + if (!eliminated) // nothing to do + return ; + unsigned newsize = popSize - eliminated; + if (newsize < 0) + throw std::logic_error("eoDetTournamentTruncateSplit: Cannot truncate to a larger size!\n"); + + + + _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); + } + } + + +private: + double t_rate; + eoHowMany howMany; + bool returnEliminated; +}; + +//----------------------------------------------------------------------------- + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoReplacement.h b/deprecated/eo/src/eoReplacement.h new file mode 100644 index 000000000..033d441cb --- /dev/null +++ b/deprecated/eo/src/eoReplacement.h @@ -0,0 +1,128 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoReplacement_h +#define _eoReplacement_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** +--- +The eoMergeReduce, combination of eoMerge and eoReduce, can be found +in file eoMergeReduce.h + +The eoReduceMergeReduce that reduces the parents and the offspring, +merges the 2 reduced populations, and eventually reduces that final +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 +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 +eoNoReplacement that did nothing, relying on the algo to swap popualtions). +MS 12/12/2000 + + @see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge + +@class eoReplacement, base (pure abstract) class +@class eoGenerationalReplacement, as it says ... +@class eoWeakElitistReplacement a wrapper to add elitism + +*/ + +/** The base class for all replacement functors. + +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 + + @ingroup Replacors + */ +template +class eoReplacement : public eoBF&, eoPop&, void> +{}; + +/** +generational replacement == swap populations + + @ingroup Replacors +*/ +template +class eoGenerationalReplacement : public eoReplacement +{ + public : + /// swap + void operator()(eoPop& _parents, eoPop& _offspring) + { + _parents.swap(_offspring); + } +}; + +/** +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... + + @ingroup Replacors +*/ +template +class eoWeakElitistReplacement : public eoReplacement +{ +public : + typedef typename EOT::Fitness Fitness; + + // Ctor, takes an eoReplacement + eoWeakElitistReplacement(eoReplacement & _replace) : + replace(_replace) {} + + /// do replacement + void operator()(eoPop& _pop, eoPop& _offspring) + { + const EOT oldChamp = _pop.best_element(); + 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; + } + } +private: + eoReplacement & replace; +}; + +#endif diff --git a/deprecated/eo/src/eoRingTopology.h b/deprecated/eo/src/eoRingTopology.h new file mode 100644 index 000000000..6bad13cd7 --- /dev/null +++ b/deprecated/eo/src/eoRingTopology.h @@ -0,0 +1,192 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRingTopology.h +// (c) INRIA Futurs DOLPHIN 2007 +/* + Clive Canape + 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 + 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: clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EORINGTOPOLOGY_H_ +#define EORINGTOPOLOGY_H_ + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + + +/** + * Static ring topology for particle swarm optimization. + * The neighborhoods are built using a ring based on each particle's indice and + * do not change for all the time steps. Only the best particle in each neighborhood is + * potentially updated thanks to the "updateNeighborhood" method. + * + * @ingroup Selectors + */ +template < class POT > class eoRingTopology:public eoTopology +{ + +public: + + /** + * The only Ctor. + * @param _neighborhoodSize - The size of each neighborhood. + */ + eoRingTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} + + + /** + * Builds the neighborhoods using a ring strategy based on the particle indices. + * Also initializes the best particle of each neighborhood. + * @param _pop - The population used to build the only neighborhood. + * @return + */ + void setup(const eoPop & _pop) + { + if (!isSetup){ + + // put in the neighborhood + 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()) + currentNghd.best(_pop[(_pop.size()+i-k+j)%_pop.size()]); + } + neighborhoods.push_back(currentNghd); + } + isSetup=true; + } + else + { + // Should activate this part ? + /* + std::string s; + s.append (" Linear topology already setup in eoRingTopology"); + throw std::runtime_error (s); + */ + } + } + + /** + * Retrieves the neighboorhood of a particle. + * @return _indice - The particle indice (in the population) + */ + unsigned retrieveNeighborhoodByIndice(unsigned _indice) + { + return _indice; + } + + + /** + * Updates the best fitness of the given particle and + * potentially replaces the local best the given particle it's better. + * @param _po - The particle to update + * @param _indice - The indice of the given particle in the population + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + //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]; + } + // 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); + } + } + + + /** + * Returns the best particle belonging to the neighborhood of the given particle. + * @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) + { + unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); + + return (neighborhoods[theGoodNhbd].best()); + } + + + /** + * Print the structure of the topology on the standard output. + */ + void printOn() + { + for (unsigned i=0;i< neighborhoods.size();i++) + { + std::cout << "{ " ; + for (unsigned j=0;j< neighborhoods[i].size();j++) + { + std::cout << neighborhoods[i].get(j) << " "; + } + std::cout << "}" << std::endl; + } + } + + /* + * 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; + bool isSetup; +}; +/** @example t-eoRingTopology.cpp + */ + +#endif /*EORINGTOPOLOGY_H_*/ diff --git a/deprecated/eo/src/eoSGA.h b/deprecated/eo/src/eoSGA.h new file mode 100644 index 000000000..b31dff04e --- /dev/null +++ b/deprecated/eo/src/eoSGA.h @@ -0,0 +1,121 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSGA.h +// (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSGA_h +#define _eoSGA_h + +#include +#include +#include +#include +#include +#include +#include +#include + +/** The Simple Genetic Algorithm, following Holland and Goldberg + * + * Needs a selector (class eoSelectOne) a crossover (eoQuad, i.e. a + * 2->2 operator) and a mutation with their respective rates, of + * course an evaluation function (eoEvalFunc) and a continuator + * (eoContinue) which gives the stopping criterion. Performs full + * generational replacement. + * + * @ingroup Algorithms + */ +template +class eoSGA : public eoAlgo +{ +public : + + // added this second ctor as I didn't like the ordering of the parameters + // in the one above. Any objection :-) MS + eoSGA( + eoSelectOne& _select, + eoQuadOp& _cross, float _crate, + eoMonOp& _mutate, float _mrate, + eoEvalFunc& _eval, + eoContinue& _cont) + : cont(_cont), + mutate(_mutate), + mutationRate(_mrate), + cross(_cross), + crossoverRate(_crate), + select(_select), + eval(_eval) {} + + void operator()(eoPop& _pop) + { + eoPop offspring; + + do + { + select(_pop, offspring); + + 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])) + { + offspring[2*i].invalidate(); + offspring[2*i+1].invalidate(); + } + } + } + + for (i=0; i < offspring.size(); i++) + { + if (rng.flip(mutationRate) ) + { + if (mutate(offspring[i])) + offspring[i].invalidate(); + } + } + + _pop.swap(offspring); + apply(eval, _pop); + + } while (cont(_pop)); + } + +private : + + eoContinue& cont; + /// eoInvalidateMonOp invalidates the embedded operator + eoInvalidateMonOp mutate; + float mutationRate; + // eoInvalidateQuadOp invalidates the embedded operator + eoInvalidateQuadOp cross; + float crossoverRate; + eoSelectPerc select; + eoEvalFunc& eval; +}; + +#endif diff --git a/deprecated/eo/src/eoSGAGenOp.h b/deprecated/eo/src/eoSGAGenOp.h new file mode 100644 index 000000000..f08b2104e --- /dev/null +++ b/deprecated/eo/src/eoSGAGenOp.h @@ -0,0 +1,93 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSGAGenOp.h +// (c) 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 + 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 + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSGAGenOp_h +#define _eoSGAGenOp_h + +#include "eoGenOp.h" +#include "eoInvalidateOps.h" +/////////////////////////////////////////////////////////////////////////////// +// class eoSGAGenOp +/////////////////////////////////////////////////////////////////////////////// + +/** + * 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 + * quadratic crossover and unary mutation + * It was introduced for didactic reasons, but seems to be popular :-) + * + * @ingroup Combination + */ + 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) + : cross(_cross), + pCross(_pCross), + 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(mut, pMut); // then mutation, with proba pmut + } + + /** do the job: delegate to op */ + virtual void apply(eoPopulator& _pop) + { + op.apply(_pop); + } + + /** inherited from eoGenOp */ + virtual unsigned max_production(void) {return 2;} + + virtual std::string className() const {return "eoSGAGenOp";} + + + private: + eoQuadOp ✗ // eoInvalidateXXX take the boolean output + double pCross; + eoMonOp & mut; // of the XXX op and invalidate the EOT + double pMut; + eoProportionalOp propOp; + eoQuadCloneOp quadClone; + eoSequentialOp op; +}; + + +#endif diff --git a/deprecated/eo/src/eoSGATransform.h b/deprecated/eo/src/eoSGATransform.h new file mode 100644 index 000000000..55b5e5eda --- /dev/null +++ b/deprecated/eo/src/eoSGATransform.h @@ -0,0 +1,168 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSGA.h +// (c) Marc.Schoenauer 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSGATransform_h +#define _eoSGATransform_h + +#include +#include + +/////////////////////////////////////////////////////////////////////////////// +// class eoSGATransform +/////////////////////////////////////////////////////////////////////////////// +#include // std::vector +#include +#include + +/** eoSGATransform: transforms a population using genetic operators. + * It does it exactly as class eoSGA, i.e. only accepts + * quadratic crossover and unary mutation + * It is here mainly for tutorial reasons + * + * @ingroup Combination +*/ +template class eoSGATransform : public eoTransform +{ + public: + + /// Default constructor. + eoSGATransform(eoQuadOp& _cross, double _cProba, + eoMonOp& _mutate, double _mProba) + : cross(_cross), + crossoverProba(_cProba), + mutate(_mutate), + mutationProba(_mProba) {} + + + /** + * Transforms a population. + * @param _pop The population to be transformed. + */ + void operator()(eoPop& _pop) + { + unsigned 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]); + } + } + + for (i=0; i < _pop.size(); i++) + { + if (rng.flip(mutationProba) ) + { + mutate(_pop[i]); + } + + } + }; + + private: + eoInvalidateQuadOp cross; + double crossoverProba; + eoInvalidateMonOp mutate; + double mutationProba; +}; + +/** 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, + * and hence can be modified from outside + * It is here mainly for tutorial reasons + * + * @ingroup Combination +*/ +template class eoDynSGATransform : public eoTransform +{ + public: + + /// Default constructor - receives values + eoDynSGATransform(eoQuadOp& _cross, double _cProba, + eoMonOp& _mutate, double _mProba) + : cross(_cross), + crossoverProbaHolder(_cProba), crossoverProba(crossoverProbaHolder), + 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) + : cross(_cross), + crossoverProbaHolder(0), crossoverProba(*_cProbaRef), + mutate(_mutate), + mutationProbaHolder(0), mutationProba(*_mProbaRef) {} + + + /** + * Transforms a population. + * @param _pop The population to be transformed. + */ + void operator()(eoPop& _pop) + { + unsigned 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]); + } + } + + for (i=0; i < _pop.size(); i++) + { + if (rng.flip(mutationProba) ) + { + mutate(_pop[i]); + } + + } + }; + // accessors - mainly for EASEA + double & PCrossHandle() { return crossoverProba;} + double & PMutHandle() { return mutationProba;} + +private: + // 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; + double crossoverProbaHolder; // the value, used only if ctor gets a value + double& crossoverProba; // the reference, to be used in operator() + eoInvalidateMonOp mutate; + double mutationProbaHolder; // the value, used only if ctor gets a value + double& mutationProba; // the reference, to be used in operator() +}; + + +#endif diff --git a/deprecated/eo/src/eoSIGContinue.cpp b/deprecated/eo/src/eoSIGContinue.cpp new file mode 100644 index 000000000..2f126ea91 --- /dev/null +++ b/deprecated/eo/src/eoSIGContinue.cpp @@ -0,0 +1,38 @@ +// -*- 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 +/* + This library is free software; you 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 +*/ +//----------------------------------------------------------------------------- +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include +#include + +// --- Global variables - but don't know what else to do - MS --- +bool existSIGContinue = false; +bool call_func = false; diff --git a/deprecated/eo/src/eoSIGContinue.h b/deprecated/eo/src/eoSIGContinue.h new file mode 100644 index 000000000..2199b49ef --- /dev/null +++ b/deprecated/eo/src/eoSIGContinue.h @@ -0,0 +1,95 @@ +// -*- 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 +/* + This library is free software; you 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 +*/ +//----------------------------------------------------------------------------- +// the same thing can probably be done in MS environement, but I hoave no way +// to test it so at the moment it is commented out when in MSVC + + +#ifndef eoSIGContinue_h +#define eoSIGContinue_h + +#include +#include + +/** @addtogroup Continuators + * @{ + */ + +extern bool existSIGContinue; +extern bool call_func; + +void set_bool(int) +{ + call_func = true; +} + +/** + A continuator that stops if a given signal is received during the execution +*/ +template< class EOT> +class eoSIGContinue: public eoContinue +{ +public: + /// Ctor : installs the signal handler + eoSIGContinue(int sig, sighandler_t fct) + : _sig(sig), _fct(fct) + { + // First checks that no other eoSIGContinue does exist + if (existSIGContinue) + throw std::runtime_error("A signal handler is already defined!\n"); + + #ifndef _WINDOWS + #ifdef SIGQUIT + ::signal( sig, set_bool ); + existSIGContinue = true; + #endif + #endif + } + + /** Returns false when the signal has been typed in reached */ + virtual bool operator() ( const eoPop& _vEO ) + { + if (call_func) + { + _fct(_sig); + call_func = false; + } + + return true; + } + + virtual std::string className(void) const { return "eoSIGContinue"; } +private: + int _sig; + sighandler_t _fct; +}; + +/** @} */ + +#endif + + // of MSVC comment-out diff --git a/deprecated/eo/src/eoSTLFunctor.h b/deprecated/eo/src/eoSTLFunctor.h new file mode 100644 index 000000000..04f96f9ca --- /dev/null +++ b/deprecated/eo/src/eoSTLFunctor.h @@ -0,0 +1,123 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSTLFunctor.h +// (c) 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSTLFunctor_H +#define _eoSTLFunctor_H + +#include "eoFunctor.h" + +/** @addtogroup Utilities + * @{ + */ + +/** + Generic set of classes that wrap an eoF, eoUF or eoBF so that they have the + copy semantics the STL functions usually require (i.e. they can be passed + by value, rather than the EO standard pass by reference). + + The family consists of eoSTLF, eoSTLUF, eoSTLBF that modify eoF, eoUF and eoBF + respectively +*/ +template +class eoSTLF +{ + public: + + typedef R result_type; + + eoSTLF(eoF& _f) : f(_f) {} + + R operator()(void) + { + return f(); + } + + private : + + eoF& f; +}; + +#ifdef _MSVC +/// specialization of void for MSVC users, unfortunately only works for eoF, +/// as MSVC does not support partial specialization either +template <> +void eoSTLF::operator()(void) +{ + f(); +} +#endif + +/** + Generic set of classes that wrap an eoF, eoUF or eoBF so that they have the + copy semantics the STL functions usually require (i.e. they can be passed + by value, rather than the EO standard pass by reference). + + The family consists of eoSTLF, eoSTLUF, eoSTLBF that modify eoF, eoUF and eoBF + respectively +*/ +template +class eoSTLUF : public std::unary_function +{ + public: + eoSTLUF(eoUF& _f) : f(_f) {} + + R operator()(A1 a) + { + return f(a); + } + + private: + eoUF& f; +}; + +/** + Generic set of classes that wrap an eoF, eoUF or eoBF so that they have the + copy semantics the STL functions usually require (i.e. they can be passed + by value, rather than the EO standard pass by reference). + + The family consists of eoSTLF, eoSTLUF, eoSTLBF that modify eoF, eoUF and eoBF + respectively +*/ +template +class eoSTLBF : public std::binary_function +{ + public: + eoSTLBF(eoUF& _f) : f(_f) {} + + R operator()(A1 a1, A2 a2) + { + return f(a1, a2); + } + + private: + + eoBF& f; +}; + +//! @todo: put automated wrappers here... + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoScalarFitness.h b/deprecated/eo/src/eoScalarFitness.h new file mode 100644 index 000000000..31a9dbffe --- /dev/null +++ b/deprecated/eo/src/eoScalarFitness.h @@ -0,0 +1,130 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoScalarFitness.h + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + + +#ifndef eoScalarFitness_h +#define eoScalarFitness_h + +#include +#include + +/** @addtogroup Evaluation + * @{ + */ + +/** + * Wraps a scalar fitness values such as a double or int, with the option of + * maximizing (using less) or minimizing (using greater) + * + * It overrides operator<() to use the Compare template argument. Thus, if you + * need to compare if an indiv1 is "better" than an indiv2, you can use: + * if( indiv1 > indiv2 ) { + * // indiv1 is better + * } else { + * // indiv2 is better + * } + * + * Suitable constructors and assignments and casts are defined to work + * with this quantity as if it were a ScalarType. +*/ +template +class eoScalarFitness +{ + public : + + eoScalarFitness() : value() {} + eoScalarFitness(const eoScalarFitness& other) : value(other.value) {} + eoScalarFitness(const ScalarType& v) : value(v) {} + + eoScalarFitness& operator=(const eoScalarFitness& other) + { value = other.value; return *this; } + eoScalarFitness& operator=(const ScalarType& v) + { value = v; return *this; } + + /** Conversion operator: it permits to use a fitness instance as its scalar + * type, if needed. For example, this is possible: + * eoScalarFitness > fit; + * double val = 1.0; + * fit = val; + * val = fit; + */ + operator ScalarType(void) const { return value; } + + /// Comparison, using less by default + 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 + bool operator<(const ScalarType& other) const + { return Compare()(value, other); } + + // implementation of the other operators + bool operator>( const eoScalarFitness& y ) const { return y < *this; } + // implementation of the other operators + bool operator<=( const eoScalarFitness& y ) const { return !(*this > y); } + // implementation of the other operators + bool operator>=(const eoScalarFitness& y ) const { return !(*this < y); } + + + private : + ScalarType value; +}; +/** @example t-eofitness.cpp + * + */ + + +/** +Typedefs for fitness comparison, Maximizing Fitness compares with less, +and minimizing fitness compares with greater. This because we want ordinary +fitness values (doubles) to be equivalent with Maximizing Fitness, and +comparing with less is the default behaviour. +*/ +#if defined(__CUDACC__) +typedef eoScalarFitness > eoMaximizingFitness; +typedef eoScalarFitness > eoMinimizingFitness; +#else +typedef eoScalarFitness > eoMaximizingFitness; +typedef eoScalarFitness > eoMinimizingFitness; +#endif + +template +std::ostream& operator<<(std::ostream& os, const eoScalarFitness& f) +{ + os << (F) f; + return os; +} + +template +std::istream& operator>>(std::istream& is, eoScalarFitness& f) +{ + F value; + is >> value; + f = value; + return is; +} + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoScalarFitnessAssembled.cpp b/deprecated/eo/src/eoScalarFitnessAssembled.cpp new file mode 100644 index 000000000..58f7615fa --- /dev/null +++ b/deprecated/eo/src/eoScalarFitnessAssembled.cpp @@ -0,0 +1,38 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoScalarFitnessAssembled.cpp +// Marc Wintermantel & Oliver Koenig +// IMES-ST@ETHZ.CH +// March 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 + 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 +*/ +//----------------------------------------------------------------------------- +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include "eoScalarFitnessAssembled.h" + + +// need to allocate the static variables of class eoScalarFitnessAssembledTraits +std::vector eoScalarFitnessAssembledTraits::TermDescriptions; diff --git a/deprecated/eo/src/eoScalarFitnessAssembled.h b/deprecated/eo/src/eoScalarFitnessAssembled.h new file mode 100644 index 000000000..50e9038de --- /dev/null +++ b/deprecated/eo/src/eoScalarFitnessAssembled.h @@ -0,0 +1,284 @@ + /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- */ + +//----------------------------------------------------------------------------- +// eoScalarFitnessAssembled.h +// Marc Wintermantel & Oliver Koenig +// IMES-ST@ETHZ.CH +// March 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 + 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 +*/ +//----------------------------------------------------------------------------- + +#ifndef eoScalarFitnessAssembled_h +#define eoScalarFitnessAssembled_h + +#include +#include +#include +#include +#include + +/** @addtogroup Evaluation + * @{ + */ + +//! Defines properties of eoScalarFitnessAssembled. +/*! Properties that are hold in this traits class: + - std::vector to hold descriptions of the different fitness terms +*/ +class eoScalarFitnessAssembledTraits{ + +public: + + typedef std::vector::size_type size_type; + + static void setDescription( size_type _idx, std::string _descr ) { + if ( _idx < TermDescriptions.size() ) + TermDescriptions[_idx] = _descr; + else{ + TermDescriptions.resize(_idx, "Unnamed variable" ); + TermDescriptions[_idx] = _descr; + } + } + + static std::string getDescription( size_type _idx) { + if ( _idx < TermDescriptions.size() ) + return TermDescriptions[_idx ]; + else + return "Unnamed Variable"; + } + + static void resize( size_type _n, const std::string& _descr) { + TermDescriptions.resize(_n, _descr); + } + + static size_type size() { return TermDescriptions.size(); } + + static std::vector getDescriptionVector() { return TermDescriptions; } + +private: + static std::vector TermDescriptions; +}; +/** @example t-eoFitnessAssembled.cpp + */ + +//! Implements fitness as std::vector, storing all values that might occur during fitness assembly +/*! Properties: + - Wraps a scalar fitness values such as a double or int, with the option of + maximizing (using less) or minimizing (using greater). + - Stores all kinda different values met during fitness assembly, to be defined in eoEvalFunc. + - It overrides operator<() to use the Compare template argument. + - Suitable constructors and assignments and casts are defined to work + with this quantity as if it were a ScalarType. + - Global fitness value is stored as first element in the vector +*/ +template +class eoScalarFitnessAssembled : public std::vector { + +public: + + using std::vector< ScalarType >::empty; + using std::vector< ScalarType >::front; + using std::vector< ScalarType >::size; + + + typedef typename std::vector baseVector; + typedef typename baseVector::size_type size_type; + + // Basic constructors and assignments + eoScalarFitnessAssembled() + : baseVector( FitnessTraits::size() ), + feasible(true), failed(false), msg("") + {} + + eoScalarFitnessAssembled( size_type _n, + const ScalarType& _val, + const std::string& _descr="Unnamed variable" ) + : baseVector(_n, _val), + feasible(true), failed(false), msg("") + { + if ( _n > FitnessTraits::size() ) + FitnessTraits::resize(_n, _descr); + } + + eoScalarFitnessAssembled( const eoScalarFitnessAssembled& other) + : baseVector( other ), + feasible(other.feasible), + failed(other.failed), + msg(other.msg) + {} + + eoScalarFitnessAssembled& operator=( const eoScalarFitnessAssembled& other) { + baseVector::operator=( other ); + feasible = other.feasible; + failed = other.failed; + msg = other.msg; + return *this; + } + + // Constructors and assignments to work with scalar type + eoScalarFitnessAssembled( const ScalarType& v ) + : baseVector( 1, v ), + feasible(true), failed(false), msg("") + {} + + eoScalarFitnessAssembled& operator=( const ScalarType& v ) { + + if( empty() ) + push_back( v ); + else + front() = v; + return *this; + } + + //! Overload push_back() + void push_back(const ScalarType& _val ){ + baseVector::push_back( _val ); + if ( size() > FitnessTraits::size() ) + FitnessTraits::setDescription( size()-1, "Unnamed variable"); + } + + //! Overload push_back() + void push_back(const ScalarType& _val, const std::string& _descr ){ + baseVector::push_back( _val ); + FitnessTraits::setDescription( size()-1, _descr ); + } + + //! Overload resize() + void resize( size_type _n, const ScalarType& _val = ScalarType(), const std::string& _descr = "Unnamed variable" ){ + baseVector::resize(_n, _val); + FitnessTraits::resize(_n, _descr); + } + + //! Set description + void setDescription( size_type _idx, std::string _descr ) { + FitnessTraits::setDescription( _idx, _descr ); + } + + //! Get description + std::string getDescription( size_type _idx ){ return FitnessTraits::getDescription( _idx ); } + + //! Get vector with descriptions + std::vector getDescriptionVector() { return FitnessTraits::getDescriptionVector(); } + + //! Feasibility boolean + /** + * Can be specified anywhere in fitness evaluation + * as an indicator if the individual is in some feasible range. + */ + bool feasible; + + //! Failed boolean + /** + * Can be specified anywhere in fitness evaluation + * as an indicator if the evaluation of the individual failed + */ + bool failed; + + //! Message + /** + * Can be specified anywhere in fitness evaluation. + * Typically used to store some sort of error messages, if evaluation of individual failed. + */ + std::string msg; + + + // Scalar type access + operator ScalarType(void) const { + if ( empty() ) + return 0.0; + else + return front(); + } + + //! Print term values and descriptions + void printAll(std::ostream& os) const { + for (size_type i=0; i < size(); ++i ) + os << FitnessTraits::getDescription(i) << " = " << this->operator[](i) << " "; + } + + //! Comparison, using less by default + bool operator<(const eoScalarFitnessAssembled& other) const{ + if ( empty() || other.empty() ) + return false; + else + return Compare()( front() , other.front() ); + } + + //! Comparison with ScalarTypes. Explicit definition needed to compile with VS 8.0 + bool operator<(ScalarType x) const{ + eoScalarFitnessAssembled ScalarFitness(x); + return this->operator<(ScalarFitness); + } + + // implementation of the other operators + bool operator>( const eoScalarFitnessAssembled& y ) const { return y < *this; } + + // implementation of the other operators + bool operator<=( const eoScalarFitnessAssembled& y ) const { return !(*this > y); } + + // implementation of the other operators + bool operator>=(const eoScalarFitnessAssembled& y ) const { return !(*this < y); } + +}; +/** + * @example t-eoFitnessAssembledEA.cpp +*/ + + +/** +Typedefs for fitness comparison, Maximizing Fitness compares with less, +and minimizing fitness compares with greater. This because we want ordinary +fitness values (doubles) to be equivalent with Maximizing Fitness, and +comparing with less is the default behaviour. +*/ +typedef eoScalarFitnessAssembled, eoScalarFitnessAssembledTraits > eoAssembledMaximizingFitness; +typedef eoScalarFitnessAssembled, eoScalarFitnessAssembledTraits > eoAssembledMinimizingFitness; + +template +std::ostream& operator<<(std::ostream& os, const eoScalarFitnessAssembled& f) +{ + for (unsigned i=0; i < f.size(); ++i) + os << f[i] << " "; + + os << f.feasible << " "; + os << f.failed << " "; + + return os; +} + +template +std::istream& operator>>(std::istream& is, eoScalarFitnessAssembled& f) +{ + for (unsigned i=0; i < f.size(); ++i){ + F value; + is >> value; + f[i] = value; + } + + is >> f.feasible; + is >> f.failed; + + return is; +} + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoSecondsElapsedContinue.h b/deprecated/eo/src/eoSecondsElapsedContinue.h new file mode 100644 index 000000000..e29aeefb5 --- /dev/null +++ b/deprecated/eo/src/eoSecondsElapsedContinue.h @@ -0,0 +1,76 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSeconsElapsedContinue.h +// (c) Maarten Keijzer, 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSecondsElapsedContinue_h +#define _eoSecondsElapsedContinue_h + +#include + +/** + Timed continuator: continues until a number of seconds is used + + @ingroup Continuators +*/ +template< class EOT> +class eoSecondsElapsedContinue: public eoContinue +{ + time_t start; + int seconds; +public: + + eoSecondsElapsedContinue(int nSeconds) : start(time(0)), seconds(nSeconds) {} + + 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; + } + + /** Print on a stream + * @param __os the ostream to print on + */ + void printOn (std :: ostream & __os) const { + + __os << start << ' ' << seconds << std :: endl; + } + +}; +/** @example t-eoSecondsElapsedContinue.cpp + */ + +#endif diff --git a/deprecated/eo/src/eoSelect.h b/deprecated/eo/src/eoSelect.h new file mode 100644 index 000000000..aae338434 --- /dev/null +++ b/deprecated/eo/src/eoSelect.h @@ -0,0 +1,46 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSelect_h +#define _eoSelect_h + + +//----------------------------------------------------------------------------- +#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 +that holds a begin and end iterator to the population + +@ingroup Core +@ingroup Selectors +*/ +template +class eoSelect : public eoBF&, eoPop&, void> +{}; + +#endif diff --git a/deprecated/eo/src/eoSelectFactory.h b/deprecated/eo/src/eoSelectFactory.h new file mode 100644 index 000000000..9dc19dabf --- /dev/null +++ b/deprecated/eo/src/eoSelectFactory.h @@ -0,0 +1,93 @@ +// eoSelectFactory.h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOSELECTFACTORY_H +#define _EOSELECTFACTORY_H + +#include +#include +#include + +//----------------------------------------------------------------------------- + +/** EO Factory.An instance of the factory class to create selectors, that is, +eoSelect objects + +@see eoSelect +@ingroup Selectors +@ingroup Utilities +*/ +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 eoObject methods + //@{ + void printOn( std::ostream& _os ) const {}; + void readFrom( std::istream& _is ){}; + + /** className is inherited */ + //@} + +}; + + +#endif diff --git a/deprecated/eo/src/eoSelectFromWorth.h b/deprecated/eo/src/eoSelectFromWorth.h new file mode 100644 index 000000000..342be9da7 --- /dev/null +++ b/deprecated/eo/src/eoSelectFromWorth.h @@ -0,0 +1,231 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSelectFromWorth.h + (c) Maarten Keijzer, Marc Schoenauer, 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSelectFromWorth_h +#define _eoSelectFromWorth_h + +#include +//----------------------------------------------------------------------------- +#include +#include +#include +//----------------------------------------------------------------------------- + +/** selects one element from a population (is an eoSelectOne) +but the selection is based on a std::vector of Worth that is different +from the fitnesses (e.g. EO fitness is what Koza terms "raw fitness", +Worth is what the selection is based upon). + +see class eoPerf2Worth: an eoStat that transforms fitnesses into Worthes + +Note: Worthes will not always be doubles - see some multi-objective +techniques where it is a std::pair of doubles ... + +It has to have a < operator it you want to call an existing +selector (see selector.h) - but of course you can write the whole +thing ... + +@ingroup Selectors +*/ +template +class eoSelectFromWorth : public eoSelectOne +{ +public: + + /* Default ctor from an eoPerf2Worth object */ + eoSelectFromWorth(eoPerf2Worth& _perf2Worth) + : perf2Worth(_perf2Worth) + {} + + /* setup the worthes */ + virtual void setup(const eoPop& pop) { + perf2Worth(pop); +#ifndef NDEBUG + fitness.resize(pop.size()); + for (unsigned i = 0; i < pop.size(); ++i) { + fitness[i] = pop[i].fitness(); + } +#endif + } + + +protected: + + eoPerf2Worth& perf2Worth; + +#ifndef NDEBUG + std::vector fitness; + void check_sync(unsigned index, const EOT& _eo) { + if (fitness[index] != _eo.fitness()) { + throw std::runtime_error("eoSelectFromWorth: fitnesses are not in sync"); + } + } +#endif +}; + + +/** An instance of eoSelectPerf2Worth that does selection from the Worthes + * using a ... determinisitic tournament, yes! + +@ingroup Selectors + */ +template +class eoDetTournamentWorthSelect : public eoSelectFromWorth +{ +public: + + using eoSelectFromWorth::perf2Worth; + + typedef typename std::vector::iterator worthIterator; + + /* Default ctor from an eoPerf2Worth object + tournament size */ + eoDetTournamentWorthSelect(eoPerf2Worth& perf2Worth, + unsigned _tSize) + : eoSelectFromWorth(perf2Worth), tSize(_tSize) {} + + /* Perform deterministic tournament on worthes by calling the + appropriate fn see selectors.h */ + virtual const EOT& operator()(const eoPop& pop) { + worthIterator it = deterministic_tournament(perf2Worth.value().begin(), + perf2Worth.value().end(), + tSize); + unsigned index = it - perf2Worth.value().begin(); +#ifndef NDEBUG + // check whether the stuff is still in sync + check_sync(index, pop[index]); +#endif + return pop[index]; + } + + +private: + + unsigned tSize; +}; + +/** An instance of eoSelectPerf2Worth that does selection from the Worthes + * using a ... stochastic tournament, yes! + +@ingroup Selectors + */ +template +class eoStochTournamentWorthSelect : public eoSelectFromWorth +{ +public: + + using eoSelectFromWorth::perf2Worth; + + typedef typename std::vector::iterator worthIterator; + + /* Default ctor from an eoPerf2Worth object + tournament rate */ + eoStochTournamentWorthSelect(eoPerf2Worth &_perf2Worth, double _tRate) + : eoSelectFromWorth(_perf2Worth), tRate(_tRate) + {} + + /* Perform stochastic tournament on worthes + by calling the appropriate fn in selectors.h + */ + virtual const EOT& operator()(const eoPop& _pop) { + worthIterator it = stochastic_tournament(perf2Worth.value().begin(), + perf2Worth.value().end(), + tRate); + + unsigned index = it - perf2Worth.value().begin(); + +#ifndef NDEBUG + // check whether the stuff is still in sync + check_sync(index, _pop[index]); +#endif + + return _pop[index]; + } + +private: + double tRate; +}; + +/** An instance of eoSelectPerf2Worth that does selection from the Worthes + * using a ... roulette wheel selection, yes! + +@ingroup Selectors + */ +template +class eoRouletteWorthSelect : public eoSelectFromWorth +{ +public: + + using eoSelectFromWorth::perf2Worth; + + typedef typename std::vector::iterator worthIterator; + + + /* Default ctor from an eoPerf2Worth object */ + eoRouletteWorthSelect(eoPerf2Worth &_perf2Worth) + : eoSelectFromWorth(_perf2Worth) + {} + + /* We have to override the default behavior to compute the total + * only once! + */ + virtual void setup(const eoPop& _pop) + { + eoSelectFromWorth::setup(_pop); + total = 0.0; + for (worthIterator it = perf2Worth.value().begin(); + it& _pop) { + // cout << "On affiche les worths\n"; + // for (unsigned i=0; + // icheck_sync(index, _pop[index]); +#endif + + return _pop[index]; + return _pop[it - perf2Worth.value().begin()]; + } + +private: + double total; +}; + +#endif diff --git a/deprecated/eo/src/eoSelectMany.h b/deprecated/eo/src/eoSelectMany.h new file mode 100644 index 000000000..63da51503 --- /dev/null +++ b/deprecated/eo/src/eoSelectMany.h @@ -0,0 +1,82 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSelectMany.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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSelectMany_h +#define _eoSelectMany_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** 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, + and push them to the back of the destination population. + +@ingroup Selectors +*/ +template +class eoSelectMany : public eoSelect +{ + public: + /// init + 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) + : select(_select), howMany(_howMany) {} + + /** + The implementation repeatidly selects an individual + + @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) + */ + 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; +}; + +#endif diff --git a/deprecated/eo/src/eoSelectNumber.h b/deprecated/eo/src/eoSelectNumber.h new file mode 100644 index 000000000..f6f094ef2 --- /dev/null +++ b/deprecated/eo/src/eoSelectNumber.h @@ -0,0 +1,74 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSelectNumber_h +#define _eoSelectNumber_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +//----------------------------------------------------------------------------- + +/** 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 + the back of the destination population. + +@ingroup Selectors +*/ +template +class eoSelectNumber : public eoSelect +{ + public: + /// init + eoSelectNumber(eoSelectOne& _select, unsigned _nb_to_select = 1) + : select(_select), nb_to_select(_nb_to_select) {} + + /** + The implementation repeatidly selects an individual + + @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) + */ + 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; +}; + +#endif diff --git a/deprecated/eo/src/eoSelectOne.h b/deprecated/eo/src/eoSelectOne.h new file mode 100644 index 000000000..5afdd1404 --- /dev/null +++ b/deprecated/eo/src/eoSelectOne.h @@ -0,0 +1,60 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSelectOne_h +#define _eoSelectOne_h + + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + +/** eoSelectOne selects only one element from a whole population. + Most selection techniques are simply repeated applications + of eoSelectOne. + + @see eoSelectMany, eoSelectRandom, eoDetTournament, eoStochTournament, eoProportional + +@ingroup Selectors +*/ +#if defined(_MSC_VER) && (_MSC_VER < 1300) +template +#else +template +#endif +class eoSelectOne : public eoUF&, const EOT&> +{ + public : + /// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this) + virtual void setup(const eoPop& _pop) + { + (void)_pop; + } +}; +/** @example t-selectOne.cpp + */ + + +#endif diff --git a/deprecated/eo/src/eoSelectPerc.h b/deprecated/eo/src/eoSelectPerc.h new file mode 100644 index 000000000..131a3d591 --- /dev/null +++ b/deprecated/eo/src/eoSelectPerc.h @@ -0,0 +1,74 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSelectPerc_h +#define _eoSelectPerc_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +//----------------------------------------------------------------------------- + +/** 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 + the back of the destination population. + +@ingroup Selectors +*/ +template +class eoSelectPerc : public eoSelect +{ + public: + /// init + eoSelectPerc(eoSelectOne& _select, float _rate = 1.0) + : select(_select), rate(_rate) {} + + /** + 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) + */ + 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; +}; + +#endif diff --git a/deprecated/eo/src/eoSequentialSelect.h b/deprecated/eo/src/eoSequentialSelect.h new file mode 100644 index 000000000..1a1f02e4e --- /dev/null +++ b/deprecated/eo/src/eoSequentialSelect.h @@ -0,0 +1,148 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSequential.h +// (c) GeNeura Team, 1998 - Maarten Keijzer 2000, 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoSequential_h +#define eoSequential_h + +#include + +#include "utils/eoData.h" +#include "utils/eoRNG.h" +#include "eoSelectOne.h" + +/** Contains the following classes: + * - eoSequentialSelect, returns all individuals one by one, + * either sorted or shuffled + * - eoEliteSequentialSelect, returns all indivisuals one by one + * starting with best, continuing shuffled (see G3 engine) + */ + + +/** All Individuals in order + +Looping back to the beginning when exhausted, can be from best to +worse, or in random order. + +It is the eoSelectOne equivalent of eoDetSelect - though eoDetSelect +always returns individuals from best to worst + +@ingroup Selectors +*/ +template class eoSequentialSelect: public eoSelectOne +{ + public: + /** Ctor: sets the current pter to numeric_limits::max() so init will take place first time + not very elegant, maybe ... + */ + eoSequentialSelect(bool _ordered = true) + : 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); + else + _pop.shuffle(eoPters); + current=0; + } + + virtual const EOT& operator()(const eoPop& _pop) + { + if (current >= _pop.size()) + setup(_pop); + + unsigned eoN = current; + current++; + return *eoPters[eoN] ; + } +private: + bool ordered; + unsigned current; + std::vector eoPters; +}; + + + +/** All Individuals in order + +The best individual first, then the others in sequence (random order). +for G3 evolution engine, see Deb, Anad and Joshi, CEC 2002 + +As eoSequentialSelect, it is an eoSelectOne to be used within the +eoEaseyEA algo, but conceptually it should be a global eoSelect, as it +selects a bunch of guys in one go (done in the setup function now) + +@ingroup Selectors +*/ +template class eoEliteSequentialSelect: public eoSelectOne +{ + public: + + /** Ctor: sets the current pter to numeric_limits::max() so init will take place first time + not very elegant, maybe ... + */ + eoEliteSequentialSelect(): current(std::numeric_limits::max()) {} + + void setup(const eoPop& _pop) + { + eoPters.resize(_pop.size()); + _pop.shuffle(eoPters); + // now get the best + unsigned int ibest = 0; + const EOT * best = eoPters[0]; + if (_pop.size() == 1) + 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]; + } + // and put it upfront + const EOT *ptmp = eoPters[0]; + eoPters[0]=best; + eoPters[ibest] = ptmp; + // exit after setting current + current=0; + } + + virtual const EOT& operator()(const eoPop& _pop) + { + if (current >= _pop.size()) + setup(_pop); + + unsigned eoN = current; + current++; + return *eoPters[eoN] ; + } +private: + unsigned current; + std::vector eoPters; +}; + + +#endif diff --git a/deprecated/eo/src/eoSharing.h b/deprecated/eo/src/eoSharing.h new file mode 100644 index 000000000..170a03b9e --- /dev/null +++ b/deprecated/eo/src/eoSharing.h @@ -0,0 +1,141 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSharing.h + (c) Maarten Keijzer, Marc Schoenauer, 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoSharing_h +#define eoSharing_h + +#include +#include + +/** Sharing is a perf2worth class that implements + * Goldberg and Richardson's basic sharing +*/ + +/** A helper class for Sharing - to hold distances + * + * @ingroup Selectors + * */ +class dMatrix : public std::vector + { + public: + // Ctor : sets size + dMatrix(unsigned _s) : std::vector(_s*_s), rSize(_s) {} + + /** simple accessor */ + double operator()(unsigned _i, unsigned _j) const + { + return this->operator[](_i*rSize + _j); + } + + /** reference - to set values */ + double & operator()(unsigned _i, unsigned _j) + { + return this->operator[](_i*rSize + _j); + } + + /** just in case */ + void printOn(std::ostream & _os) + { + unsigned index=0; + for (unsigned i=0; ioperator[](index++) << " " ; + _os << std::endl; + } + _os << std::endl; + } + + private: + unsigned rSize; // row size (== number of columns!) + }; + + +/** Sharing is a perf2worth class that implements + * Goldberg and Richardson's basic sharing + * see eoSharingSelect for how to use it + * and test/t-eoSharing.cpp for a sample use of both + * @ingroup Selectors +*/ +template +class eoSharing : public eoPerf2Worth +{ +public: + + using eoPerf2Worth::value; + + + /* Ctor requires a distance - cannot have a default distance! */ + eoSharing(double _nicheSize, eoDistance & _dist) : eoPerf2Worth("Sharing"), + nicheSize(_nicheSize), + dist(_dist) + {} + + /** Computes shared fitnesses + */ + void operator()(const eoPop& _pop) + { + unsigned i, j, + pSize=_pop.size(); + if (pSize <= 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 + 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) ); + } + } + + for (i=0; i & dist; // specific distance +}; + + + +#endif diff --git a/deprecated/eo/src/eoSharingSelect.h b/deprecated/eo/src/eoSharingSelect.h new file mode 100644 index 000000000..0754cdd08 --- /dev/null +++ b/deprecated/eo/src/eoSharingSelect.h @@ -0,0 +1,60 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoSharingSelect_h +#define eoSharingSelect_h + +//----------------------------------------------------------------------------- + +#include +#include + +/** 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 + * an eoPerf2Worth + * @ingroup Selectors +*/ + +template +class eoSharingSelect: public eoRouletteWorthSelect +{ +public: + /** Ctor: + * @param _sigma the sigma_share + * @param _dist the distance object to use + */ + eoSharingSelect(double _sigma, eoDistance & _dist): + eoRouletteWorthSelect(sharing), sharing(_sigma, _dist) {} + +private : + eoSharing sharing; // derived from eoPerf2Worth +}; +/** @example t-eoSharing.cpp + */ + +#endif diff --git a/deprecated/eo/src/eoShiftMutation.h b/deprecated/eo/src/eoShiftMutation.h new file mode 100644 index 000000000..a9b71d665 --- /dev/null +++ b/deprecated/eo/src/eoShiftMutation.h @@ -0,0 +1,91 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + thomas.legrand@lifl.fr + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoShiftMutation_h +#define eoShiftMutation_h + +//----------------------------------------------------------------------------- + + +/** + * Shift two components of a chromosome. + * + * @ingroup Variators + */ +template class eoShiftMutation: public eoMonOp +{ + public: + + typedef typename EOT::AtomType GeneType; + + /// CTor + eoShiftMutation(){} + + + /// The class name. + virtual std::string className() const { return "eoShiftMutation"; } + + + /** + * Shift two components of the given eoosome. + * @param _eo The cromosome which is going to be changed. + */ + bool operator()(EOT& _eo) + { + + 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); + + // indexes + from=std::min(i,j); + to=std::max(i,j); + + // keep the first component to change + tmp=_eo[to]; + + // shift + for(unsigned int k=to ; k > from ; k--) + _eo[k]=_eo[k-1]; + + // shift the first component + _eo[from]=tmp; + + return true; + } + +}; +/** @example t-eoShiftMutation.cpp + */ + + +//----------------------------------------------------------------------------- +#endif diff --git a/deprecated/eo/src/eoSigBinaryFlight.h b/deprecated/eo/src/eoSigBinaryFlight.h new file mode 100644 index 000000000..dccf2e5f6 --- /dev/null +++ b/deprecated/eo/src/eoSigBinaryFlight.h @@ -0,0 +1,94 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSigBinaryFlight.h +// (c) OPAC 2007, INRIA Futurs DOLPHIN +/* + This library is free software; you 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: thomas.legrand@lifl.fr + clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOSIGBINARYFLIGHT_H +#define EOSIGBINARYFLIGHT_H + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + + + +/** + * 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 + * + * @ingroup Variators + */ +template < class POT > class eoSigBinaryFlight:public eoBinaryFlight < POT > +{ + +public: + + /** + * Constructor. + */ + eoSigBinaryFlight (){slope = 1;} + eoSigBinaryFlight (unsigned _slope){slope = _slope;} + + + /** + * Sigmoid function + */ + double sigmoid( double _value) + { + return(1/(1+ exp(- _value/slope))); + + } + + /** + * Apply the sigmoid binary flight to a particle. + * + */ + void operator () (POT & _po) + { + + for (unsigned j = 0; j < _po.size (); j++) + { + double sigma=rng.uniform(1); + + if (sigma < sigmoid(_po.velocities[j])) + _po[j]=1; + else + _po[j]=0; + } + + // invalidate the fitness because the positions have changed + _po.invalidate(); + } + +private : + unsigned slope; + +}; + + + +#endif /*EOSIGBINARYFLIGHT_H */ diff --git a/deprecated/eo/src/eoSimpleEDA.h b/deprecated/eo/src/eoSimpleEDA.h new file mode 100644 index 000000000..afbf152f0 --- /dev/null +++ b/deprecated/eo/src/eoSimpleEDA.h @@ -0,0 +1,106 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSimpleEDA_h +#define _eoSimpleEDA_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include + +/** A very simple Estimation of Distribution Algorithm + * + * 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 + * update the distribution + * + * @ingroup Algorithms +*/ + +template class eoSimpleEDA: public eoEDA +{ + public: + + /** Ctor from an eoDistribUpdater, + * plus an eoEval and eoContinue of course. + */ + eoSimpleEDA(eoDistribUpdater& _update, + eoEvalFunc& _eval, + unsigned _popSize, + eoContinue& _continuator + ) : + update(_update), + eval(_eval), + popSize(_popSize), + continuator(_continuator) + {} + + /** The algorithm: + * generate pop from distrib, + * evaluate pop, + * update distrib + */ + virtual void operator()(eoDistribution& _distrib) + { + eoPop pop(popSize, _distrib); + do + { + try + { + apply(_distrib, pop); // re-init. of _pop from distrib + + apply(eval, pop); // eval of current population + + 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 ); + } + } while ( continuator( pop ) ); + } + + private: + eoDistribUpdater & update; + + eoEvalFunc& eval; + + unsigned popSize; + + eoContinue& continuator; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/eoSocialNeighborhood.h b/deprecated/eo/src/eoSocialNeighborhood.h new file mode 100644 index 000000000..944031f9d --- /dev/null +++ b/deprecated/eo/src/eoSocialNeighborhood.h @@ -0,0 +1,125 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSocialNeighborhood.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOSOCIALNEIGHBORHOOD_H_ +#define EOSOCIALNEIGHBORHOOD_H_ + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + +/** + * Derivated from eoNeighborhood. Just takes relationships into account. + * The neighborhood is defined as a list of indices corresponding to particles. + * Also contains ONE particle considered as the best of the neighborhood. + * + * @ingroup Selectors + */ +template < class POT > class eoSocialNeighborhood : public eoNeighborhood +{ +public: + + eoSocialNeighborhood(){} + + /** + * Put a particle (identified by its indice in its population) in the neighborhood. + * @param _oneIndice - The indice of the particle in its population. + */ + void put(unsigned _oneIndice) + { + indicesList.push_back(_oneIndice); + } + + /** + * 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. + */ + bool contains(unsigned _oneIndice) + { + for (unsigned i=0;i< indicesList.size();i++) + { + if (indicesList[i]==_oneIndice) + return true; + } + return false; + } + + /** + * Return the list of particle indices as a vector. + */ + std::vector getInformatives() + { + return indicesList; + } + + /** + * Return the size of the neighborhood. + */ + unsigned size() + { + return indicesList.size(); + + } + + /** + * Return the "_index-th" particle of the neighborhood. + * Throw an exception if its not contained in the neighborhood. + */ + unsigned get(unsigned _index) + { + if (_index < size()) + return indicesList[_index]; + else{ + std::string s; + s.append (" Invalid indice in eoSocialNeighborhood "); + throw std::runtime_error (s); + } + } + + /** + * Return the best particle of the neighborhood. + * The topology is expected to get it. + */ + POT & best() + { + return lBest; + } + + /** + * Set the best particle of the neighborhood. + * The topology is expected to set it. + */ + void best(POT _particle) + { + lBest=_particle; + } + +protected: + std::vector indicesList; // The list of particles as a vector of indices + POT lBest; // the best particle of the neighborhood +}; + + +#endif /* EOSOCIALNEIGHBORHOOD_H_ */ diff --git a/deprecated/eo/src/eoStandardFlight.h b/deprecated/eo/src/eoStandardFlight.h new file mode 100644 index 000000000..228839eb7 --- /dev/null +++ b/deprecated/eo/src/eoStandardFlight.h @@ -0,0 +1,109 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStandardFlight.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOSTANDARDFLIGHT_H +#define EOSTANDARDFLIGHT_H + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + + + +/** Standard flight for particle swarm optimization. Derivated from abstract eoFlight, + * just adds the velocities to the current position of the particle + * and invalidates its fitness + * + * @ingroup Variators + */ +template < class POT > class eoStandardFlight:public eoFlight < POT > +{ + +public: + + /* + * Each element for the postion evaluation is expected to be of type PositionType. + */ + typedef typename POT::AtomType PositionType; + + + /** Constructor without bounds. + * + */ + eoStandardFlight ():bnds (*(new eoRealVectorNoBounds(0))){} + + + /** Constructor for continuous flight with real bounds: expects a eoRealVectorBounds object for bound + * control. + * @param _bounds - An eoRealVectorBounds + */ + eoStandardFlight (eoRealVectorBounds & _bounds):bnds (_bounds){} + + + /** Constructor for continuous flight with real bounds: expects a min and a + * max to build the same real bounds for all the positions. + * WARNING: _min and max MUST be double as the position type + * @param _dim - The dimension of the bounds = the dimension of the position + * @param _min - The lower bound to use for all the positions + * @param _max - The upper bound to use for all the positions + */ + eoStandardFlight (const unsigned _dim,const double & _min,const double & _max ):bnds (*(new eoRealVectorBounds(_dim,_min,_max))){} + + + /** + * Apply the standard flight to a particle : position:=position + velocity + * and ... invalidates the particle's fitness + */ + void operator () (POT & _po) + { + // need to resize the bounds even if there are dummy because of "isBounded" call + bnds.adjust_size(_po.size()); + + for (unsigned j = 0; j < _po.size (); j++) + { + PositionType newPosition; + + // tmp position + newPosition = _po[j] + _po.velocities[j]; + + /* check bounds */ + if (bnds.isMinBounded(j)) + newPosition=std::max(newPosition,bnds.minimum(j)); + if (bnds.isMaxBounded(j)) + newPosition=std::min(newPosition,bnds.maximum(j)); + + _po[j]=newPosition; + } + // invalidate the fitness because the positions have changed + _po.invalidate(); + } + +protected: + eoRealVectorBounds & bnds; +}; + + + + +#endif /*EOSTANDARDFLIGHT_H */ diff --git a/deprecated/eo/src/eoStandardVelocity.h b/deprecated/eo/src/eoStandardVelocity.h new file mode 100644 index 000000000..62abd487b --- /dev/null +++ b/deprecated/eo/src/eoStandardVelocity.h @@ -0,0 +1,195 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStandardVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOSTANDARDVELOCITY_H +#define EOSTANDARDVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + +/** 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 +* global. Otherwise, lbest is a "local best", i.e the best in a neighborhood. +* +* @ingroup Variators +*/ +template < class POT > class eoStandardVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** 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. + * 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 & _c1, + const VelocityType & _c2, + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + omega (_w), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** 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. + * 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 + */ + eoStandardVelocity (eoTopology < POT > & _topology, + const VelocityType & _w, + const VelocityType & _c1, + const VelocityType & _c2, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + omega (_w), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _gen - The eo random generator, default=rng + */ + eoStandardVelocity (eoTopology < POT > & _topology, + const VelocityType & _w, + const VelocityType & _c1, + const VelocityType & _c2, + eoRng & _gen = rng): + topology(_topology), + omega (_w), + c1 (_c1), + c2 (_c2), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen) + {} + + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * into the topology. + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r1; + VelocityType r2; + + VelocityType newVelocity; + + // cast the learning factors to VelocityType + r1 = (VelocityType) rng.uniform (1) * c1; + r2 = (VelocityType) rng.uniform (1) * c2; + + // 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]); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + //! 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; + + 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/deprecated/eo/src/eoStarTopology.h b/deprecated/eo/src/eoStarTopology.h new file mode 100644 index 000000000..02df64a98 --- /dev/null +++ b/deprecated/eo/src/eoStarTopology.h @@ -0,0 +1,141 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStarTopology.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOSTARTOPOLOGY_H_ +#define EOSTARTOPOLOGY_H_ + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + + +/** + * Topology dedicated to "globest best" strategy for particle swarm optimization. + * All the particles of the swarm belong to the same and only social neighborhood. + * The global best is stored and updated using the eoSocialNeighborhood. +* +* @ingroup Selectors + */ +template < class POT > class eoStarTopology:public eoTopology +{ + +public: + + /** + * The only Ctor. No parameter required. + */ + eoStarTopology ():isSetup(false){} + + + /** + * Builds the only neighborhood that contains all the particles of the given population. + * Also initializes the global best particle with the best particle of the given population. + * @param _pop - The population used to build the only neighborhood. + * @return + */ + void setup(const eoPop & _pop) + { + if (!isSetup){ + + // put all the particles in the only neighborhood + for (unsigned i=0;i < _pop.size();i++) + neighborhood.put(i); + + // set the initial global best as the best initial particle + neighborhood.best(_pop.best_element()); + + isSetup=true; + } + else + { + // Should activate this part ? + /* + std::string s; + s.append (" Linear topology already setup in eoStarTopology"); + throw std::runtime_error (s); + */ + } + } + + /* + * Update the best fitness of the given particle if it's better. + * Also replace the global best by the given particle if it's better. + * @param _po - The particle to update + * @param _indice - The indice of the given particle in the population + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + // 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]; + } + // update the global best if the given particle is "better" + if (_po.fitness() > neighborhood.best().fitness()) + { + neighborhood.best(_po); + } + } + + + /** + * Return the global best particle. + * @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) {return (neighborhood.best());} + + /* + * Return the global best of the topology + */ + + virtual POT & globalBest(const eoPop& _pop) + { + return neighborhood.best(); + } + + + /** + * Print the structure of the topology on the standard output. + */ + void printOn() + { + std::cout << "{" ; + for (unsigned i=0;i< neighborhood.size();i++) + std::cout << neighborhood.get(i) << " "; + std::cout << "}" << std::endl; + } + + + +protected: + eoSocialNeighborhood neighborhood; // the only neighborhood + bool isSetup; +}; + +#endif /*EOSTARTOPOLOGY_H_ */ diff --git a/deprecated/eo/src/eoSteadyFitContinue.h b/deprecated/eo/src/eoSteadyFitContinue.h new file mode 100644 index 000000000..229d93bc1 --- /dev/null +++ b/deprecated/eo/src/eoSteadyFitContinue.h @@ -0,0 +1,119 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSteadyFitContinue_h +#define _eoSteadyFitContinue_h + +#include +#include + +/** + A continuator: does a minimum number of generations, then + stops whenever a given number of generations takes place without improvement + + @ingroup Continuators +*/ +template< class EOT> +class eoSteadyFitContinue: public eoContinue +{ +public: + typedef typename EOT::Fitness Fitness; + + /// Ctor for setting a + eoSteadyFitContinue( unsigned long _minGens, unsigned long _steadyGens) + : 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) + : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGen), + steadyState(_currentGen>_minGens), thisGenerationPlaceHolder(0), + thisGeneration(_currentGen){}; + + /** Returns false when a certain number of generations is + * reached withtout improvement */ + virtual bool operator() ( const eoPop& _vEO ) { + thisGeneration++; + + Fitness bestCurrentFitness = _vEO.nth_element_fitness(0); + + if (steadyState) { // already after MinGenenerations + if (bestCurrentFitness > bestSoFar) { + 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 > repMinGenerations) { // go to steady state + 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.) + 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; + repSteadyGenerations = _sg; + reset(); + }; + + /// 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 std::string className(void) const { return "eoSteadyFitContinue"; } +private: + unsigned long repMinGenerations; + unsigned long repSteadyGenerations; + bool steadyState; + unsigned long thisGenerationPlaceHolder; + unsigned long& thisGeneration; + unsigned int lastImprovement; + Fitness bestSoFar; +}; + +#endif diff --git a/deprecated/eo/src/eoStochTournamentSelect.h b/deprecated/eo/src/eoStochTournamentSelect.h new file mode 100644 index 000000000..650041296 --- /dev/null +++ b/deprecated/eo/src/eoStochTournamentSelect.h @@ -0,0 +1,67 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + */ + +#ifndef eoStochTournamentSelect_h +#define eoStochTournamentSelect_h + +#include +#include // accumulate +#include // eoSelectOne +#include // stochastic_tournament + +/** eoStochTournamentSelect: a selection method that selects ONE individual by + binary stochastic tournament + -MS- 24/10/99 + + @ingroup Selectors + */ +template class eoStochTournamentSelect: public eoSelectOne +{ + public: + + /// + eoStochTournamentSelect(double _Trate = 1.0 ) : eoSelectOne(), Trate(_Trate) + { + // consistency checks + if (Trate < 0.5) { + std::cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n"; + Trate = 0.55; + } + if (Trate > 1) { + std::cerr << "Warning, Tournament rate should be < 1\nAdjusted to 1\n"; + Trate = 1; + } + } + + /** Perform the stochastic tournament */ + virtual const EOT& operator()(const eoPop& pop) + { + return stochastic_tournament(pop, Trate); + } + +private: + double Trate; +}; + +#endif diff --git a/deprecated/eo/src/eoStochasticUniversalSelect.h b/deprecated/eo/src/eoStochasticUniversalSelect.h new file mode 100644 index 000000000..fb1669ecc --- /dev/null +++ b/deprecated/eo/src/eoStochasticUniversalSelect.h @@ -0,0 +1,110 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStochasticUniversalSelect.h +// (c) Maarten Keijzer 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@cs.vu.nl + */ +//----------------------------------------------------------------------------- + +#ifndef eoStochasticUniversalSelect_h +#define eoStochasticUniversalSelect_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +/** eoStochasticUniversalSelect: select an individual proportional to her stored fitness + value, but in contrast with eoStochasticUniversalSelect, get rid of most finite sampling effects + by doing all selections in one go, using a single random number. + + @ingroup Selectors +*/ +template class eoStochasticUniversalSelect: public eoSelectOne +{ +public: + /// Sanity check + eoStochasticUniversalSelect(const eoPop& pop = eoPop()) + { + if (minimizing_fitness()) + throw std::logic_error("eoStochasticUniversalSelect: minimizing fitness"); + } + + void setup(const eoPop& _pop) + { + if (_pop.size() == 0) return; + + std::vector cumulative(_pop.size()); + + cumulative[0] = _pop[0].fitness(); + for (unsigned i = 1; i < _pop.size(); ++i) + { + cumulative[i] = _pop[i].fitness() + cumulative[i-1]; + } + + indices.reserve(_pop.size()); + indices.resize(0); + + double fortune = rng.uniform() * cumulative.back(); + double step = cumulative.back() / double(_pop.size()); + + unsigned i = std::upper_bound(cumulative.begin(), cumulative.end(), fortune) - cumulative.begin(); + + while (indices.size() < _pop.size()) { + + 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; + } + } + // shuffle + for (int i = indices.size() - 1; i > 0; --i) { + int j = rng.random(i+1); + std::swap(indices[i], indices[j]); + } + } + + /** do the selection, + */ + const EOT& operator()(const eoPop& _pop) + { + if (indices.empty()) setup(_pop); + + unsigned index = indices.back(); + indices.pop_back(); + return _pop[index]; + } + +private : + + typedef std::vector IndexVec; + IndexVec indices; +}; +/** @example t-eoRoulette.cpp + */ + +#endif diff --git a/deprecated/eo/src/eoSurviveAndDie.h b/deprecated/eo/src/eoSurviveAndDie.h new file mode 100644 index 000000000..63cf22197 --- /dev/null +++ b/deprecated/eo/src/eoSurviveAndDie.h @@ -0,0 +1,197 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSurviveAndDie.h + (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSurviveAndDie_h +#define _eoSurviveAndDie_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** +eoSurviveAndDie: takes a population (first argument), +kills the ones that are to die, +puts the ones that are to survive into the second argument +removes them from the first pop argument + +@class eoSurviveAndDie +@class eoDeterministicSurviveAndDie, +@class eoDeterministicSaDReplacement +*/ + +/** @addtogroup Replacors + * @{ + */ + +/** eoSurviveAndDie +A pure abstract class, to store the howmany's +*/ +template +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) + {} + +protected: + eoHowMany howmanySurvive; + eoHowMany howmanyDie; + +}; + +/** An instance (theonly one as of today, Dec. 20, 2000) of an + eoSurviveAndDie, that does everything deterministically + + Used in eoDeterministicSaDReplacement. +*/ +template +class eoDeterministicSurviveAndDie : public eoSurviveAndDie +{ +public: + + using eoSurviveAndDie< EOT >::howmanyDie; + using eoSurviveAndDie< EOT >::howmanySurvive; + + /** constructor */ + eoDeterministicSurviveAndDie(double _survive, double _die, bool _interpret_as_rate = true) + : eoSurviveAndDie< EOT >(_survive, _die, _interpret_as_rate) + {} + + + void operator()(eoPop & _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(); + + // 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); + } + +}; + +/** +eoDeterministicSaDReplacement: replacement strategy that is just, in sequence + saves best and kill worse from parents ++ saves best and kill worse from offspring ++ merge remaining (neither save nor killed) parents and offspring ++ reduce that merged population += returns reduced pop + best parents + best offspring + +An obvious use is as strong elitist strategy, + i.e. preserving best parents, and reducing + (either offspring or parents+offspring) +*/ +template +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) + {} + + /** 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) + {} + + void operator()(eoPop& _parents, eoPop& _offspring) + { + unsigned pSize = _parents.size(); // target number of individuals + + eoPop luckyParents; // to hold the absolute survivors + sAdParents(_parents, luckyParents); + + 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"); + + plus(_parents, _offspring); // all that remain in _offspring + + reduceGlobal(_offspring, pSize - survivorSize); + plus(luckyParents, _offspring); + plus(luckyOffspring, _offspring); + + _parents.swap(_offspring); + + } + +private : + eoReduce& reduceGlobal; + eoDeterministicSurviveAndDie sAdParents; + eoDeterministicSurviveAndDie sAdOffspring; + // plus helper (could be replaced by operator+= ???) + eoPlus plus; + // the default reduce: deterministic truncation + eoTruncate truncate; +}; + + +/** @} */ + +#endif diff --git a/deprecated/eo/src/eoSwapMutation.h b/deprecated/eo/src/eoSwapMutation.h new file mode 100644 index 000000000..58d3cf604 --- /dev/null +++ b/deprecated/eo/src/eoSwapMutation.h @@ -0,0 +1,82 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + thomas.legrand@lifl.fr + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoSwapMutation_h +#define eoSwapMutation_h + +//----------------------------------------------------------------------------- + + +/** + * Swap two components of a chromosome. + * + * @ingroup Variators + */ +template class eoSwapMutation: public eoMonOp +{ + public: + + /// CTor + eoSwapMutation(const unsigned _howManySwaps=1): howManySwaps(_howManySwaps) + { + // 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"; } + + /** + * Swap two components of the given chromosome. + * @param chrom The cromosome which is going to be changed. + */ + bool operator()(Chrom& chrom) + { + 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]); + } + return true; + } + + private: + unsigned int howManySwaps; +}; +/** @example t-eoSwapMutation.cpp + */ + +//----------------------------------------------------------------------------- +#endif diff --git a/deprecated/eo/src/eoSyncEasyPSO.h b/deprecated/eo/src/eoSyncEasyPSO.h new file mode 100644 index 000000000..d0a82059a --- /dev/null +++ b/deprecated/eo/src/eoSyncEasyPSO.h @@ -0,0 +1,260 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSyncEasyPSO.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOSYNCEASYPSO_H +#define _EOSYNCEASYPSO_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** An easy-to-use synchronous particle swarm algorithm; you can use any particle, +* 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 +* +* @ingroup Algorithms +*/ +template < class POT > class eoSyncEasyPSO:public eoPSO < POT > +{ +public: + + /** Full constructor + * @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s) + * @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 + * to modify the positions according to the velocities + */ + eoSyncEasyPSO ( + eoInitializerBase &_init, + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity, + eoFlight < POT > &_flight): + init(_init), + continuator (_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + velocity (_velocity), + flight (_flight) + {} + + + /** Constructor without eoFlight. For special cases when the flight is performed withing the velocity. + * @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s) + * @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 + */ + eoSyncEasyPSO ( + eoInitializerBase &_init, + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity): + init(_init), + continuator (_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + velocity (_velocity), + flight (dummyFlight) + {} + + /** Full constructor - Can be used in parallel + * @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s) + * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system + * @param _eval - An eoPopEvalFunc + * @param _velocity - An eoVelocity that defines how to compute the velocities + * @param _flight - An eoFlight + */ + eoSyncEasyPSO ( + eoInitializerBase &_init, + eoContinue < POT > &_continuator, + eoPopEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity, + eoFlight &_flight): + init(_init), + continuator (_continuator), + eval (dummyEval), + loopEval(dummyEval), + popEval(_eval), + velocity (_velocity), + flight (_flight) + {} + + + /** 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 + * to modify the positions according to the velocities + */ + eoSyncEasyPSO ( + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity, + eoFlight < POT > &_flight): + init(dummyInit), + continuator (_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + velocity (_velocity), + flight (_flight) + {} + + + /** Constructor without eoFlight nor eoInitializer. For special cases when the flight is performed withing the velocity. + * @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 + */ + eoSyncEasyPSO ( + eoContinue < POT > &_continuator, + eoEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity): + init(dummyInit), + continuator (_continuator), + eval (_eval), + loopEval(_eval), + popEval(loopEval), + velocity (_velocity), + flight (dummyFlight) + {} + + /** Full constructor - Can be used in parallel + * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system + * @param _eval - An eoPopEvalFunc + * @param _velocity - An eoVelocity that defines how to compute the velocities + * @param _flight - An eoFlight + */ + eoSyncEasyPSO ( + eoContinue < POT > &_continuator, + eoPopEvalFunc < POT > &_eval, + eoVelocity < POT > &_velocity, + eoFlight &_flight): + init(dummyInit), + continuator (_continuator), + eval (dummyEval), + loopEval(dummyEval), + popEval(_eval), + velocity (_velocity), + flight (_flight) + {} + + /// Apply a few iteration of flight to the population (=swarm). + virtual void operator () (eoPop < POT > &_pop) + { + + try + { + // initializes the topology, velocity, best particle(s) + init(); + + // just to use a loop eval + eoPop empty_pop; + + do + { + // perform velocity evaluation + velocity.apply (_pop); + + // apply the flight + flight.apply (_pop); + + // evaluate the position (with a loop eval, empty_swarm IS USELESS) + popEval(empty_pop,_pop); + + // update the topology (particle and local/global best(s)) + velocity.updateNeighborhood(_pop); + + } + while (continuator (_pop)); + + } + catch (std::exception & e) + { + std::string s = e.what (); + s.append (" in eoSyncEasyPSO"); + throw std::runtime_error (s); + } + + } + +protected: + + eoInitializerBase &init; + eoContinue < POT > &continuator; + + eoEvalFunc < POT > &eval; + eoPopLoopEval loopEval; + eoPopEvalFunc& popEval; + + eoVelocity < POT > &velocity; + 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 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 + */ + + +#endif /*_EOSYNCEASYPSO_H*/ diff --git a/deprecated/eo/src/eoTimeContinue.h b/deprecated/eo/src/eoTimeContinue.h new file mode 100644 index 000000000..d49f5ea56 --- /dev/null +++ b/deprecated/eo/src/eoTimeContinue.h @@ -0,0 +1,87 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoTimeContinue.h +// (c) OPAC Team (LIFL), Dolphin Project (INRIA), 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOTIMECONTINUE_H +#define _EOTIMECONTINUE_H + +#include + +#include +#include + +/** + * Termination condition until a running time is reached. + * + * @ingroup Continuators + */ +template < class EOT > +class eoTimeContinue: public eoContinue +{ +public: + + /** + * Ctor. + * @param _max maximum running time + */ + eoTimeContinue(time_t _max): max(_max) + { + start = time(NULL); + } + + + /** + * Returns false when the running time is reached. + * @param _pop the population + */ + virtual bool operator() (const eoPop < EOT > & _pop) + { + time_t elapsed = (time_t) difftime(time(NULL), start); + if (elapsed >= max) + { + eo::log << eo::progress << "STOP in eoTimeContinue: Reached maximum time [" << elapsed << "/" << max << "]" << std::endl; + return false; + } + return true; + } + + + /** + * Class name + */ + virtual std::string className(void) const + { + return "eoTimeContinue"; + } + + +private: + + /** maximum running time */ + time_t max; + /** starting time */ + time_t start; + +}; + +#endif diff --git a/deprecated/eo/src/eoTopology.h b/deprecated/eo/src/eoTopology.h new file mode 100644 index 000000000..a12bf43dc --- /dev/null +++ b/deprecated/eo/src/eoTopology.h @@ -0,0 +1,86 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoTopology.h +// (c) OPAC 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 + 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: thomas.legrand@inria.fr + clive.canape@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOTOPOLOGY_H_ +#define EOTOPOLOGY_H_ + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + + +/** + * Defines the interface of a swarm topology. Can be static (usually the case for the social topologies) + * or dynamic. It's the same interface for both social and physical topologies. ("social" topology means + * social-neighborhood-based toplogy and so on ...) + * + * @ingroup Selectors + * @ingroup Core + */ +template < class POT > class eoTopology:public eoPop < POT > +{ +public: + + /** + * Builds the neighborhoods contained in the topology. + */ + virtual void setup(const eoPop &)=0; + + /** + * Updates the neighborhood of the given particle and its indice in the population + */ + virtual void updateNeighborhood(POT & ,unsigned)=0; + + + /** + * Updates the neighborhood of the given particle thanks to a whole population (used for distributed or synchronous PSO) + */ + virtual void updateNeighborhood(eoPop < POT > &_pop) + { + for (unsigned i = 0; i < _pop.size (); i++) + updateNeighborhood(_pop[i],i); + } + + + /** + * Builds the neighborhoods contained in the topology. + */ + virtual POT & best (unsigned ) = 0; + + + /* + * Return the global best of the topology + */ + virtual POT & globalBest() = 0; + + + /** + * Prints the neighborhoods contained in the topology. + */ + virtual void printOn() = 0; +}; + + +#endif /*EOTOPOLOGY_H_ */ diff --git a/deprecated/eo/src/eoTransform.h b/deprecated/eo/src/eoTransform.h new file mode 100644 index 000000000..f8823382a --- /dev/null +++ b/deprecated/eo/src/eoTransform.h @@ -0,0 +1,43 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoTransform_h +#define _eoTransform_h + + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + +/** +eoTransform transforms a population by applying genetic operators on it. + +@ingroup Combination +@ingroup Core +*/ +template +class eoTransform : public eoUF&, void> +{}; + +#endif diff --git a/deprecated/eo/src/eoTruncSelect.h b/deprecated/eo/src/eoTruncSelect.h new file mode 100644 index 000000000..e46b39bc3 --- /dev/null +++ b/deprecated/eo/src/eoTruncSelect.h @@ -0,0 +1,75 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoTruncSelect_h +#define _eoTruncSelect_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +//----------------------------------------------------------------------------- + +/** eoTruncSelect selects individuals after truncating the population + * 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, + * + * @ingroup Selectors +*/ +template +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) + : select(_select), howMany(_howMany) {} + + /** + The implementation repeatidly selects an individual + + @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) + */ + 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; +}; + +#endif diff --git a/deprecated/eo/src/eoTruncatedSelectMany.h b/deprecated/eo/src/eoTruncatedSelectMany.h new file mode 100644 index 000000000..1b3bad726 --- /dev/null +++ b/deprecated/eo/src/eoTruncatedSelectMany.h @@ -0,0 +1,119 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoTruncatedSelectMany_h +#define _eoTruncatedSelectMany_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** 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, + and push them to the back of the destination population. + + 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 + the population to discard the worst guys before doing the selection + + However, the same result can be obtained by embedding an + eoTruncatedSelectOne into an eoSelectMany ... + + @ingroup Selectors +*/ +template +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) {} + + // Ctor with eoHowManys + eoTruncatedSelectMany(eoSelectOne& _select, + eoHowMany _howManyGenitors, eoHowMany _howManyFertile) + : select(_select), howManyGenitors(_howManyGenitors), + howManyFertile(_howManyFertile) {} + + /** + The implementation repeatidly selects an individual + + @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) + */ + virtual void operator()(const eoPop& _source, eoPop& _dest) + { + unsigned target = howManyGenitors(_source.size()); + + _dest.resize(target); + + unsigned nbFertile = howManyFertile(_source.size()); + + //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); + } + 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 + + 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); + } + } + +private : + eoSelectOne& select; // selector for one guy + eoHowMany howManyGenitors; // number of guys to select + eoHowMany howManyFertile; // number of fertile guys +}; + +#endif diff --git a/deprecated/eo/src/eoTruncatedSelectOne.h b/deprecated/eo/src/eoTruncatedSelectOne.h new file mode 100644 index 000000000..e86cce81d --- /dev/null +++ b/deprecated/eo/src/eoTruncatedSelectOne.h @@ -0,0 +1,112 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoTruncatedSelectOne_h +#define _eoTruncatedSelectOne_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** 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. + + @ingroup Selectors +*/ +template +class eoTruncatedSelectOne : public eoSelectOne +{ +public: + /** Ctor from rate and bool */ + 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) + : select(_select), howManyFertile(_howManyFertile), + tmpPop(), actualPop(tmpPop) + {} + + + /** setup procedures: fills the temporary population with the fertile guys */ + void setup(const eoPop& _source) + { + unsigned fertile = howManyFertile(_source.size()); + if (fertile == _source.size()) // noting to do, all are fertile + { + 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& _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 +}; + +#endif diff --git a/deprecated/eo/src/eoTwoOptMutation.h b/deprecated/eo/src/eoTwoOptMutation.h new file mode 100644 index 000000000..054f223ea --- /dev/null +++ b/deprecated/eo/src/eoTwoOptMutation.h @@ -0,0 +1,86 @@ +//----------------------------------------------------------------------------- +// eoTwoOptMutation.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 +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 +thomas.legrand@lifl.fr +Marc.Schoenauer@polytechnique.fr +mak@dhi.dk +*/ +//----------------------------------------------------------------------------- + +#ifndef eoTwoOptMutation_h +#define eoTwoOptMutation_h + +//----------------------------------------------------------------------------- + + +/** +* Especially designed for combinatorial problem such as the TSP. +* +* @ingroup Variators +*/ +template class eoTwoOptMutation: public eoMonOp +{ +public: + + typedef typename EOT::AtomType GeneType; + + /// CTor + eoTwoOptMutation(){} + + /// The class name. + virtual std::string className() const { return "eoTwoOptMutation"; } + + /** + * + * @param _eo The cromosome which is going to be changed. + */ + bool operator()(EOT& _eo) { + // generate two different indices + unsigned i(eo::rng.random(_eo.size())); + unsigned j; + do { + j = eo::rng.random(_eo.size()); + } while(i == j); + unsigned from(std::min(i,j)); + unsigned to(std::max(i,j)); + unsigned idx((to - from)/2); + + // inverse between from and to + for(unsigned k = 0; k <= idx; ++k) + std::swap(_eo[from+k],_eo[to-k]); + return true; + } + +}; +/** @example t-eoTwoOptMutation.cpp + */ + + +//----------------------------------------------------------------------------- +#endif + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/eoVariableInertiaWeightedVelocity.h b/deprecated/eo/src/eoVariableInertiaWeightedVelocity.h new file mode 100644 index 000000000..a926feee8 --- /dev/null +++ b/deprecated/eo/src/eoVariableInertiaWeightedVelocity.h @@ -0,0 +1,198 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVariableInertiaWeightedVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOVARIABLEINERTIAWEIGHTEDVELOCITY_H +#define EOVARIABLEINERTIAWEIGHTEDVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + + + +/** Inertia variable weight based velocity 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* ( gbest(t) - x(t) ) +* w is updated each time the velocity performer is called. +* (ci given and Ri chosen at random in [0;1]). +* +* @ingroup Core +* @ingroup Variators +*/ +template < class POT > class eoVariableInertiaWeightedVelocity:public eoVelocity < POT > +{ + +public: + + /* + * Each element for the velocity evaluation is expected to be of type VelocityType. + */ + typedef typename POT::ParticleVelocityType VelocityType; + + /** 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. + * 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 + */ + eoVariableInertiaWeightedVelocity (eoTopology < POT > & _topology, + eoWeightUpdater & _weightUpdater, + const VelocityType & _c1, + const VelocityType & _c2 , + eoRealVectorBounds & _bounds, + eoRealBoundModifier & _bndsModifier, + eoRng & _gen = rng): + topology(_topology), + weightUpdater(_weightUpdater), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(_bndsModifier), + gen(_gen){} + + + /** 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. + * 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 + */ + eoVariableInertiaWeightedVelocity (eoTopology < POT > & _topology, + eoWeightUpdater & _weightUpdater, + const VelocityType & _c1, + const VelocityType & _c2, + eoRealVectorBounds & _bounds, + eoRng & _gen = rng): + topology(_topology), + weightUpdater(_weightUpdater), + c1 (_c1), + c2 (_c2), + bounds(_bounds), + bndsModifier(dummyModifier), + gen(_gen){} + + + /** 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 _gen - The eo random generator, default=rng + */ + eoVariableInertiaWeightedVelocity (eoTopology < POT > & _topology, + eoWeightUpdater & _weightUpdater, + const VelocityType & _c1, + const VelocityType & _c2, + eoRng & _gen = rng): + topology(_topology), + weightUpdater(_weightUpdater), + c1 (_c1), + c2 (_c2), + bounds(*(new eoRealVectorNoBounds(0))), + bndsModifier(dummyModifier), + gen(_gen) + {} + + /** + * Evaluate the new velocities of the given particle. Need an indice to identify the particle + * 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) + * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) + * @param _po - A particle + * @param _indice - The indice (into the topology) of the given particle + */ + void operator () (POT & _po,unsigned _indice) + { + VelocityType r1; + VelocityType r2; + + VelocityType newVelocity; + + // cast the learning factors to VelocityType + r1 = (VelocityType) rng.uniform (1) * c1; + r2 = (VelocityType) rng.uniform (1) * c2; + + // need to resize the bounds even if there are dummy because of "isBounded" call + bounds.adjust_size(_po.size()); + + // update the inertia weight + weightUpdater(weight); + + // assign the new velocities + for (unsigned j = 0; j < _po.size (); j++) + { + newVelocity= weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]); + + /* modify the bounds */ + bndsModifier(bounds,j); + + /* check bounds */ + if (bounds.isMinBounded(j)) + newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j)); + if (bounds.isMaxBounded(j)) + newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j)); + + _po.velocities[j]=newVelocity; + } + } + + /** + * Update the neighborhood. + */ + void updateNeighborhood(POT & _po,unsigned _indice) + { + topology.updateNeighborhood(_po,_indice); + } + + + +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. + eoRealBoundModifier & bndsModifier; + + VelocityType weight; + 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/deprecated/eo/src/eoVariableLengthCrossover.h b/deprecated/eo/src/eoVariableLengthCrossover.h new file mode 100644 index 000000000..510fc9b03 --- /dev/null +++ b/deprecated/eo/src/eoVariableLengthCrossover.h @@ -0,0 +1,352 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVariableLengthCrossover.h +// (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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 + mkeijzer@cs.vu.nl + */ +//----------------------------------------------------------------------------- + +#ifndef _eoVariableLengthCrossover_h +#define _eoVariableLengthCrossover_h + +#include +#include + +/** + Base classes for generic crossovers on variable length chromosomes. + +Basically, they exchange genes - we need some matching information to apply +atom crossover +*/ + +/** @addtogroup Variators + * @{ + */ + +/** A helper class for choosing which genes to exchange */ +template +class eoAtomExchange : public eoBF +{ +public: + /** a function to initlialize - to be called before every crossover */ + virtual void randomize(unsigned int, unsigned int){} + /** the inherited className() */ + virtual std::string className() const=0; +}; + +/** Uniform crossover - well, not really, efficient for FixedLength */ +template +class eoUniformAtomExchange: public eoAtomExchange +{ +public: + eoUniformAtomExchange(double _rate=0.5):rate(_rate){} + + /** randomize: fill the mask: the exchange will be simulated first + * to see if sizes are OK, so it must be repeatable : + * the mask has to be a private data, cannot be computed on the fly + */ + void randomize(unsigned _size1, unsigned _size2) + { + mask.resize(_size1 + _size2); + for (unsigned i=0; i<_size1+_size2; i++) + mask[i]=eo::rng.flip(rate); + } + + /** the operator() simply returns the mask booleans in turn */ + bool operator()(unsigned _i, Atom & ) + { + return mask[_i]; + } + + /** inherited className() */ + virtual std::string className() const {return "eoUniformAtomExchange";} + +private: + double rate; + std::vector mask; +}; + +///////////////////////////////////////////////////////////////////// +////// Now the operators themsleves +///////////////////////////////////////////////////////////////////// + +/** Exchange Crossover using an AtomExchange + */ +template +class eoVlAtomExchangeQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires bounds on number of genes + a rate */ + eoVlAtomExchangeQuadOp(unsigned _Min, unsigned _Max, + eoAtomExchange& _atomExchange): + Min(_Min), Max(_Max), atomExchange(_atomExchange) {} + + bool operator()(EOT & _eo1, EOT & _eo2) + { + EOT tmp1, tmp2; // empty individuals + unsigned index=0; + // main loop: until sizes are OK, do only simulated exchange + unsigned i, i1, i2; + do { + // "initialize the AtomExchange + atomExchange.randomize(_eo1.size(), _eo2.size()); + // simulate crossover + i1=i2=0; + for (i=0; i<_eo1.size(); i++) + { + if (atomExchange(i, _eo1[i])) + i1++; + else + i2++; + } + for (i=0; i<_eo2.size(); i++) + { + if (atomExchange(i, _eo2[i])) + i2++; + else + i1++; + } + index++; + } while ( ( (i1Max) || (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; + } + // 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]); + } + for (i=0; i<_eo2.size(); 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 + } + + /** the inherited className */ + virtual std::string className() const + { + std::ostringstream os; + os << "eoVlAtomExchangeQuadOp(" << atomExchange.className() << ")"; + return os.str(); + } + +private: + unsigned Min, Max; + eoAtomExchange & atomExchange; +}; + +/** Crossover using an AtomCrossover. Probably irrelevant in Variable Length - + see eoFlOrBinOp.h and eoFlOrQuadOp.h for the similar Fixed Length operators + */ +template +class eoInnerExchangeQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor: requires bounds on number of genes + a rate */ + eoInnerExchangeQuadOp( eoQuadOp& _op, float _rate = 0.5): + op(_op), rate( _rate ) {} + + /** performs the Atom crossover */ + bool operator()(EOT & _eo1, EOT & _eo2) + { + unsigned size1 = _eo1.size(), size2 = _eo2.size(), minsize = ( size1 > size2)?size2:size1; + bool changed = false; + for ( unsigned i = 0; i < minsize; i ++ ) { + if ( rng.flip( rate ) ) { + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; + } + } + return changed; // should we test that? Yes, but no time now + } + + virtual std::string className() const + { + return "eoInnerExchangeQuadOp(" + op.className() + ")"; + } + +private: + float rate; + eoQuadOp & op; +}; + + + + +/** Direct Uniform Exchange of genes (obsolete, already :-) stays there for historical reasons + +A very primitive version, that does no verification at all!!! +NEEDS to be improved - but no time now :-((( +Especially, if both guys have maximal size, it will take a lot of time +to generate 2 offspring that both are not oversized!!! +Also, we should first check for identical atoms, and copy them to the +offspring, and only after that exchange the other ones (Radcliffe's RRR). + */ +template +class eoVlUniformQuadOp : public eoQuadOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + // default ctor: requires bounds on number of genes + a rate + eoVlUniformQuadOp(unsigned _Min, unsigned _Max, double _rate=0.5) : + Min(_Min), Max(_Max), rate(_rate) {} + + bool operator()(EOT & _eo1, EOT & _eo2) + { + unsigned i; + EOT tmp1, tmp2; + 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! + } + for (i=0; i<_eo2.size(); 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) ); + //! @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; + } + + _eo1.swap(tmp1); + _eo2.swap(tmp2); + return true; // should we test that? + } +private: + unsigned Min, Max; + double rate; +}; + + +/** Direct Uniform Exchange of genes for Variable Length, BINARY version + +A very primitive version, that does no verification at all!!! +NEEDS to be improved - but no time now :-((( +Especially, if both guys have maximal size, it will take some time +to generate even 1 offspring that is not oversized!!! +Also, we should first check for identical atoms, and copy them to the +offspring, and only after that exchange the other ones (Radcliffe's RRR). + */ +template +class eoVlUniformBinOp : public eoBinOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + // default ctor: requires bounds on number of genes + a rate + eoVlUniformBinOp(unsigned _Min, unsigned _Max, double _rate=0.5) : + Min(_Min), Max(_Max), rate(_rate) {} + + bool operator()(EOT & _eo1, const EOT & _eo2) + { + unsigned i; + EOT tmp1; + bool tmpIsOne=true, tmpIsTwo=true; + 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! + } + for (i=0; i<_eo2.size(); i++) + { + if (! eo::rng.flip(rate)) + { + tmp1.push_back(_eo2[i]); + tmpIsOne = false; + } + else + tmpIsTwo = false; + } + index++; + } while ( ( (tmp1.size()Max) ) + && (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; + } + + _eo1.swap(tmp1); + if (tmpIsTwo) + { + // _eo1.fitness(_eo2.fitness()); 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... + } + +private: + unsigned Min, Max; + double rate; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoVariableLengthMutation.h b/deprecated/eo/src/eoVariableLengthMutation.h new file mode 100644 index 000000000..542541d70 --- /dev/null +++ b/deprecated/eo/src/eoVariableLengthMutation.h @@ -0,0 +1,160 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVariableLengthMutation.h +// (c) Marc Schoenauer 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 + 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 + mkeijzer@cs.vu.nl + */ +//----------------------------------------------------------------------------- + +#ifndef _eoVariableLengthMutation_h +#define _eoVariableLengthMutation_h + +#include +#include +#include + +/** + Base classes for generic mutations on variable length chromosomes. + Contains addition and deletion of a gene + + The generic mutations that apply a gene-level mutation to some genes + dont't modify the length, and so are NOT specific to variable-length + Hence they are in file eoFlOr MonOp.h file (FixedLengthOrdered mutations) +*/ + +/* @addtogroup Variators + * @{ + */ + +/** Addition of a gene + Is inserted at a random position - so can be applied to both + order-dependent and order-independent + */ +template +class eoVlAddMutation : public eoMonOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** default ctor + + * @param _nMax max number of atoms + * @param _atomInit an Atom initializer + */ + eoVlAddMutation(unsigned _nMax, eoInit & _atomInit) : + nMax(_nMax), atomInit(_atomInit) {} + + /** operator: actually adds an Atom */ + bool operator()(EOT & _eo) + { + if (_eo.size() >= nMax) + return false; // unmodifed + AtomType atom; + atomInit(atom); + unsigned pos = rng.random(_eo.size()+1); + _eo.insert(_eo.begin()+pos, atom); + return true; + } + + /** inherited className */ + virtual std::string className() const { return "eoVlAddMutation"; } + +private: + unsigned nMax; + eoInit & atomInit; +}; + + +/** A helper class for choosing which site to delete */ +template +class eoGeneDelChooser : public eoUF +{ +public: + virtual std::string className() const =0; + +}; + +/** Uniform choice of gene to delete */ +template +class eoUniformGeneChooser: public eoGeneDelChooser +{ +public: + eoUniformGeneChooser(){} + unsigned operator()(EOT & _eo) + { + return eo::rng.random(_eo.size()); + } + virtual std::string className() const { return "eoUniformGeneChooser"; } +}; + +/** Deletion of a gene + By default at a random position, but a "chooser" can be specified + can of course be applied to both order-dependent and order-independent + */ +template +class eoVlDelMutation : public eoMonOp +{ +public : + + typedef typename EOT::AtomType AtomType; + + /** ctor with an external gene chooser + + * @param _nMin min number of atoms to leave in the individual + * @param _chooser an eoGeneCHooser to choose which one to delete + */ + eoVlDelMutation(unsigned _nMin, eoGeneDelChooser & _chooser) : + nMin(_nMin), uChooser(), chooser(_chooser) {} + + /** ctor with uniform gene chooser - the default + + * @param _nMin min number of atoms to leave in the individual + */ + eoVlDelMutation(unsigned _nMin) : + nMin(_nMin), uChooser(), chooser(uChooser) {} + + /** Do the job (delete one gene) + * @param _eo the EO to mutate + */ + bool operator()(EOT & _eo) + { + if (_eo.size() <= nMin) + return false; // unmodifed + unsigned pos = chooser(_eo); + _eo.erase(_eo.begin()+pos); + return true; + } + + virtual std::string className() const + { + std::ostringstream os; + os << "eoVlDelMutation("< uChooser; + eoGeneDelChooser & chooser; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/eoVector.h b/deprecated/eo/src/eoVector.h new file mode 100644 index 000000000..fce05d117 --- /dev/null +++ b/deprecated/eo/src/eoVector.h @@ -0,0 +1,169 @@ +/* (C) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: eodev-main@lists.sourceforge.net +Old contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk +*/ + +#ifndef _eoVector_h +#define _eoVector_h + +#include +#include +#include +#include + + +/** + @defgroup Representations Representations + + Solution to a given optimization problem are using a given representation, and are called individuals. + + Some of the most classical representations are proposed, but you can create your own one, providing + that it inherits from the EO base class. It will be used as a template parameter in almost all operators. + + @{ +*/ + +/** Base class for fixed length chromosomes + +It just derives from EO and std::vector and redirects the smaller than +operator to EO (fitness based comparison). + +GeneType must have the following methods: void ctor (needed for the +std::vector<>), copy ctor, + +*/ +template +class eoVector : public EO, public std::vector +{ +public: + + using EO::invalidate; + using std::vector::operator[]; + using std::vector::begin; + using std::vector::end; + using std::vector::resize; + using std::vector::size; + + typedef GeneType AtomType; + typedef std::vector ContainerType; + + /** default constructor + + @param _size Length of vector (default is 0) + @param _value Initial value of all elements (default is default value of type GeneType) + */ + eoVector(unsigned _size = 0, GeneType _value = GeneType()) + : EO(), std::vector(_size, _value) + {} + + /// copy ctor abstracting from the FitT + template + eoVector(const eoVector& _vec) : std::vector(_vec) + {} + + // we can't have a Ctor from a std::vector, it would create ambiguity + // with the copy Ctor + void value(const std::vector& _v) + { + if (_v.size() != size()) // safety check + { + if (size()) // NOT an initial empty std::vector + eo::log << eo::warnings << "Warning: Changing size in eoVector assignation" << std::endl; + resize(_v.size()); + } + + std::copy(_v.begin(), _v.end(), begin()); + invalidate(); + } + + /// to avoid conflicts between EO::operator< and std::vector::operator< + bool operator<(const eoVector& _eo) const + { + return EO::operator<(_eo); + } + + /// printing... + virtual void printOn(std::ostream& os) const + { + EO::printOn(os); + os << ' '; + + os << size() << ' '; + + std::copy(begin(), end(), std::ostream_iterator(os, " ")); + } + + /// reading... + virtual void readFrom(std::istream& is) + { + EO::readFrom(is); + + unsigned sz; + is >> sz; + + resize(sz); + unsigned i; + + for (i = 0; i < sz; ++i) + { + AtomType atom; + is >> atom; + operator[](i) = atom; + } + } +}; +/** @example t-eoVector.cpp + */ + +/** Less than + +This is impemented to avoid conflicts between EO::operator< and +std::vector::operator< +*/ +template +bool operator<(const eoVector& _eo1, const eoVector& _eo2) +{ + return _eo1.operator<(_eo2); +} + + +/** Greater than + +This is impemented to avoid conflicts between EO::operator> and +std::vector::operator> +*/ +template +bool operator>(const eoVector& _eo1, const eoVector& _eo2) +{ + return _eo1.operator>(_eo2); +} + + +#endif + +/** @} */ + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/eoVectorParticle.h b/deprecated/eo/src/eoVectorParticle.h new file mode 100644 index 000000000..25cfcc9fa --- /dev/null +++ b/deprecated/eo/src/eoVectorParticle.h @@ -0,0 +1,155 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVectorParticle.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _EOVECTORPARTICLE_H +#define _EOVECTORPARTICLE_H + +#include + + +/** + @addtogroup Representations + @{ +*/ + +/** + * Main class for particle representation of particle swarm optimization. The positions, velocities and the best positions + * associated to the particle are stored as vectors. Inheriting from PO and std::vector, + * tree templates arguments are required: the fitness type (which is also the type of the + * particle's best fitness), the position type and the velocity type. + */ +template < class FitT, class PositionType, class VelocityType > class eoVectorParticle:public PO < FitT >, + public std::vector < + PositionType > +{ + +public: + + using PO < FitT >::invalidate; + using + std::vector < + PositionType >::operator[]; + using + std::vector < + PositionType >::begin; + using + std::vector < + PositionType >::end; + using + std::vector < + PositionType >::size; + + typedef PositionType AtomType; + typedef VelocityType ParticleVelocityType; + + + /** Default constructor. + * @param _size Length of the tree vectors (we expect the same size), default is 0 + * @param _position + * @param _velocity + * @param _bestPositions + */ + eoVectorParticle (unsigned _size = 0,PositionType _position = PositionType (), VelocityType _velocity = VelocityType (), PositionType _bestPositions = PositionType ()):PO < FitT > (),std::vector < PositionType > (_size, _position), bestPositions (_size, _bestPositions), velocities (_size, + _velocity) + { + } + + + // we can't have a Ctor from a std::vector, it would create ambiguity + // with the copy Ctor + void + position (const std::vector < PositionType > &_v) + { + if (_v.size () != size ()) // safety check + { + if (size ()) // NOT an initial empty std::vector + eo::log << eo::warnings << + "Warning: Changing position size in eoVectorParticle assignation" + << std::endl; + resize (_v.size ()); + } + + std::copy (_v.begin (), _v.end (), begin ()); + invalidate (); + } + + /** Resize the tree vectors of the particle: positions, velocities and bestPositions + * @param _size The new size for positions, velocities and bestPositions + */ + void + resize (unsigned _size) + { + std::vector < PositionType >::resize (_size); + bestPositions.resize (_size); + velocities.resize (_size); + } + + + /** Resize the best positions. + * @param _size The new size for the best positions. + */ + void + resizeBestPositions (unsigned _size) + { + bestPositions.resize (_size); + } + + + /** Resize the velocities. + * @param _size The new size for the velocities. + */ + void + resizeVelocities (unsigned _size) + { + 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; + } + + /** + * Print-on a vector-particle + */ + virtual void printOn(std::ostream& os) const + { + PO::printOn(os); + os << ' '; + os << size() << ' '; + std::copy(bestPositions.begin(), bestPositions.end(), std::ostream_iterator(os, " ")); + } + + /* public attributes */ + std::vector < PositionType > bestPositions; + std::vector < ParticleVelocityType > velocities; + +}; + +#endif /*_EOVECTORPARTICLE_H*/ +/** @} */ diff --git a/deprecated/eo/src/eoVelocity.h b/deprecated/eo/src/eoVelocity.h new file mode 100644 index 000000000..e388078c1 --- /dev/null +++ b/deprecated/eo/src/eoVelocity.h @@ -0,0 +1,80 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVelocity.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOVELOCITY_H +#define EOVELOCITY_H + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** + * Abstract class for velocities calculation (particle swarm optimization). + * All the velocities must derivated from eoVelocity. + * + * @ingroup Variators + */ +template < class POT > class eoVelocity:public eoBF < POT &,unsigned , void > +{ +public: + /** + * Apply the velocity computation to a whole given population. + * Used for synchronous PSO. + */ + virtual void apply (eoPop < POT > &_pop) + { + for (unsigned i = 0; i < _pop.size (); i++) + { + this->operator ()(_pop[i],i); + } + + } + + /** + * Update the neighborhood of the given particle. + */ + virtual void updateNeighborhood(POT & ,unsigned /*_indice*/){} + + + /** + * Apply the neighborhood with a whole population (used for distributed or synchronous PSO). + */ + virtual void updateNeighborhood (eoPop < POT > &_pop) + { + for (unsigned i = 0; i < _pop.size (); i++) + { + updateNeighborhood(_pop[i],i); + } + + } + + + virtual eoTopology & getTopology () = 0; + +}; + +#endif /*EOVELOCITY_H_H */ diff --git a/deprecated/eo/src/eoVelocityInit.h b/deprecated/eo/src/eoVelocityInit.h new file mode 100644 index 000000000..8c57a6891 --- /dev/null +++ b/deprecated/eo/src/eoVelocityInit.h @@ -0,0 +1,146 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVelocityInit.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOVELOCITYINIT_H +#define EOVELOCITYINIT_H + + +#include + +#include +#include +#include + +/** + @addtogroup Initializators + @{ + */ + +/** Abstract class for velocities initilization of particle swarm optimization.*/ +template < class POT > class eoVelocityInit:public eoInit < POT > +{ +public: + virtual std::string className (void) const + { + return "eoVelocityInit"; + } +}; + + +/** +* Provides a particle initialized thanks to the eoVelocityInit object given. +*/ +template < class POT > class eoVelocityInitGenerator:public eoF < POT > +{ +public: + + /** Ctor from a plain eoVelocityInit */ + eoVelocityInitGenerator (eoVelocityInit < POT > &_init):init (_init){} + + virtual POT operator () () + { + POT p; + init (p); + return (p); + } + +private: + eoVelocityInit < POT > &init; +}; + +/** + Initializer for fixed length velocities with a single type +*/ +template < class POT > class eoVelocityInitFixedLength:public eoVelocityInit < + POT > +{ +public: + + typedef typename POT::ParticleVelocityType VelocityType; + + eoVelocityInitFixedLength (unsigned _combien, + eoRndGenerator < VelocityType > + &_generator):combien (_combien), + generator (_generator) + { + } + + virtual void operator () (POT & chrom) + { + chrom.resize (combien); + std::generate (chrom.velocities.begin (), chrom.velocities.end (), + generator); + } + +private: + unsigned combien; + /// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics + eoSTLF < VelocityType > generator; +}; + +/** + Initializer for variable length velocitys with a single type +*/ +template < class POT > class eoVelocityInitVariableLength:public eoVelocityInit < + POT > +{ +public: + typedef typename POT::ParticleVelocityType VelocityType; + + /** Ctor from an eoVelocityInit */ + eoVelocityInitVariableLength (unsigned _minSize, unsigned _maxSize, + eoVelocityInit < VelocityType > + &_init):offset (_minSize), + extent (_maxSize - _minSize), init (_init) + { + if (_minSize >= _maxSize) + throw std:: + logic_error + ("eoVelocityInitVariableLength: minSize larger or equal to maxSize"); + } + + + virtual void operator () (POT & _chrom) + { + _chrom.resizeVelocities (offset + rng.random (extent)); + typename std::vector < VelocityType >::iterator it; + for (it = _chrom.velocities.begin (); it < _chrom.velocities.end (); it++) + init (*it); + } + + // accessor to the atom initializer (needed by operator constructs sometimes) + eoInit < VelocityType > &atomInit () + { + return init; + } + +private: + unsigned offset; + unsigned extent; + eoVelocityInit < VelocityType > &init; +}; + +#endif /*EOVELOCITYINIT_H */ + +/** @} */ diff --git a/deprecated/eo/src/eoWeightUpdater.h b/deprecated/eo/src/eoWeightUpdater.h new file mode 100644 index 000000000..d4970eca4 --- /dev/null +++ b/deprecated/eo/src/eoWeightUpdater.h @@ -0,0 +1,41 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoWeightUpdater.h +// (c) OPAC 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 + 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: thomas.legrand@lifl.fr + */ +//----------------------------------------------------------------------------- + +#ifndef EOWEIGHTUPDATER_H +#define EOWEIGHTUPDATER_H + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + +/** + * Abstract class for (inertia) weight updater (particle swarm optimization). + * Used inside classes extending eoVelocity. + * + * @ingroup Core + */ +template < class WeightType > class eoWeightUpdater: public eoUF < WeightType &, void > {}; + + +#endif/*EOWEIGHTUPDATER_H*/ diff --git a/deprecated/eo/src/es.h b/deprecated/eo/src/es.h new file mode 100644 index 000000000..d5dffc2f3 --- /dev/null +++ b/deprecated/eo/src/es.h @@ -0,0 +1,63 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mak@dhi.dk + todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#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 +#include +#include + +// the initialization +#include + +// general operators +#include +#include +#include // for generic operators + +// SBX crossover (following Deb) +#include + +// ES specific operators +#include // Global ES Xover +#include // 2-parents ES Xover + +// the ES-mutations +#include +#include + +#endif diff --git a/deprecated/eo/src/es/CMAParams.cpp b/deprecated/eo/src/es/CMAParams.cpp new file mode 100644 index 000000000..131edb72f --- /dev/null +++ b/deprecated/eo/src/es/CMAParams.cpp @@ -0,0 +1,233 @@ +/* + * C++ification of Nikolaus Hansen's original C-source code for the + * CMA-ES + * + * C++-ificiation performed by Maarten Keijzer (C) 2005. Licensed under + * the LGPL. Original copyright of Nikolaus Hansen can be found below + * + * + * + */ + +/* --------------------------------------------------------- */ +/* --------------------------------------------------------- */ +/* --- File: cmaes.c -------- Author: Nikolaus Hansen --- */ +/* --------------------------------------------------------- */ +/* + * CMA-ES for non-linear function minimization. + * + * Copyright (C) 1996, 2003 Nikolaus Hansen. + * e-mail: hansen@bionik.tu-berlin.de + * + * This library is free software; you 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.1 of the License, or (at your option) any later + * version (see http://www.gnu.org/copyleft/lesser.html). + * + * 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. + * + * */ +/* --- Changes : --- + * 03/03/21: argument const double *rgFunVal of + * cmaes_ReestimateDistribution() was treated incorrectly. + * 03/03/29: restart via cmaes_resume_distribution() implemented. + * 03/03/30: Always max std dev / largest axis is printed first. + * 03/08/30: Damping is adjusted for large mueff. + * 03/10/30: Damping is adjusted for large mueff always. + * 04/04/22: Cumulation time and damping for step size adjusted. + * No iniphase but conditional update of pc. + * Version 2.23. + * */ + +#include +#include + +#include + +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(); + + + if (n == 0) { + return; + } + + defaults(n, maxgen); + + /* handle lambda */ + lambda = parser.createParam( + 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; + } + + /* handle mu */ + mu = parser.createParam( + 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; + } + + /* handle selection weights */ + + int weight_type = parser.createParam( + 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.); + } + } + + } + + /* 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; + + 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(); + + 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]; + } + } + + 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(); + + 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]; + } + } + +} + +void CMAParams::defaults(unsigned n_, unsigned maxgen_) { + n = n_; + maxgen = 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.); + } + + /* 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; + + minStdevs.resize(n); + minStdevs = 0.0; + + initialStdevs.resize(n); + initialStdevs = 0.3; + + +} + + +}// namespace eo diff --git a/deprecated/eo/src/es/CMAParams.h b/deprecated/eo/src/es/CMAParams.h new file mode 100644 index 000000000..905869040 --- /dev/null +++ b/deprecated/eo/src/es/CMAParams.h @@ -0,0 +1,51 @@ +/* + * C++ification of Nikolaus Hansen's original C-source code for the + * CMA-ES. + * + * Copyright (C) 1996, 2003, Nikolaus Hansen + * (C) 2005, Maarten Keijzer + * + * License: LGPL + * + */ + +#ifndef CMAPARAMS_H__ +#define CMAPARAMS_H__ + +#include + +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; + double ccov; /* <- mucov, N */ + + std::valarray minStdevs; /* Minimum standard deviations per coordinate (default = 0.0) */ + std::valarray initialStdevs; /* Initial standard deviations per coordinate (default = 0.3) */ +}; + +} // namespace eo + +#endif diff --git a/deprecated/eo/src/es/CMAState.cpp b/deprecated/eo/src/es/CMAState.cpp new file mode 100644 index 000000000..328552434 --- /dev/null +++ b/deprecated/eo/src/es/CMAState.cpp @@ -0,0 +1,364 @@ +/* + * C++ification of Nikolaus Hansen's original C-source code for the + * CMA-ES + * + * C++-ificiation performed by Maarten Keijzer (C) 2005. Licensed under + * the LGPL. Original copyright of Nikolaus Hansen can be found below + * + * + * Some changes have been made to the original flow and logic of the + * algorithm: + * + * - Numerical issues are now treated 'before' going into the eigenvector decomposition + * (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) + * + * + */ + +/* --------------------------------------------------------- */ +/* --------------------------------------------------------- */ +/* --- File: cmaes.c -------- Author: Nikolaus Hansen --- */ +/* --------------------------------------------------------- */ +/* + * CMA-ES for non-linear function minimization. + * + * Copyright (C) 1996, 2003 Nikolaus Hansen. + * e-mail: hansen@bionik.tu-berlin.de + * + * This library is free software; you 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.1 of the License, or (at your option) any later + * version (see http://www.gnu.org/copyleft/lesser.html). + * + * 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. + * + * */ +/* --- Changes : --- + * 03/03/21: argument const double *rgFunVal of + * cmaes_ReestimateDistribution() was treated incorrectly. + * 03/03/29: restart via cmaes_resume_distribution() implemented. + * 03/03/30: Always max std dev / largest axis is printed first. + * 03/08/30: Damping is adjusted for large mueff. + * 03/10/30: Damping is adjusted for large mueff always. + * 04/04/22: Cumulation time and damping for step size adjusted. + * No iniphase but conditional update of pc. + * Version 2.23. + * */ + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +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) + { + 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; + } + } + + 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; + } + + 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]; + } + + /* 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; + } + + /* calculate norm(ps)^2 */ + double psxps = (ps * ps).sum(); + + + 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) */ + + /* 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; + + 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(); + + /* (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& initial_point, const double initial_sigma) + : pimpl(new CMAStateImpl(params, initial_point, initial_sigma)) {} + +CMAState::~CMAState() { delete pimpl; } +CMAState::CMAState(const CMAState& that) : pimpl(new CMAStateImpl(*that.pimpl )) {} +CMAState& CMAState::operator=(const CMAState& that) { *pimpl = *that.pimpl; return *this; } + +void CMAState::sample(vector& v) const { pimpl->sample(v); } + +void CMAState::reestimate(const vector* >& population, double muBest, double muWorst) { pimpl->reestimate(population, muBest, muWorst); } +bool CMAState::updateEigenSystem(unsigned max_tries, unsigned max_iters) { return pimpl->updateEigenSystem(max_tries, max_iters); } + + +} // namespace eo diff --git a/deprecated/eo/src/es/CMAState.h b/deprecated/eo/src/es/CMAState.h new file mode 100644 index 000000000..85a80c52c --- /dev/null +++ b/deprecated/eo/src/es/CMAState.h @@ -0,0 +1,78 @@ +/* + * C++ification of Nikolaus Hansen's original C-source code for the + * CMA-ES. + * + * Copyright (C) 1996, 2003, Nikolaus Hansen + * (C) 2005, Maarten Keijzer + * + * License: LGPL (see source file) + * + */ + +#ifndef CMASTATE_H_ +#define CMASTATE_H_ + +#include +#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); + ~CMAState(); + CMAState(const CMAState&); + CMAState& operator=(const 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: + * + * 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 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 + * 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 + * + * max_iters = 0 implies 30 * N iterations + * + * 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); +}; + +} // namespace eo + +#endif diff --git a/deprecated/eo/src/es/CMakeLists.txt b/deprecated/eo/src/es/CMakeLists.txt new file mode 100644 index 000000000..b71260fb5 --- /dev/null +++ b/deprecated/eo/src/es/CMakeLists.txt @@ -0,0 +1,56 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the es and cma targets +###################################################################################### + +SET(ES_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) +SET(CMA_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) + +SET(LIBRARY_OUTPUT_PATH ${ES_LIB_OUTPUT_PATH}) # the same output for the two libs + +SET(ES_SOURCES + make_algo_scalar_es.cpp + make_algo_scalar_real.cpp + make_checkpoint_es.cpp + make_checkpoint_real.cpp + make_continue_es.cpp + make_continue_real.cpp + make_genotype_es.cpp + make_genotype_real.cpp + make_op_es.cpp + make_op_real.cpp + make_pop_es.cpp + make_pop_real.cpp + make_run_es.cpp + make_run_real.cpp + ) + +SET(CMA_SOURCES + eig.cpp + CMAState.cpp + CMAParams.cpp + ) + +ADD_LIBRARY(es STATIC ${ES_SOURCES}) +INSTALL(TARGETS es ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +ADD_LIBRARY(cma STATIC ${CMA_SOURCES}) +INSTALL(TARGETS cma ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +###################################################################################### +### 3) Optionnal +###################################################################################### + +SET(ES_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(es PROPERTIES VERSION "${ES_VERSION}") + +SET(CMA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(cma PROPERTIES VERSION "${CMA_VERSION}") + +###################################################################################### diff --git a/deprecated/eo/src/es/ChangeLog b/deprecated/eo/src/es/ChangeLog new file mode 100644 index 000000000..29437b429 --- /dev/null +++ b/deprecated/eo/src/es/ChangeLog @@ -0,0 +1,18 @@ +2006-12-01 Jochen Kpper + + * Makefile.am: Add missing CMA header for distribution. + +2006-11-16 Jochen Kpper + + * 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. + + * eoEsChromInit.h (class eoEsChromInit): Take const-reference to sigma-vector. + include + + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/deprecated/eo/src/es/eig.cpp b/deprecated/eo/src/es/eig.cpp new file mode 100644 index 000000000..d7ddd41da --- /dev/null +++ b/deprecated/eo/src/es/eig.cpp @@ -0,0 +1,258 @@ +/* + * C++ification of Nikolaus Hansen's original C-source code for the + * CMA-ES. These are the eigenvector calculations + * + * C++-ificiation performed by Maarten Keijzer (C) 2005. Licensed under + * the LGPL. Original copyright of Nikolaus Hansen can be found below + * + * This algorithm is held almost completely intact. Some other datatypes are used, + * but hardly any code has changed + * + */ + +/* --------------------------------------------------------- */ +/* --------------------------------------------------------- */ +/* --- File: cmaes.c -------- Author: Nikolaus Hansen --- */ +/* --------------------------------------------------------- */ +/* + * CMA-ES for non-linear function minimization. + * + * Copyright (C) 1996, 2003 Nikolaus Hansen. + * e-mail: hansen@bionik.tu-berlin.de + * + * This library is free software; you 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.1 of the License, or (at your option) any later + * version (see http://www.gnu.org/copyleft/lesser.html). + * + * 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. + * + * */ +/* --- Changes : --- + * 03/03/21: argument const double *rgFunVal of + * cmaes_ReestimateDistribution() was treated incorrectly. + * 03/03/29: restart via cmaes_resume_distribution() implemented. + * 03/03/30: Always max std dev / largest axis is printed first. + * 03/08/30: Damping is adjusted for large mueff. + * 03/10/30: Damping is adjusted for large mueff always. + * 04/04/22: Cumulation time and damping for step size adjusted. + * No iniphase but conditional update of pc. + * Version 2.23. + * */ +#include "eig.h" + +using namespace std; + +/* ========================================================= */ +/* + Householder Transformation einer symmetrischen Matrix + auf tridiagonale Form. + -> n : Dimension + -> ma : symmetrische nxn-Matrix + <- 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 +Householder( int N, square_matrix& ma, valarray& diag, double* neben) +{ + double epsilon; + int i, j, k; + double h, sum, tmp, tmp2; + + for (i = N-1; i > 0; --i) + { + h = 0.0; + if (i == 1) + neben[i] = ma[i][i-1]; + else + { + for (k = i-1, epsilon = 0.0; k >= 0; --k) + epsilon += fabs(ma[i][k]); + + if (epsilon == 0.0) + neben[i] = ma[i][i-1]; + else + { + for(k = i-1, sum = 0.0; k >= 0; --k) + { /* 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 */ + } /* else epsilon */ + } /* else i == 1 */ + diag[i] = h; + } /* for i */ + + 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; k >= 0; --k) + ma[k][j] -= tmp*ma[k][i]; + } /* for j */ + diag[i] = ma[i][i]; + ma[i][i] = 1.0; + for (k = i-1; k >= 0; --k) + ma[k][i] = ma[i][k] = 0.0; + } /* for i */ +} + +/* + QL-Algorithmus mit implizitem Shift, zur Berechnung von Eigenwerten + 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 + <- 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) +{ + int i, j, k, kp1, l; + double tmp, diff, cneben, c1, c2, p; + int iter; + + neben[N-1] = 0.0; + for (i = 0, iter = 0; i < N && iter < maxIter; ++i) + do /* while j != i */ + { + for (j = i; j < N-1; ++j) + { + 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 */ + } while (j != i); + return iter; +} /* QLalgo() */ + +/* ========================================================= */ +/* + 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: + 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 niter) +{ + int ret; + int i, j; + + if (niter == 0) niter = 30*N; + + for (i=0; i < N; ++i) + { + vector::const_iterator row = C[i]; + for (j = 0; j <= i; ++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/deprecated/eo/src/es/eig.h b/deprecated/eo/src/es/eig.h new file mode 100644 index 000000000..65d9c53d2 --- /dev/null +++ b/deprecated/eo/src/es/eig.h @@ -0,0 +1,25 @@ +#ifndef EIG_H__ +#define EIG_H__ + +#include +#include + +namespace eo { +/* ========================================================= */ +/* + Calculating eigenvalues and vectors. + Input: + N: dimension. + C: lower_triangular NxN-matrix. + 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, + int niter = 0); + +} // namespace eo + +#endif diff --git a/deprecated/eo/src/es/eoCMABreed.h b/deprecated/eo/src/es/eoCMABreed.h new file mode 100644 index 000000000..450654a7f --- /dev/null +++ b/deprecated/eo/src/es/eoCMABreed.h @@ -0,0 +1,78 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; fill-column: 80; -*- + +//----------------------------------------------------------------------------- +// eoCMABreed +// (c) Maarten Keijzer 2005 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +//----------------------------------------------------------------------------- + + +#ifndef _EOCMABREED_H +#define _EOCMABREED_H + +#include +#include +#include + +#include + +/// @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()); + + // 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(); + } + + } +}; + + +#endif diff --git a/deprecated/eo/src/es/eoCMAInit.h b/deprecated/eo/src/es/eoCMAInit.h new file mode 100644 index 000000000..2fdb967e0 --- /dev/null +++ b/deprecated/eo/src/es/eoCMAInit.h @@ -0,0 +1,54 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; fill-column: 80; -*- + +//----------------------------------------------------------------------------- +// eoCMAInit +// (c) Maarten Keijzer 2005 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + marc.schoenauer@polytechnique.fr + http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + + +#ifndef _EOCMAINIT_H +#define _EOCMAINIT_H + +#include +#include +#include + +/// @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(); + } +}; + + +#endif diff --git a/deprecated/eo/src/es/eoEsChromInit.h b/deprecated/eo/src/es/eoEsChromInit.h new file mode 100644 index 000000000..c5382890b --- /dev/null +++ b/deprecated/eo/src/es/eoEsChromInit.h @@ -0,0 +1,208 @@ +// +/* (c) Maarten Keijzer 2000, GeNeura Team, 1998 - EEAAX 1999 + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ + + +#ifndef _eoEsChromInit_H +#define _eoEsChromInit_H + +#include +#include +#include +#include + +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + +/** Random Es-chromosome initializer (therefore derived from eoInit) + +@ingroup Real +@ingroup Initializators + + +This class can initialize four types of real-valued genotypes thanks +to tempate specialization of private method create: + +- eoReal just an eoVector +- eoEsSimple + one self-adapting single sigma for all variables +- eoEsStdev a whole std::vector of self-adapting sigmas +- eoEsFull a full self-adapting correlation matrix + +@see eoReal eoEsSimple eoEsStdev eoEsFull eoInit +*/ +template +class eoEsChromInit : public eoRealInitBounded +{ +public: + + using eoRealInitBounded::size; + using eoRealInitBounded::theBounds; + + typedef typename EOT::Fitness FitT; + + /** Constructor + + @param _bounds bounds for uniform initialization + @param _sigma initial value for the stddev + @param _to_scale wether sigma should be multiplied by the range of each variable + added December 2004 - MS (together with the whole comment :-) + */ + eoEsChromInit(eoRealVectorBounds& _bounds, double _sigma = 0.3, bool _to_scale=false) + : eoRealInitBounded(_bounds) + { + // a bit of pre-computations, to save time later (even if some are useless) + // + // first, in the case of one unique sigma + // sigma is scaled by the average range (if that means anything!) + if (_to_scale) + { + double scaleUnique = 0; + for (unsigned i=0; i& _vecSigma) + : eoRealInitBounded(_bounds), uniqueSigma(_vecSigma[0]), vecSigma(_vecSigma) + { + assert(_bounds.size() == size()); + assert(_vecSigma.size() == size()); + } + + + void operator()(EOT& _eo) + { + eoRealInitBounded::operator()(_eo); + create_self_adapt(_eo); + _eo.invalidate(); + } + + +private: + + /** Create intializer + + No adaptive mutation at all + */ + void create_self_adapt(eoReal&) + {} + + + + /** Create intializer + + @overload + + Adaptive mutation through a unique sigma + */ + void create_self_adapt(eoEsSimple& result) + { + // pre-computed in the Ctor + result.stdev = uniqueSigma; + } + + + + /** Create intializer + + @overload + + Adaptive mutation through a std::vector of sigmas + + @todo Should we scale sigmas to the corresponding object variable range? + */ + void create_self_adapt(eoEsStdev& result) + { + // pre-computed in the constructor + result.stdevs = vecSigma; + } + + + + /** Create intializer + + @overload + + Adaptive mutation through a whole correlation matrix + */ + void create_self_adapt(eoEsFull& result) + { + // first the stdevs (pre-computed in the Ctor) + result.stdevs = vecSigma; + unsigned int theSize = size(); + // nb of rotation angles: N*(N-1)/2 (in general!) + result.correlations.resize(theSize*(theSize - 1) / 2); + for (unsigned i=0; i vecSigma; +}; + +#endif + + + +// Local Variables: +// coding: iso-8859-1 +// mode:C++ +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/es/eoEsFull.h b/deprecated/eo/src/es/eoEsFull.h new file mode 100644 index 000000000..a1091c83d --- /dev/null +++ b/deprecated/eo/src/es/eoEsFull.h @@ -0,0 +1,85 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoEsFull.h +// (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoEsFull_h +#define _eoEsFull_h + +#include + +/** +\ingroup Real + + The most complex evolutionary strategy representation. Co-evolving mutation +rates and correlated mutations. +*/ + +template +class eoEsFull : public eoVector +{ +public: + + using eoVector::size; + + + typedef double Type; + + eoEsFull(void) : eoVector() {} + + virtual std::string className(void) const { return "eoEsFull"; } + + void printOn(std::ostream& os) const + { + eoVector::printOn(os); + os << ' '; + std::copy(stdevs.begin(), stdevs.end(), std::ostream_iterator(os, " ")); + os << ' '; + std::copy(correlations.begin(), correlations.end(), std::ostream_iterator(os, " ")); + os << ' '; + } + + void readFrom(std::istream& is) + { + eoVector::readFrom(is); + + stdevs.resize(size()); + + unsigned i; + for (i = 0; i < size(); ++i) + is >> stdevs[i]; + + correlations.resize(size()*(size() - 1) / 2); + + for (i = 0; i < correlations.size(); ++i) + is >> correlations[i]; + } + + std::vector stdevs; + std::vector correlations; +}; + + + +#endif diff --git a/deprecated/eo/src/es/eoEsGlobalXover.h b/deprecated/eo/src/es/eoEsGlobalXover.h new file mode 100644 index 000000000..5be4b5061 --- /dev/null +++ b/deprecated/eo/src/es/eoEsGlobalXover.h @@ -0,0 +1,152 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoEsGlobalXover.h : ES global crossover +// (c) Marc Schoenauer 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + + +#ifndef _eoEsGlobalXover_H +#define _eoEsGlobalXover_H + +#include + +#include +#include +#include + +#include +// needs a selector - here random +#include + +/** Global crossover operator for ES genotypes. + * Uses some Atom crossovers to handle both the object variables + * and the mutation strategy parameters + * + * @ingroup Real + * @ingroup Variators + */ +template +class eoEsGlobalXover: public eoGenOp +{ +public: + typedef typename EOT::Fitness FitT; + + /** + * (Default) Constructor. + */ + eoEsGlobalXover(eoBinOp & _crossObj, eoBinOp & _crossMut) : + crossObj(_crossObj), crossMut(_crossMut) {} + + /// The class name. Used to display statistics + virtual std::string className() const { return "eoEsGlobalXover"; } + + /// The TOTAL number of offspring (here = nb of parents modified in place) + unsigned max_production(void) { return 1; } + + /** + * modifies one parents in the populator + * using 2 new parents for each component! + * + * @param _plop a POPULATOR (not a simple population) + */ + void apply(eoPopulator& _plop) + { + // First, select as many parents as you will have offspring + EOT& parent = *_plop; // select the first parent + + // 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 + } + // then the self-adaptation parameters + cross_self_adapt(parent, _plop.source()); + // dont' forget to invalidate + parent.invalidate(); + } + +private: + + /** Method for cross self-adaptation parameters + + Specialization for eoEsSimple. + */ + void cross_self_adapt(eoEsSimple & _parent, const eoPop >& _pop) + { + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.stdev = realParent1.stdev; + crossMut(_parent.stdev, realParent2.stdev); // apply eoBinOp + } + + /** Method for cross self-adaptation parameters + + Specialization for eoEsStdev. + */ + void cross_self_adapt(eoEsStdev & _parent, const eoPop >& _pop) + { + 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 + } + } + + /** Method for cross self-adaptation parameters + + Specialization for eoEsFull. + */ + void cross_self_adapt(eoEsFull & _parent, const eoPop >& _pop) + { + unsigned i; + // 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 + } + // 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 + } + + } + + // the data + eoRandomSelect sel; + eoBinOp & crossObj; + eoBinOp & crossMut; +}; + +#endif diff --git a/deprecated/eo/src/es/eoEsMutate.h b/deprecated/eo/src/es/eoEsMutate.h new file mode 100644 index 000000000..fd1152685 --- /dev/null +++ b/deprecated/eo/src/es/eoEsMutate.h @@ -0,0 +1,287 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; fill-column: 80; -*- + +//----------------------------------------------------------------------------- +// eoESMute.h : ES mutation +// (c) Maarten Keijzer 2000 & GeNeura Team, 1998 for the EO part +// Th. Baeck 1994 and EEAAX 1999 for the ES part +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + marc.schoenauer@polytechnique.fr + http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + + +#ifndef _EOESMUTATE_H +#define _EOESMUTATE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + +/** ES-style mutation in the large + +@ingroup Real +@ingroup Variators + +Obviously, valid only for eoES*. It is currently valid for three types +of ES chromosomes: +- eoEsSimple: Exactly one stdandard-deviation +- eoEsStdev: As many standard deviations as object variables +- eoEsFull: The whole guacemole: correlations, stdevs and object variables + +Each of these three variant has it's own operator() in eoEsMutate and +intialization is also split into three cases (that share some commonalities) +*/ +template +class eoEsMutate : public eoMonOp< EOT > +{ +public: + + /** Fitness-type */ + typedef typename EOT::Fitness FitT; + + + /** Initialization. + + @param _init Proxy class for initializating the three parameters + eoEsMutate needs + @param _bounds Bounds for the objective variables + */ + eoEsMutate(eoEsMutationInit& _init, eoRealVectorBounds& _bounds) : bounds(_bounds) + { + init(EOT(), _init); // initialize on actual type used + } + + + /** @brief Virtual Destructor */ + virtual ~eoEsMutate() {}; + + + /** Classname. + + Inherited from eoObject @see eoObject + + @return Name of class. + */ + virtual std::string className() const {return "eoESMutate";}; + + + /** Mutate eoEsSimple + + @param _eo Individual to mutate. + */ + virtual bool operator()( eoEsSimple& _eo) + { + _eo.stdev *= exp(TauLcl * rng.normal()); + if (_eo.stdev < stdev_eps) + _eo.stdev = stdev_eps; + // now apply to all + for (unsigned i = 0; i < _eo.size(); ++i) + { + _eo[i] += _eo.stdev * rng.normal(); + } + bounds.foldsInBounds(_eo); + return true; + } + + + /** Standard mutation in ES + + @overload + + Standard mutation of object variables and standard deviations in ESs. + + If there are fewer different standard deviations available than the + dimension of the objective function requires, the last standard deviation is + responsible for ALL remaining object variables. + + @param _eo Individual to mutate. + + @see + Schwefel 1977: Numerische Optimierung von Computer-Modellen mittels der + Evolutionsstrategie, pp. 165 ff. + */ + virtual bool operator()( eoEsStdev& _eo ) + { + double global = TauGlb * rng.normal(); + for (unsigned i = 0; i < _eo.size(); i++) + { + double stdev = _eo.stdevs[i]; + stdev *= exp( global + TauLcl * rng.normal() ); + if (stdev < stdev_eps) + stdev = stdev_eps; + _eo.stdevs[i] = stdev; + _eo[i] += stdev * rng.normal(); + } + bounds.foldsInBounds(_eo); + return true; + } + + + /** Correlated mutations in ES + + @overload + + Mutation of object variables, standard deviations, and their correlations in + ESs. + + @param _eo Individual to mutate. + + @see + - H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80, p. 43, 1980. + - G. Rudolph: Globale Optimierung mit parallelen Evolutionsstrategien, + Diploma Thesis, University of Dortmund, 1990. + */ + virtual bool operator()( eoEsFull & _eo ) + // Code originally from Thomas Bck + { + // First: mutate standard deviations (as for eoEsStdev). + double global = TauGlb * rng.normal(); + unsigned i; + for (i = 0; i < _eo.size(); i++) + { + double stdev = _eo.stdevs[i]; + stdev *= exp( global + TauLcl*rng.normal() ); + if (stdev < stdev_eps) + stdev = stdev_eps; + _eo.stdevs[i] = stdev; + } + // Mutate rotation angles. + for (i = 0; i < _eo.correlations.size(); i++) + { + _eo.correlations[i] += TauBeta * rng.normal(); + if ( fabs(_eo.correlations[i]) > M_PI ) + { + _eo.correlations[i] -= M_PI * (int) (_eo.correlations[i]/M_PI) ; + } + } + // Perform correlated mutations. + unsigned k, n1, n2; + double d1,d2, S, C; + std::vector VarStp(_eo.size()); + for (i = 0; i < _eo.size(); i++) + VarStp[i] = _eo.stdevs[i] * rng.normal(); + unsigned nq = _eo.correlations.size() - 1; + for (k = 0; k < _eo.size()-1; k++) + { + n1 = _eo.size() - k - 1; + n2 = _eo.size() - 1; + for (i = 0; i < k; i++) + { + d1 = VarStp[n1]; + d2 = VarStp[n2]; + S = sin( _eo.correlations[nq] ); + C = cos( _eo.correlations[nq] ); + VarStp[n2] = d1 * S + d2 * C; + VarStp[n1] = d1 * C - d2 * S; + n2--; + nq--; + } + } + for (i = 0; i < _eo.size(); i++) + _eo[i] += VarStp[i]; + bounds.foldsInBounds(_eo); + return true; + } + + + private : + + /** Initialization of simple ES */ + void init(eoEsSimple, eoEsMutationInit& _init) + { + unsigned size = bounds.size(); + TauLcl = _init.TauLcl(); + TauLcl /= sqrt(2*(double) size); + std::cout << "Init: tau local " << TauLcl << std::endl; + } + + + /** Initialization of standard ES + + @overload + */ + void init(eoEsStdev, eoEsMutationInit& _init) + { + unsigned size = bounds.size(); + TauLcl = _init.TauLcl(); + TauGlb = _init.TauGlb(); + // renormalization + TauLcl /= sqrt( 2.0 * sqrt(double(size)) ); + TauGlb /= sqrt( 2.0 * double(size) ); + std::cout << "Init: tau local " << TauLcl << " et global " << TauGlb << std::endl; + } + + + /** Initialization of full ES + + @overload + */ + void init(eoEsFull, eoEsMutationInit& _init) + { + init(eoEsStdev(), _init); + TauBeta = _init.TauBeta(); + std::cout << "Init: tau local " << TauLcl << " et global " << TauGlb << std::endl; + } + + + /** Local factor for mutation of std deviations */ + double TauLcl; + + /** Global factor for mutation of std deviations */ + double TauGlb; + + /** Factor for mutation of correlation parameters */ + double TauBeta; + + /** Bounds of parameters */ + eoRealVectorBounds& bounds; + + /** Minimum stdev. + + If you let the step-size go to 0, self-adaptation stops, therefore we give a + lower bound. The actual value used is somewhat arbitrary and the is no + theoretical reasoning known for it (Sep 2005). + + The code that we have in EO is a port from a C code that Thomas Bck kindly + donated to the community some years ago. It has been modified by Marc + Schoenauer for inclusion in EvolC, than by Maarten Keijzer into EO. The + exact value was adjusted based on practice. + + Removing this doesn't work well, but it was never tried to figure out what + the best value would be. + */ + static const double stdev_eps; +}; + + +// Minimum value of stdevs, see declaration for details. +template +const double eoEsMutate::stdev_eps = 1.0e-40; + +#endif diff --git a/deprecated/eo/src/es/eoEsMutationInit.h b/deprecated/eo/src/es/eoEsMutationInit.h new file mode 100644 index 000000000..987de86bd --- /dev/null +++ b/deprecated/eo/src/es/eoEsMutationInit.h @@ -0,0 +1,122 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; fill-column: 80 -*- + +//----------------------------------------------------------------------------- +// eoEsMutationInit.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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoEsMutationInit_h +#define _eoEsMutationInit_h + +#include + +/** Initialize Mutation operator + +@ingroup Real +@ingroup Variators + +Proxy class that is used for initializing the mutation operator. It provides an +interface between eoEsMutate and the abstract parameterLoader. It also provides +the names for the parameters in this class as virtual protected member +functions. + +If you have more than a single ES in a project that need different names in the +configuration files, you might consider overriding this class to change the +names. + +@see eoEsMutate +*/ +class eoEsMutationInit +{ +public : + + /** Constructor + + @param _parser Parser to read parameters from. + @param _section Parser section for \f$\tau\f$-parameters. + */ + eoEsMutationInit(eoParser& _parser, + std::string _section="ES mutation parameters" ) : + parser(_parser), repSection(_section), + TauLclParam(0), TauGlbParam(0), TauBetaParam(0) {} + + /** Virtual destructor */ + virtual ~eoEsMutationInit() {} + + /** local tau */ + double TauLcl(void) + { + if (TauLclParam == 0) + { + TauLclParam = &parser.getORcreateParam(1.0, TauLclName(), + "Local Tau (before normalization)", + TauLclShort(), section()); + } + return TauLclParam->value(); + } + + /** global tau */ + double TauGlb(void) + { + if (TauGlbParam == 0) + { + TauGlbParam = &parser.getORcreateParam(1.0, TauGlbName(), + "Global Tau (before normalization)", + TauGlbShort(), section()); + } + return TauGlbParam->value(); + } + + /** correlation's tau */ + double TauBeta(void) + { + if (TauBetaParam == 0) + { + TauBetaParam = &parser.getORcreateParam(0.0873, TauBetaName(), + "Beta", TauBetaShort(), section()); + } + return TauBetaParam->value(); + } + + protected : + + virtual std::string section(void) { return repSection; } + + virtual std::string TauLclName(void) const { return "TauLoc"; } + virtual char TauLclShort(void) const { return 'l'; } + + virtual std::string TauGlbName(void) const { return "TauGlob"; } + virtual char TauGlbShort(void) const { return 'g'; } + + virtual std::string TauBetaName(void) const { return "Beta"; } + virtual char TauBetaShort(void) const { return 'b'; } + +private: + + eoParser& parser; + std::string repSection; + eoValueParam* TauLclParam; + eoValueParam* TauGlbParam; + eoValueParam* TauBetaParam; +}; + +#endif diff --git a/deprecated/eo/src/es/eoEsSimple.h b/deprecated/eo/src/es/eoEsSimple.h new file mode 100644 index 000000000..ac93ab4b6 --- /dev/null +++ b/deprecated/eo/src/es/eoEsSimple.h @@ -0,0 +1,77 @@ +/* (c) GeNeura Team, 2000 - EEAAX 1999, Maarten Keijzer 2000 + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ + + +#ifndef _eoEsSimple_h +#define _eoEsSimple_h + +#include +#include + +#include + +/** Simple Evolution Strategy + +@ingroup Real + +One of the more simple evolution strategies, sporting just a single stdeviation +for the entire chromosome. For more advanced versions see also eoEsStdev +eoEsFull + +@see eoEsStdev eoEsFull +*/ +template +class eoEsSimple : public eoVector +{ +public : + + typedef double Type; + + eoEsSimple() : eoVector() {} + + virtual std::string className() const { return "eoEsSimple"; } + + void printOn(std::ostream& os) const + { + eoVector::printOn(os); + os << ' ' << stdev << ' '; + } + + void readFrom(std::istream& is) + { + eoVector::readFrom(is); + is >> stdev; + } + + double stdev; +}; + +#endif + + + +// Local Variables: +// coding: iso-8859-1 +// mode:C++ +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/es/eoEsStandardXover.h b/deprecated/eo/src/es/eoEsStandardXover.h new file mode 100644 index 000000000..34739693c --- /dev/null +++ b/deprecated/eo/src/es/eoEsStandardXover.h @@ -0,0 +1,123 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoEsLocalXover.h : ES global crossover +// (c) Marc Schoenauer 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + + +#ifndef _eoEsLocalXover_H +#define _eoEsLocalXover_H + +#include + +#include +#include +#include + +#include +// needs a selector - here random +#include + +/** Standard (i.e. eoBinOp) crossover operator for ES genotypes. + * Uses some Atom crossovers to handle both the object variables + * and the mutation strategy parameters + * It is an eoBinOp and has to be wrapped into an eoGenOp before being used + * like the global version + * + * @ingroup Real + * @ingroup Variators + */ +template +class eoEsStandardXover: public eoBinOp +{ +public: + typedef typename EOT::Fitness FitT; + + /** + * (Default) Constructor. + */ + eoEsStandardXover(eoBinOp & _crossObj, eoBinOp & _crossMut) : + crossObj(_crossObj), crossMut(_crossMut) {} + + /// The class name. Used to display statistics + virtual std::string className() const { return "eoEsStandardXover"; } + + /** + * modifies one parents in the populator + * using a second parent + */ + bool operator()(EOT& _eo1, const EOT& _eo2) + { + bool bLoc=false; + // first, the object variables + for (unsigned i=0; i<_eo1.size(); i++) + { + 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 + + bool cross_self_adapt(eoEsSimple & _parent1, const eoEsSimple & _parent2) + { + return crossMut(_parent1.stdev, _parent2.stdev); // apply eoBinOp + } + + bool cross_self_adapt(eoEsStdev & _parent1, const eoEsStdev & _parent2) + { + bool bLoc=false; + for (unsigned i=0; i<_parent1.size(); i++) + { + bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp + } + return bLoc; + } + + bool cross_self_adapt(eoEsFull & _parent1, const eoEsFull & _parent2) + { + bool bLoc=false; + unsigned i; + // the StDev + for (i=0; i<_parent1.size(); i++) + { + 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 + } + return bLoc; + + } + + // the data + eoRandomSelect sel; + eoBinOp & crossObj; + eoBinOp & crossMut; +}; + +#endif diff --git a/deprecated/eo/src/es/eoEsStdev.h b/deprecated/eo/src/es/eoEsStdev.h new file mode 100644 index 000000000..b8910512c --- /dev/null +++ b/deprecated/eo/src/es/eoEsStdev.h @@ -0,0 +1,80 @@ +/* (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ + + +#ifndef _eoEsStdev_h +#define _eoEsStdev_h + +#include + + +/** Evolutionary Strategy with a standard deviation per parameter + +Evolutionary strategie style representation, supporting co-evolving +standard deviations. + +@ingroup Real +*/ +template +class eoEsStdev : public eoVector +{ +public: + + using eoVector::size; + + typedef double Type; + + eoEsStdev(void) : eoVector() {} + + virtual std::string className(void) const { return "eoEsStdev"; } + + void printOn(std::ostream& os) const + { + eoVector::printOn(os); + os << ' '; + std::copy(stdevs.begin(), stdevs.end(), std::ostream_iterator(os, " ")); + os << ' '; + } + + void readFrom(std::istream& is) + { + eoVector::readFrom(is); + stdevs.resize(size()); + unsigned i; + for (i = 0; i < size(); ++i) + is >> stdevs[i]; + } + + + std::vector stdevs; +}; + +#endif + + + +// Local Variables: +// coding: iso-8859-1 +// mode:C++ +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/es/eoNormalMutation.h b/deprecated/eo/src/es/eoNormalMutation.h new file mode 100644 index 000000000..96dcf54c2 --- /dev/null +++ b/deprecated/eo/src/es/eoNormalMutation.h @@ -0,0 +1,281 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoNormalMutation.h +// (c) EEAAX 2001 - Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoNormalMutation_h +#define eoNormalMutation_h + +//----------------------------------------------------------------------------- + +#include // swap_ranges +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** Simple normal mutation of a std::vector of real values. + * The stDev is fixed - but it is passed ans stored as a reference, + * to enable dynamic mutations (see eoOenFithMutation below). + * + * As for the bounds, the values are here folded back into the bounds. + * The other possiblity would be to iterate until we fall inside the bounds - + * but this sometimes takes a long time!!! + * + * @ingroup Real + * @ingroup Variators + */ +template class eoNormalVecMutation: public eoMonOp +{ + public: + /** + * (Default) Constructor. + * The bounds are initialized with the global object that says: no bounds. + * + * @param _sigma the range for uniform nutation + * @param _p_change the probability to change a given coordinate + */ + eoNormalVecMutation(double _sigma, const double& _p_change = 1.0): + sigma(_sigma), bounds(eoDummyVectorNoBounds), p_change(_p_change) {} + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _sigma the range for uniform nutation + * @param _p_change the probability to change a given coordinate + * + * 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): + sigma(_bounds.size(), _sigma), bounds(_bounds), p_change(_p_change) + { + // scale to the range - if any + for (unsigned i=0; i sigma; + eoRealVectorBounds & bounds; + double p_change; +}; + +/** Simple normal mutation of a std::vector of real values. + * The stDev is fixed - but it is passed ans stored as a reference, + * to enable dynamic mutations (see eoOenFithMutation below). + * + * As for the bounds, the values are here folded back into the bounds. + * The other possiblity would be to iterate until we fall inside the bounds - + * but this sometimes takes a long time!!! + * + * @ingroup Real + * @ingroup Variators + */ +template class eoNormalMutation + : public eoMonOp +{ +public: + /** + * (Default) Constructor. + * The bounds are initialized with the global object that says: no bounds. + * + * @param _sigma the range for uniform nutation + * @param _p_change the probability to change a given coordinate + */ + eoNormalMutation(double & _sigma, const double& _p_change = 1.0): + sigma(_sigma), bounds(eoDummyVectorNoBounds), p_change(_p_change) {} + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _sigma the range for uniform nutation + * @param _p_change the probability to change a given coordinate + */ + eoNormalMutation(eoRealVectorBounds & _bounds, + double _sigma, const double& _p_change = 1.0): + sigma(_sigma), bounds(_bounds), p_change(_p_change) {} + + /** The class name */ + virtual std::string className() const { return "eoNormalMutation"; } + + /** + * Do it! + * @param _eo The cromosome undergoing the mutation + */ + bool operator()(EOT& _eo) + { + 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; + } + } + return hasChanged; + } + + /** Accessor to ref to sigma - for update and monitor */ + double & Sigma() {return sigma;} + +private: + double & sigma; + eoRealVectorBounds & bounds; + double p_change; +}; + +/** the dynamic version: just say it is updatable - + * and write the update() method! + * here the 1 fifth rule: count the proportion of successful mutations, and + * increase sigma if more than threshold (1/5 !) + * + * @ingroup Real + * @ingroup Variators + */ +template class eoOneFifthMutation : + public eoNormalMutation, public eoUpdatable +{ +public: + + using eoNormalMutation< EOT >::Sigma; + + typedef typename EOT::Fitness Fitness; + + /** + * (Default) Constructor. + * + * @param _eval the evaluation function, needed to recompute the fitmess + * @param _sigmaInit the initial value for uniform mutation + * @param _windowSize the size of the window for statistics + * @param _updateFactor multiplicative update factor for sigma + * @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): + eoNormalMutation(_sigmaInit), eval(_eval), + threshold(_threshold), updateFactor(_updateFactor), + nbMut(_windowSize, 0), nbSuccess(_windowSize, 0), genIndex(0) + { + // minimal check + if (updateFactor>=1) + throw std::runtime_error("Update factor must be < 1 in eoOneFifthMutation"); + } + + /** The class name */ + virtual std::string className() const { return "eoOneFifthMutation"; } + + /** + * Do it! + * calls the standard mutation, then checks for success and updates stats + * + * @param _eo The chromosome undergoing the mutation + */ + bool operator()(EOT & _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 + + 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 + * if the object is added to the checkpoint + */ + void update() + { + unsigned totalMut = 0; + unsigned totalSuccess = 0; + // compute the average stats over the time window + for ( unsigned i=0; i threshold) { + Sigma() /= updateFactor; // increase sigma + } + else + { + Sigma() *= updateFactor; // decrease sigma + } + genIndex = (genIndex+1) % nbMut.size() ; + nbMut[genIndex] = nbSuccess[genIndex] = 0; + + } + +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) +}; + + +//----------------------------------------------------------------------------- +//@} +#endif diff --git a/deprecated/eo/src/es/eoReal.h b/deprecated/eo/src/es/eoReal.h new file mode 100644 index 000000000..ff1908a0c --- /dev/null +++ b/deprecated/eo/src/es/eoReal.h @@ -0,0 +1,63 @@ +/* + eoReal.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: Marc.Schoenauer@polytechnique.fr + todos@geneura.ugr.es, http://geneura.ugr.es + mkeijzer@dhi.dk +*/ + +#ifndef eoReal_h +#define eoReal_h + +//----------------------------------------------------------------------------- + +#include // std::ostream, std::istream +#include // std::string + +#include + +/** eoReal: implementation of simple real-valued chromosome. + * based on eoVector class + * + * @ingroup Real +*/ +template class eoReal: public eoVector +{ + public: + + /** + * (Default) Constructor. + * @param size Size of the std::vector + * @param value fill the vector with this value + */ + eoReal(unsigned size = 0, double value = 0.0): + eoVector(size, value) {} + + /// My class name. + virtual std::string className() const + { + return "eoReal"; + } + +}; +/** @example t-eoReal.cpp + */ + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/es/eoRealAtomXover.h b/deprecated/eo/src/es/eoRealAtomXover.h new file mode 100644 index 000000000..4d4244dd2 --- /dev/null +++ b/deprecated/eo/src/es/eoRealAtomXover.h @@ -0,0 +1,100 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRealAtomXover.h : helper classes for std::vector crossover +// (c) Marc Schoenauer 2001 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + +/** Some basic atomic crossovers for doubles + * + * Are used in all ES specifici crossovers + * and will be in more general stuff, using the generic crossovers + */ + +#ifndef _eoRealAtomXover_H +#define _eoRealAtomXover_H + +#include + +#include + +/** + Discrete crossover == exchange of values + * + * @ingroup Real + * @ingroup Variators +*/ +class eoDoubleExchange: public eoBinOp +{ +public: + /** + * (Default) Constructor. + */ + eoDoubleExchange() {} + + /// The class name. Used to display statistics + virtual std::string className() const { return "eoDoubleExchange"; } + + /** + Exchanges or not the values + */ + 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; + } + return false; + } + +}; + +/** + Intermediate crossover == linear combination + * + * @ingroup Real + * @ingroup Variators +*/ +class eoDoubleIntermediate: public eoBinOp +{ +public: + /** + * (Default) Constructor. + */ + eoDoubleIntermediate() {} + + /// The class name. Used to display statistics + virtual std::string className() const { return "eoDoubleIntermediate"; } + + /** + Linear combination of both parents + */ + bool operator()(double& r1, const double& r2) + { + double alpha = eo::rng.uniform(); + r1 = alpha * r2 + (1-alpha) * r1; + return true; + } + +}; + +#endif diff --git a/deprecated/eo/src/es/eoRealInitBounded.h b/deprecated/eo/src/es/eoRealInitBounded.h new file mode 100644 index 000000000..6488dd056 --- /dev/null +++ b/deprecated/eo/src/es/eoRealInitBounded.h @@ -0,0 +1,70 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoRealInitBounded_h +#define eoRealInitBounded_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +/** Simple initialization for any EOT that derives from std::vector + * uniformly in some bounds + * + * @ingroup Real + * @ingroup Variators + */ +template +class eoRealInitBounded : public eoInit +{ + public: + /** Ctor - from eoRealVectorBounds */ + eoRealInitBounded(eoRealVectorBounds & _bounds):bounds(_bounds) + { + if (!bounds.isBounded()) + throw std::runtime_error("Needs bounded bounds to initialize a std::vector"); + } + + /** simply passes the argument to the uniform method of the bounds */ + virtual void operator()(EOT & _eo) + { + bounds.uniform(_eo); // resizes, and fills uniformly in bounds + _eo.invalidate(); // was MISSING!!!! + } + + /** accessor to the bounds */ + virtual eoRealVectorBounds & theBounds() {return bounds;} + virtual unsigned size(){return bounds.size();} + + private: + eoRealVectorBounds & bounds; +}; + +//----------------------------------------------------------------------------- +//@} +#endif diff --git a/deprecated/eo/src/es/eoRealOp.h b/deprecated/eo/src/es/eoRealOp.h new file mode 100644 index 000000000..c8c6471a5 --- /dev/null +++ b/deprecated/eo/src/es/eoRealOp.h @@ -0,0 +1,513 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRealOp.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 + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoRealOp_h +#define eoRealOp_h + +//----------------------------------------------------------------------------- + +#include // swap_ranges +#include +#include +#include + +//----------------------------------------------------------------------------- + +/** eoUniformMutation --> changes all values of the std::vector + by uniform choice with range epsilon + with probability p_change per variable +\class eoUniformMutation eoRealOp.h Tutorial/eoRealOp.h + * + * @ingroup Real + * @ingroup Variators +*/ + +template class eoUniformMutation: public eoMonOp +{ + public: + /** + * Constructor without bounds == unbounded variables :-) + * not very clean, but who's doing unbounded optimization anyway? + * and it's there mostly for backward compatibility + * + * @param _epsilon the range for uniform nutation + * @param _p_change the probability to change a given coordinate + */ + eoUniformMutation(const double& _epsilon, const double& _p_change = 1.0): + homogeneous(true), bounds(eoDummyVectorNoBounds), epsilon(1, _epsilon), + p_change(1, _p_change) {} + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _epsilon the range for uniform mutation - a double to be scaled + * @param _p_change the one probability to change all coordinates + */ + eoUniformMutation(eoRealVectorBounds & _bounds, + 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& _epsilon, + const std::vector& _p_change): + homogeneous(false), bounds(_bounds), epsilon(_epsilon), + p_change(_p_change) {} + + /// The class name. + virtual std::string className() const { return "eoUniformMutation"; } + + /** + * Do it! + * @param _eo The indi undergoing the mutation + */ + 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; + } + } + else + { + // 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; + } + } + 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 +}; + +/** eoDetUniformMutation --> changes exactly k values of the std::vector + by uniform choice with range epsilon +\class eoDetUniformMutation eoRealOp.h Tutorial/eoRealOp.h + * + * @ingroup Real + * @ingroup Variators +*/ + +template class eoDetUniformMutation: public eoMonOp +{ + public: + /** + * (Default) Constructor for homogeneous genotype + * it's there mostly for backward compatibility + * + * @param _epsilon the range for uniform nutation + * @param _no number of coordinate to modify + */ + eoDetUniformMutation(const double& _epsilon, const unsigned& _no = 1): + homogeneous(true), bounds(eoDummyVectorNoBounds), + epsilon(1, _epsilon), no(_no) {} + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _epsilon the range for uniform nutation (to be scaled if necessary) + * @param _no number of coordinate to modify + */ + eoDetUniformMutation(eoRealVectorBounds & _bounds, + 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& _epsilon, + const unsigned& _no = 1): + homogeneous(false), bounds(_bounds), epsilon(_epsilon), no(_no) + { + // scale to the range - if any + for (unsigned i=0; i epsilon; // the ranges of mutation + unsigned no; +}; + + +// two arithmetical crossovers + +/** eoSegmentCrossover --> uniform choice in segment + == arithmetical with same value along all coordinates +\class eoSegmentCrossover eoRealOp.h Tutorial/eoRealOp.h + * + * @ingroup Real + * @ingroup Variators +*/ + +template class eoSegmentCrossover: public eoQuadOp +{ + public: + /** + * (Default) Constructor. + * The bounds are initialized with the global object that says: no bounds. + * + * @param _alpha the amount of exploration OUTSIDE the parents + * as in BLX-alpha notation (Eshelman and Schaffer) + * 0 == contractive application + * Must be positive + */ + eoSegmentCrossover(const double& _alpha = 0.0) : + bounds(eoDummyVectorNoBounds), alpha(_alpha), range(1+2*_alpha) {} + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _alpha the amount of exploration OUTSIDE the parents + * as in BLX-alpha notation (Eshelman and Schaffer) + * 0 == contractive application + * Must be positive + */ + eoSegmentCrossover(eoRealVectorBounds & _bounds, + const double& _alpha = 0.0) : + bounds(_bounds), alpha(_alpha), range(1+2*_alpha) {} + + /// The class name. + virtual std::string className() const { return "eoSegmentCrossover"; } + + /** + * segment crossover - modifies both parents + * @param _eo1 The first parent + * @param _eo2 The first parent + */ + bool operator()(EOT& _eo1, EOT& _eo2) + { + unsigned i; + 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(); + } + + 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 :-))) + } + +protected: + eoRealVectorBounds & bounds; + double alpha; + double range; // == 1+2*alpha +}; + +/** eoHypercubeCrossover --> uniform choice in hypercube + == arithmetical with different values for each coordinate +\class eoArithmeticCrossover eoRealOp.h Tutorial/eoRealOp.h + * + * @ingroup Real + * @ingroup Variators +*/ +template class eoHypercubeCrossover: public eoQuadOp +{ + public: + /** + * (Default) Constructor. + * The bounds are initialized with the global object that says: no bounds. + * + * @param _alpha the amount of exploration OUTSIDE the parents + * as in BLX-alpha notation (Eshelman and Schaffer) + * 0 == contractive application + * Must be positive + */ + eoHypercubeCrossover(const double& _alpha = 0.0): + bounds(eoDummyVectorNoBounds), alpha(_alpha), range(1+2*_alpha) + { + if (_alpha < 0) + throw std::runtime_error("BLX coefficient should be positive"); + } + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _alpha the amount of exploration OUTSIDE the parents + * as in BLX-alpha notation (Eshelman and Schaffer) + * 0 == contractive application + * Must be positive + */ + eoHypercubeCrossover(eoRealVectorBounds & _bounds, + const double& _alpha = 0.0): + bounds(_bounds), alpha(_alpha), range(1+2*_alpha) + { + if (_alpha < 0) + throw std::runtime_error("BLX coefficient should be positive"); + } + + /// The class name. + virtual std::string className() const { return "eoHypercubeCrossover"; } + + /** + * hypercube crossover - modifies both parents + * @param _eo1 The first parent + * @param _eo2 The first parent + */ + bool operator()(EOT& _eo1, EOT& _eo2) + { + 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); + + // 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 + } + } + + return hasChanged; + } + +protected: + eoRealVectorBounds & bounds; + double alpha; + double range; // == 1+2*alphaMin +}; + + +/** eoRealUxOver --> Uniform crossover, also termed intermediate crossover +\class eoRealUxOver eoRealOp.h Tutorial/eoRealOp.h + * + * @ingroup Real + * @ingroup Variators +*/ + +template class eoRealUXover: public eoQuadOp +{ + public: + /** + * (Default) Constructor. + * @param _preference bias in the choice (usually, no bias == 0.5) + */ + eoRealUXover(const float& _preference = 0.5): preference(_preference) + { + if ( (_preference <= 0.0) || (_preference >= 1.0) ) + std::runtime_error("UxOver --> invalid preference"); + } + + /// The class name. + virtual std::string className() const { return "eoRealUXover"; } + + /** + * Uniform crossover for real std::vectors + * @param _eo1 The first parent + * @param _eo2 The second parent + * @exception std::runtime_error if sizes don't match + */ + bool operator()(EOT& _eo1, EOT& _eo2) + { + if ( _eo1.size() != _eo2.size()) + 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; + } + } + return changed; + } + private: + float preference; +}; + + +//----------------------------------------------------------------------------- +//@} +#endif diff --git a/deprecated/eo/src/es/eoSBXcross.h b/deprecated/eo/src/es/eoSBXcross.h new file mode 100644 index 000000000..40f8ac360 --- /dev/null +++ b/deprecated/eo/src/es/eoSBXcross.h @@ -0,0 +1,135 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#include // swap_ranges +#include +#include +#include +#include +#include + + + +/** +* @ingroup Real +* @ingroup Variators +*/ +template class eoSBXCrossover: public eoQuadOp +{ + public: + /**** + * (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) {} + + + ////////////////////////////////////////////// + + /** + * Constructor with bounds + * @param _bounds an eoRealVectorBounds that contains the bounds + * @param _eta the amount of exploration OUTSIDE the parents + * as in BLX-alpha notation (Eshelman and Schaffer) + * 0 == contractive application + * Must be positive + */ + + + + eoSBXCrossover(eoRealVectorBounds & _bounds, + const double& _eta = 1.0) : + bounds(_bounds), eta(_eta), range(1) {} + + /////////////////////////////////////////////// + + ////////////////////////////////////////////// + + /** + * Constructor from a parser. Will read from the argument parser + * eoRealVectorBounds that contains the bounds + * eta, the SBX parameter + */ + + 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"; } + + /***************************************** + * SBX crossover - modifies both parents * + * @param _eo1 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++) + { + double u = rng.uniform(range) ; + + 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]); + + + + } + return true; + } + + + +protected: + eoRealVectorBounds & bounds; + double eta; + double range; // == 1 +}; diff --git a/deprecated/eo/src/es/make_algo_scalar_es.cpp b/deprecated/eo/src/es/make_algo_scalar_es.cpp new file mode 100644 index 000000000..47585a78c --- /dev/null +++ b/deprecated/eo/src/es/make_algo_scalar_es.cpp @@ -0,0 +1,84 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of select/replace fns + * of the library for evolution of ***eoEs genotypes*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/es.h + * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir + */ + +// 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 + +/// The following function merely call the templatized do_* functions above + +// Algo +/////// +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +////////////// +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +/////////////// +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} diff --git a/deprecated/eo/src/es/make_algo_scalar_real.cpp b/deprecated/eo/src/es/make_algo_scalar_real.cpp new file mode 100644 index 000000000..1a1796bed --- /dev/null +++ b/deprecated/eo/src/es/make_algo_scalar_real.cpp @@ -0,0 +1,60 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of select/replace fns + * of the library for evolution of ***eoReal*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/real.h + * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions above + +// Algo +/////// +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); +} diff --git a/deprecated/eo/src/es/make_checkpoint_es.cpp b/deprecated/eo/src/es/make_checkpoint_es.cpp new file mode 100644 index 000000000..12bc78605 --- /dev/null +++ b/deprecated/eo/src/es/make_checkpoint_es.cpp @@ -0,0 +1,81 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of checkpoint fns + * of the library for evolution of ***ES genotypes*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/es.h + * while the TEMPLATIZED code is define in make_checkpoint.h in the src/do dir + */ + +// 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 + +/// The following function merely call the templatized do_* functions + +// checkpoint +///////////// +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) +{ + return do_make_checkpoint(_parser, _state, _eval, _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) +{ + return do_make_checkpoint(_parser, _state, _eval, _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) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} diff --git a/deprecated/eo/src/es/make_checkpoint_real.cpp b/deprecated/eo/src/es/make_checkpoint_real.cpp new file mode 100644 index 000000000..a1cf6d4f3 --- /dev/null +++ b/deprecated/eo/src/es/make_checkpoint_real.cpp @@ -0,0 +1,59 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of checkpoint fns + * of the library for evolution of ***eoReal*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/real.h + * while the TEMPLATIZED code is define in make_checkpoint.h in the src/do dir + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions + +// checkpoint +///////////// +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) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} diff --git a/deprecated/eo/src/es/make_continue_es.cpp b/deprecated/eo/src/es/make_continue_es.cpp new file mode 100644 index 000000000..e50167959 --- /dev/null +++ b/deprecated/eo/src/es/make_continue_es.cpp @@ -0,0 +1,81 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of continuator fns + * of the library for evolution of ***ES genotypes*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/es.h + * while the TEMPLATIZED code is define in make_continue.h in the src/do dir + */ + +// 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 + +/// The following function merely call the templatized do_* functions + +// continue +/////////// +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +/////////// +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +/////////// +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} diff --git a/deprecated/eo/src/es/make_continue_real.cpp b/deprecated/eo/src/es/make_continue_real.cpp new file mode 100644 index 000000000..060852172 --- /dev/null +++ b/deprecated/eo/src/es/make_continue_real.cpp @@ -0,0 +1,59 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of continuator fns + * of the library for evolution of ***REAL vectors*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/real.h + * while the TEMPLATIZED code is define in make_continue.h in the src/do dir + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions + +// continue +/////////// +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} diff --git a/deprecated/eo/src/es/make_es.h b/deprecated/eo/src/es/make_es.h new file mode 100644 index 000000000..46a4e23f6 --- /dev/null +++ b/deprecated/eo/src/es/make_es.h @@ -0,0 +1,152 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +/** 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, + * while the TEMPLATIZED code is define in the different make_XXX.h files + * 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 + * i.e. ***without*** mutation parameters attached to individuals + * + * Unlike most EO .h files, it does not (and should not) contain any code, + * just declarations + */ + +#ifndef es_h +#define es_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 +#include + +/** @addtogroup Builders + * @{ + */ + +//Representation dependent - rewrite everything anew for each representation +////////////////////////// +// the genotypes +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsSimple _eo); +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsSimple _eo); + +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsStdev _eo); +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsStdev _eo); + +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsFull _eo); +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsFull _eo); + + + +// the operators +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); + +//Representation INdependent +//////////////////////////// +// you don't need to modify that part even if you use your own representation + +// init pop +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); + +// the continue's +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); + +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); + +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); + +// the checkpoint +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); + +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); + +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); + + +// the algo +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +// run +void run_ea(eoAlgo >& _ga, eoPop >& _pop); +void run_ea(eoAlgo >& _ga, eoPop >& _pop); + +void run_ea(eoAlgo >& _ga, eoPop >& _pop); +void run_ea(eoAlgo >& _ga, eoPop >& _pop); + +void run_ea(eoAlgo >& _ga, eoPop >& _pop); +void run_ea(eoAlgo >& _ga, eoPop >& _pop); + +// end of parameter input (+ .status + help) +// that one is not templatized, but is here for completeness +void make_help(eoParser & _parser); + +/** @} */ +/** @} */ +#endif diff --git a/deprecated/eo/src/es/make_genotype_es.cpp b/deprecated/eo/src/es/make_genotype_es.cpp new file mode 100644 index 000000000..41f764cdf --- /dev/null +++ b/deprecated/eo/src/es/make_genotype_es.cpp @@ -0,0 +1,121 @@ +/* (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk +*/ + + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + + +/** Init functions + +This file contains ***INSTANCIATED DEFINITIONS*** of eoReal Init fns +It should be included in the file that calls any of the corresponding +fns 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 +src/es/make_real.h while the TEMPLATIZED code is define in +make_genotype_real.h + +It is instanciated in src/es/make_genotype_real.cpp - and incorporated +in the ga/libga.a + +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 that is +***not properly initialized*** +*/ + +// the templatized code (same for real and es here) +#include + + +/// The following function merely call the templatized do_* functions +eoRealInitBounded >& make_genotype(eoParser& _parser, + eoState& _state, + eoEsSimple _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + +eoRealInitBounded >& make_genotype(eoParser& _parser, + eoState& _state, + eoEsSimple _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + +eoRealInitBounded >& make_genotype(eoParser& _parser, + eoState& _state, + eoEsStdev _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + +eoRealInitBounded >& make_genotype(eoParser& _parser, + eoState& _state, + eoEsStdev _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + +eoRealInitBounded > & make_genotype(eoParser& _parser, + eoState& _state, + eoEsFull _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + +eoRealInitBounded >& make_genotype(eoParser& _parser, + eoState& _state, + eoEsFull _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + + +// Local Variables: +// coding: iso-8859-1 +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/es/make_genotype_real.cpp b/deprecated/eo/src/es/make_genotype_real.cpp new file mode 100644 index 000000000..d5ad238d4 --- /dev/null +++ b/deprecated/eo/src/es/make_genotype_real.cpp @@ -0,0 +1,73 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_genotype_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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of eoReal Init fns + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/make_real.h + * while the TEMPLATIZED code is define in make_genotype_real.h + * + * It is instanciated in src/es/make_genotype_real.cpp - + * and incorporated in the ga/libga.a + * + * 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 + * that is ***not properly initialized*** +*/ + +// the templatized code +#include + +/// The following functions merely call the templatized do_* functions +eoRealInitBounded > & make_genotype(eoParser& _parser, + eoState& _state, + eoReal _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + + + +eoRealInitBounded > & make_genotype(eoParser& _parser, + eoState& _state, + eoReal _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} diff --git a/deprecated/eo/src/es/make_genotype_real.h b/deprecated/eo/src/es/make_genotype_real.h new file mode 100644 index 000000000..6ab62967f --- /dev/null +++ b/deprecated/eo/src/es/make_genotype_real.h @@ -0,0 +1,128 @@ +//----------------------------------------------------------------------------- +/** (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk +*/ + + +#ifndef EO_make_genotype_h +#define EO_make_genotype_h + +#include +#include +#include + +#include "es/eoReal.h" +#include "es/eoEsChromInit.h" +#include "utils/eoParser.h" +#include "utils/eoRealVectorBounds.h" +#include "utils/eoState.h" + + +/** @addtogroup Builders + * @{ + */ + +/** Initialize genotype + +This fuction does the initialization of what's needed for a particular genotype +(here, std::vector == eoReal). 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 allows to choose the type of genotype at run +time (see in es dir) + +It is instanciated in src/es/make_genotyupe_real.cpp and incorporated in the +src/es/libes.a + +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 that is ***not properly +initialized*** +*/ +template +eoEsChromInit & do_make_genotype(eoParser& _parser, eoState& _state, EOT) +{ + // the fitness type + typedef typename EOT::Fitness FitT; + eoEsChromInit *init; + + // for eoReal, only thing needed is the size - but might have been created elswhere ... + eoValueParam& vecSize + = _parser.getORcreateParam(unsigned(10), "vecSize", + "The number of variables ", + 'n', "Genotype Initialization"); + // to build an eoReal Initializer, we need bounds: [-1,1] by default + eoValueParam& boundsParam + = _parser.getORcreateParam(eoRealVectorBounds(vecSize.value(), -1, 1), + "initBounds", + "Bounds for initialization (MUST be bounded)", + 'B', "Genotype Initialization"); + // now some initial value for sigmas - even if useless? + // should be used in Normal mutation + 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"); + // check for % + bool to_scale = false; + size_t pos = sigmaParam.value().find('%'); + if(pos < sigmaParam.value().size()) { + // found a % - use scaling and get rid of '%' + to_scale = true; + sigmaParam.value().resize(pos); + } + std::istringstream is(sigmaParam.value()); + double sigma; + is >> sigma; + // minimum check + if(sigma < 0) + throw std::runtime_error("Negative sigma in make_genotype"); + if(to_scale) + init = new eoEsChromInit(boundsParam.value(), sigma, to_scale); + else { + // define parameter + eoValueParam >& vecSigmaParam + = _parser.getORcreateParam(std::vector(vecSize.value(), sigma), "vecSigmaInit", + "Initial value for Sigmas (only used when initSigma is not scaled)", + 'S', "Genotype Initialization"); + init = new eoEsChromInit(boundsParam.value(), vecSigmaParam.value()); + } + // store in state + _state.storeFunctor(init); + return *init; +} + +/** @} */ +#endif // EO_make_genotype_h + + + +// Local Variables: +// coding: iso-8859-1 +// mode:C++ +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/es/make_op.h b/deprecated/eo/src/es/make_op.h new file mode 100644 index 000000000..1c7fe50e7 --- /dev/null +++ b/deprecated/eo/src/es/make_op.h @@ -0,0 +1,299 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_op.h - the real-valued version +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_op_h +#define _make_op_h + +// the operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include + +// the specialized Real stuff +#include +#include +#include +#include + // also need the parser and param includes +#include +#include + + +/** @addtogroup Builders + * @{ + */ + +/* + * This function builds the operators that will be applied to the eoReal + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * 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 + * about the gneotypes, the init has it all (e.g. bounds, ...) + * Simply do + * EOT myEO; + * _init(myEO); + * and myEO is then an ACTUAL object +*/ +template +eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit& _init) +{ + // First, decide whether the objective variables are bounded + eoValueParam& boundsParam + = _parser.getORcreateParam(eoParamParamType("(0,1)"), "objectBounds", + "Bounds for variables (unbounded if absent)", + 'B', "Genetic Operators"); + + // get initisalizer size == std::vector size + // eoRealInitBounded * realInit = (eoRealInitBounded*)(&_init); + // unsigned vecSize = realInit->theBounds().size(); + + // get std::vector size: safer??? + EOT eoTmp; + _init(eoTmp); + unsigned vecSize = eoTmp.size(); + + // the bounds pointer + eoRealVectorBounds * ptBounds; + if (_parser.isItThere(boundsParam)) // otherwise, no bounds + { + /////Warning: this code should probably be replaced by creating + ///// some eoValueParam with specific implementation + //// in eoParser.cpp. At the moemnt, it is there (cf also make_genotype + eoParamParamType & ppBounds = boundsParam.value(); // std::pair > + // transform into a std::vector + std::vector v; + std::vector::iterator it; + for (it=ppBounds.second.begin(); itc_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"); + // we need to give ownership of this pointer to somebody + /////////// end of temporary code + } + else // no param for bounds was given + ptBounds = new eoRealVectorNoBounds(vecSize); // DON'T USE eoDummyVectorNoBounds + // as it does not have any dimension + + // this is a temporary version(!), + // while Maarten codes the full tree-structured general operator input + // BTW we must leave that simple version available somehow, as it is the one + // that 90% people use! + eoValueParam& operatorParam + = _parser.getORcreateParam(std::string("SGA"), "operator", + "Description of the operator (SGA only now)", + 'o', "Genetic Operators"); + + if (operatorParam.value() != std::string("SGA")) + throw std::runtime_error("Sorry, only SGA-like operator available right now\n"); + + // 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 + // crossover with pcross + mutation with pmut + + eoValueParam& pCrossParam + = _parser.getORcreateParam(0.6, "pCross", "Probability of Crossover", + 'C', "Genetic Operators" ); + // minimum check + if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) ) + throw std::runtime_error("Invalid pCross"); + + eoValueParam& pMutParam + = _parser.getORcreateParam(0.1, "pMut", "Probability of Mutation", + 'M', "Genetic Operators" ); + // minimum check + if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) ) + throw std::runtime_error("Invalid pMut"); + + // the crossovers + ///////////////// + // the parameters + eoValueParam& segmentRateParam + = _parser.getORcreateParam(double(1.0), "segmentRate", + "Relative rate for segment crossover", + 's', "Genetic Operators" ); + // minimum check + if ( (segmentRateParam.value() < 0) ) + throw std::runtime_error("Invalid segmentRate"); + + eoValueParam& arithmeticRateParam + = _parser.getORcreateParam(double(2.0), "arithmeticRate", + "Relative rate for arithmetic crossover", + 'A', "Genetic Operators" ); + // minimum check + if ( (arithmeticRateParam.value() < 0) ) + throw std::runtime_error("Invalid arithmeticRate"); + + // minimum check + bool bCross = true; + if (segmentRateParam.value()+arithmeticRateParam.value()==0) + { + std::cerr << "Warning: no crossover" << std::endl; + bCross = false; + } + + // Create the CombinedQuadOp + eoPropCombinedQuadOp *ptCombinedQuadOp = NULL; + eoQuadOp *ptQuad = NULL; + + if (bCross) + { + // segment crossover for bitstring - pass it the bounds + ptQuad = new eoSegmentCrossover(*ptBounds); + _state.storeFunctor(ptQuad); + ptCombinedQuadOp = new eoPropCombinedQuadOp(*ptQuad, segmentRateParam.value()); + + // arithmetic crossover + ptQuad = new eoArithmeticCrossover(*ptBounds); + _state.storeFunctor(ptQuad); + ptCombinedQuadOp->add(*ptQuad, arithmeticRateParam.value()); + + // don't forget to store the CombinedQuadOp + _state.storeFunctor(ptCombinedQuadOp); + } + + // the mutations + ///////////////// + // the parameters + eoValueParam & epsilonParam + = _parser.getORcreateParam(0.01, "epsilon", "Half-size of interval for Uniform Mutation", + 'e', "Genetic Operators" ); + // minimum check + if ( (epsilonParam.value() < 0) ) + throw std::runtime_error("Invalid epsilon"); + + eoValueParam & uniformMutRateParam + = _parser.getORcreateParam(1.0, "uniformMutRate", + "Relative rate for uniform mutation", 'u', "Genetic Operators" ); + // minimum check + if ( (uniformMutRateParam.value() < 0) ) + throw std::runtime_error("Invalid uniformMutRate"); + + eoValueParam & detMutRateParam + = _parser.getORcreateParam(1.0, "detMutRate", + "Relative rate for deterministic uniform mutation", + 'd', "Genetic Operators" ); + // minimum check + if ( (detMutRateParam.value() < 0) ) + throw std::runtime_error("Invalid detMutRate"); + + eoValueParam & normalMutRateParam + = _parser.getORcreateParam(1.0, "normalMutRate", + "Relative rate for Gaussian mutation", + 'd', "Genetic Operators" ); + // minimum check + if ( (normalMutRateParam.value() < 0) ) + throw std::runtime_error("Invalid normalMutRate"); + // and the sigma + eoValueParam & sigmaParam + = _parser.getORcreateParam(1.0, "sigma", + "Sigma (fixed) for Gaussian mutation", + 'S', "Genetic Operators" ); + // minimum check + if ( (sigmaParam.value() < 0) ) + throw std::runtime_error("Invalid sigma"); + + // minimum check + bool bMut = true; + if (uniformMutRateParam.value()+detMutRateParam.value()+normalMutRateParam.value()==0) + { + std::cerr << "Warning: no mutation" << std::endl; + bMut = false; + } + if (!bCross && !bMut) + throw std::runtime_error("No operator called in SGA operator definition!!!"); + + // Create the CombinedMonOp + eoPropCombinedMonOp *ptCombinedMonOp = NULL; + eoMonOp *ptMon = NULL; + + if (bMut) + { + // uniform mutation on all components: + // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon] + ptMon = new eoUniformMutation(*ptBounds, epsilonParam.value()); + _state.storeFunctor(ptMon); + // create the CombinedMonOp + ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, uniformMutRateParam.value()); + + // mutate exactly 1 component (uniformly) per individual + ptMon = new eoDetUniformMutation(*ptBounds, epsilonParam.value()); + _state.storeFunctor(ptMon); + ptCombinedMonOp->add(*ptMon, detMutRateParam.value()); + + // mutate all component using Gaussian mutation + ptMon = new eoNormalMutation(*ptBounds, sigmaParam.value()); + _state.storeFunctor(ptMon); + ptCombinedMonOp->add(*ptMon, normalMutRateParam.value()); + _state.storeFunctor(ptCombinedMonOp); + } + + // now build the eoGenOp: + // 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 + // a QuadCopy and our crossover + // with proba pMut, our mutation + + // the crossover - with probability pCross + eoProportionalOp * cross = new eoProportionalOp ; + _state.storeFunctor(cross); + ptQuad = new eoQuadCloneOp; + _state.storeFunctor(ptQuad); + cross->add(*ptCombinedQuadOp, pCrossParam.value()); // user crossover + cross->add(*ptQuad, 1-pCrossParam.value()); // clone operator + + // 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(*ptCombinedMonOp, pMutParam.value()); + + // that's it! + return *op; +} +/** @} */ +#endif diff --git a/deprecated/eo/src/es/make_op_es.cpp b/deprecated/eo/src/es/make_op_es.cpp new file mode 100644 index 000000000..4dfbacf34 --- /dev/null +++ b/deprecated/eo/src/es/make_op_es.cpp @@ -0,0 +1,79 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of operators fns + * of the library for ***eoReal*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 es.h in src/es dir + * while the TEMPLATIZED code is define in make_op.h in the es dir + * + */ + +// Templatized code +#include + +/// The following function merely call the templatized do_* functions above + +// operators +//////////// +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} diff --git a/deprecated/eo/src/es/make_op_es.h b/deprecated/eo/src/es/make_op_es.h new file mode 100644 index 000000000..00a3373f9 --- /dev/null +++ b/deprecated/eo/src/es/make_op_es.h @@ -0,0 +1,202 @@ +/* (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ + + +#ifndef EO_make_op_h +#define EO_make_op_h + +// the operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include + +// the specialized Real stuff +#include +#include +#include +#include +#include +#include +#include + // also need the parser and param includes +#include +#include + + +/** @addtogroup Builders + * @{ + */ + +/* + * This function builds the operators that will be applied to the eoReal + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * 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 + * about the gneotypes, the init has it all (e.g. bounds, ...) + * Simply do + * EOT myEO; + * _init(myEO); + * and myEO is then an ACTUAL object +*/ + +template +eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded& _init) +{ + // get std::vector size + unsigned vecSize = _init.size(); + + // First, decide whether the objective variables are bounded + eoValueParam& boundsParam + = _parser.getORcreateParam(eoRealVectorBounds(vecSize,eoDummyRealNoBounds), + "objectBounds", "Bounds for variables", + 'B', "Variation Operators"); + + std::cerr << boundsParam.value() << std::endl; + + // now we read Pcross and Pmut, + eoValueParam& operatorParam + = _parser.getORcreateParam(std::string("SGA"), "operator", + "Description of the operator (SGA only now)", + 'o', "Variation Operators"); + + if (operatorParam.value() != std::string("SGA")) + throw std::runtime_error("Sorry, only SGA-like operator available right now\n"); + + // now we read Pcross and Pmut, + // and create the eoGenOp that is exactly + // crossover with pcross + mutation with pmut + + eoValueParam& pCrossParam + = _parser.getORcreateParam(1.0, "pCross", "Probability of Crossover", + 'C', "Variation Operators" ); + // minimum check + if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) ) + throw std::runtime_error("Invalid pCross"); + + eoValueParam& pMutParam + = _parser.getORcreateParam(1.0, "pMut", "Probability of Mutation", + 'M', "Variation Operators" ); + // minimum check + if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) ) + throw std::runtime_error("Invalid pMut"); + + + // crossover + ///////////// + // ES crossover + eoValueParam& crossTypeParam + = _parser.getORcreateParam(std::string("global"), "crossType", + "Type of ES recombination (global or standard)", + 'C', "Variation Operators"); + + eoValueParam& crossObjParam + = _parser.getORcreateParam(std::string("discrete"), "crossObj", + "Recombination of object variables (discrete, intermediate or none)", + 'O', "Variation Operators"); + eoValueParam& crossStdevParam + = _parser.getORcreateParam(std::string("intermediate"), "crossStdev", + "Recombination of mutation strategy parameters " + "(intermediate, discrete or none)", + 'S', "Variation Operators"); + + // The pointers: first the atom Xover + eoBinOp *ptObjAtomCross = NULL; + eoBinOp *ptStdevAtomCross = NULL; + // then the EOT-level one (need to be an eoGenOp as global Xover is + eoGenOp *ptCross; + + // check for the atom Xovers + if (crossObjParam.value() == std::string("discrete")) + ptObjAtomCross = new eoDoubleExchange; + else if (crossObjParam.value() == std::string("intermediate")) + ptObjAtomCross = new eoDoubleIntermediate; + else if (crossObjParam.value() == std::string("none")) + ptObjAtomCross = new eoBinCloneOp; + else throw std::runtime_error("Invalid Object variable crossover type"); + + if (crossStdevParam.value() == std::string("discrete")) + ptStdevAtomCross = new eoDoubleExchange; + else if (crossStdevParam.value() == std::string("intermediate")) + ptStdevAtomCross = new eoDoubleIntermediate; + else if (crossStdevParam.value() == std::string("none")) + ptStdevAtomCross = new eoBinCloneOp; + else throw std::runtime_error("Invalid mutation strategy parameter crossover type"); + + // and build the indi Xover + 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 + eoBinOp & crossTmp = _state.storeFunctor( + new eoEsStandardXover(*ptObjAtomCross, *ptStdevAtomCross) + ); + ptCross = new eoBinGenOp(crossTmp); + } + else throw std::runtime_error("Invalide Object variable crossover type"); + + // now that everything is OK, DON'T FORGET TO STORE MEMORY + _state.storeFunctor(ptObjAtomCross); + _state.storeFunctor(ptStdevAtomCross); + _state.storeFunctor(ptCross); + + // mutation + ///////////// + + // Ok, time to set up the self-adaptive mutation + // Proxy for the mutation parameters + eoEsMutationInit mutateInit(_parser, "Variation Operators"); + + eoEsMutate & mut = _state.storeFunctor( + new eoEsMutate(mutateInit, boundsParam.value())); + + // now the general op - a sequential application of crossover and mutatation + // no need to first have crossover combined with a clone as it is an + // eoBinOp and not an eoQuadOp as in SGA paradigm + + eoSequentialOp & op = _state.storeFunctor(new eoSequentialOp); + op.add(*ptCross, pCrossParam.value()); + op.add(mut, pMutParam.value()); + + // that's it! + return op; +} +#endif // EO_make_op_h + + +/** @} */ + +// Local Variables: +// coding: iso-8859-1 +// mode:C++ +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/es/make_op_real.cpp b/deprecated/eo/src/es/make_op_real.cpp new file mode 100644 index 000000000..b429cd411 --- /dev/null +++ b/deprecated/eo/src/es/make_op_real.cpp @@ -0,0 +1,59 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of operators fns + * of the library for ***eoReal*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 es.h in src/es dir + * while the TEMPLATIZED code is define in make_op.h in the es dir + * + */ + +// Templatized code +#include + +/// The following function merely call the templatized do_* functions above + +// oeprators +//////////// +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init) +{ + return do_make_op(_parser, _state, _init); +} diff --git a/deprecated/eo/src/es/make_op_real.h b/deprecated/eo/src/es/make_op_real.h new file mode 100644 index 000000000..19a8b16b6 --- /dev/null +++ b/deprecated/eo/src/es/make_op_real.h @@ -0,0 +1,289 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_op.h - the real-valued version +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_op_h +#define _make_op_h + +// the operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include + +// the specialized Real stuff +#include +#include +#include +#include + // also need the parser and param includes +#include +#include + + +/** @addtogroup Builders + * @{ + */ + +/* + * This function builds the operators that will be applied to the eoReal + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * 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 + * about the gneotypes, the init has it all (e.g. bounds, ...) + * Simply do + * EOT myEO; + * _init(myEO); + * and myEO is then an ACTUAL object +*/ + +template +eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded& _init) +{ + // get std::vector size + unsigned vecSize = _init.size(); + + // First, decide whether the objective variables are bounded + eoValueParam& boundsParam + = _parser.getORcreateParam(eoRealVectorBounds(vecSize,eoDummyRealNoBounds), "objectBounds", + "Bounds for variables", 'B', "Variation Operators"); + + // this is a temporary version(!), + // while Maarten codes the full tree-structured general operator input + // BTW we must leave that simple version available somehow, as it is the one + // that 90% people use! + eoValueParam& operatorParam + = _parser.getORcreateParam(std::string("SGA"), "operator", + "Description of the operator (SGA only now)", + 'o', "Variation Operators"); + + if (operatorParam.value() != std::string("SGA")) + throw std::runtime_error("Sorry, only SGA-like operator available right now\n"); + + // 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 + // crossover with pcross + mutation with pmut + + eoValueParam& pCrossParam + = _parser.getORcreateParam(0.6, "pCross", + "Probability of Crossover", + 'C', "Variation Operators" ); + // minimum check + if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) ) + throw std::runtime_error("Invalid pCross"); + + eoValueParam& pMutParam + = _parser.getORcreateParam(0.1, "pMut", + "Probability of Mutation", + 'M', "Variation Operators" ); + // minimum check + if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) ) + throw std::runtime_error("Invalid pMut"); + + // the crossovers + ///////////////// + // the parameters + eoValueParam& alphaParam + = _parser.getORcreateParam(double(0.0), "alpha", + "Bound for factor of linear recombinations", + 'a', "Variation Operators" ); + // minimum check + if ( (alphaParam.value() < 0) ) + throw std::runtime_error("Invalid BLX coefficient alpha"); + + + eoValueParam& segmentRateParam + = _parser.getORcreateParam(double(1.0), "segmentRate", + "Relative rate for segment crossover", + 's', "Variation Operators" ); + // minimum check + if ( (segmentRateParam.value() < 0) ) + throw std::runtime_error("Invalid segmentRate"); + + eoValueParam& hypercubeRateParam + = _parser.getORcreateParam(double(1.0), "hypercubeRate", + "Relative rate for hypercube crossover", + 'A', "Variation Operators" ); + // minimum check + if ( (hypercubeRateParam.value() < 0) ) + throw std::runtime_error("Invalid hypercubeRate"); + + eoValueParam& uxoverRateParam + = _parser.getORcreateParam(double(1.0), "uxoverRate", + "Relative rate for uniform crossover", + 'A', "Variation Operators" ); + // minimum check + if ( (uxoverRateParam.value() < 0) ) + throw std::runtime_error("Invalid uxoverRate"); + + // minimum check + bool bCross = true; + if (segmentRateParam.value()+hypercubeRateParam.value()+uxoverRateParam.value()==0) + { + std::cerr << "Warning: no crossover" << std::endl; + bCross = false; + } + + // Create the CombinedQuadOp + eoPropCombinedQuadOp *ptCombinedQuadOp = NULL; + eoQuadOp *ptQuad = NULL; + + if (bCross) + { + // segment crossover for bitstring - pass it the bounds + ptQuad = new eoSegmentCrossover(boundsParam.value(), alphaParam.value()); + _state.storeFunctor(ptQuad); + ptCombinedQuadOp = new eoPropCombinedQuadOp(*ptQuad, segmentRateParam.value()); + + // hypercube crossover + ptQuad = new eoHypercubeCrossover(boundsParam.value(), alphaParam.value()); + _state.storeFunctor(ptQuad); + ptCombinedQuadOp->add(*ptQuad, hypercubeRateParam.value()); + + // uniform crossover + ptQuad = new eoRealUXover(); + _state.storeFunctor(ptQuad); + ptCombinedQuadOp->add(*ptQuad, uxoverRateParam.value()); + + // don't forget to store the CombinedQuadOp + _state.storeFunctor(ptCombinedQuadOp); + } + + // the mutations + ///////////////// + // the parameters + eoValueParam & epsilonParam + = _parser.getORcreateParam(0.01, "epsilon", + "Half-size of interval for Uniform Mutation", + 'e', "Variation Operators" ); + // minimum check + if ( (epsilonParam.value() < 0) ) + throw std::runtime_error("Invalid epsilon"); + + eoValueParam & uniformMutRateParam + = _parser.getORcreateParam(1.0, "uniformMutRate", + "Relative rate for uniform mutation", + 'u', "Variation Operators" ); + // minimum check + if ( (uniformMutRateParam.value() < 0) ) + throw std::runtime_error("Invalid uniformMutRate"); + + eoValueParam & detMutRateParam + = _parser.getORcreateParam(1.0, "detMutRate", + "Relative rate for deterministic uniform mutation", + 'd', "Variation Operators" ); + // minimum check + if ( (detMutRateParam.value() < 0) ) + throw std::runtime_error("Invalid detMutRate"); + + eoValueParam & normalMutRateParam + = _parser.getORcreateParam(1.0, "normalMutRate", + "Relative rate for Gaussian mutation", 'd', "Variation Operators" ); + // minimum check + if ( (normalMutRateParam.value() < 0) ) + throw std::runtime_error("Invalid normalMutRate"); + + eoValueParam & sigmaParam + = _parser.getORcreateParam(0.3, "sigma", + "Sigma (fixed) for Gaussian mutation", + 's', "Variation Operators" ); + + eoValueParam & pNormalParam + = _parser.getORcreateParam(1.0, "pNormal", + "Proba. to change each variable for Gaussian mutation", + 's', "Variation Operators" ); + + // minimum check + bool bMut = true; + if (uniformMutRateParam.value()+detMutRateParam.value()+normalMutRateParam.value()==0) + { + std::cerr << "Warning: no mutation" << std::endl; + bMut = false; + } + if (!bCross && !bMut) + throw std::runtime_error("No operator called in SGA operator definition!!!"); + + // Create the CombinedMonOp + eoPropCombinedMonOp *ptCombinedMonOp = NULL; + eoMonOp *ptMon = NULL; + + if (bMut) + { + // uniform mutation on all components: + // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon] + ptMon = new eoUniformMutation(boundsParam.value(), epsilonParam.value()); + _state.storeFunctor(ptMon); + // create the CombinedMonOp + ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, uniformMutRateParam.value()); + + // mutate exactly 1 component (uniformly) per individual + ptMon = new eoDetUniformMutation(boundsParam.value(), epsilonParam.value()); + _state.storeFunctor(ptMon); + ptCombinedMonOp->add(*ptMon, detMutRateParam.value()); + + // mutate all component using Gaussian mutation + ptMon = new eoNormalVecMutation(boundsParam.value(), sigmaParam.value(), pNormalParam.value()); + _state.storeFunctor(ptMon); + ptCombinedMonOp->add(*ptMon, normalMutRateParam.value()); + _state.storeFunctor(ptCombinedMonOp); + } + + // now build the eoGenOp: + // 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 + // a QuadCopy and our crossover + // with proba pMut, our mutation + + // the crossover - with probability pCross + eoProportionalOp * cross = new eoProportionalOp ; + _state.storeFunctor(cross); + ptQuad = new eoQuadCloneOp; + _state.storeFunctor(ptQuad); + cross->add(*ptCombinedQuadOp, pCrossParam.value()); // user crossover + cross->add(*ptQuad, 1-pCrossParam.value()); // clone operator + + // now the sequential + eoSequentialOp & op = _state.storeFunctor(new eoSequentialOp); + op.add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op.add(*ptCombinedMonOp, pMutParam.value()); + + // that's it! + return op; +} +/** @} */ +#endif diff --git a/deprecated/eo/src/es/make_pop_es.cpp b/deprecated/eo/src/es/make_pop_es.cpp new file mode 100644 index 000000000..4f72e3441 --- /dev/null +++ b/deprecated/eo/src/es/make_pop_es.cpp @@ -0,0 +1,84 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of pop. init. fns + * of the library for evolution of ***ES genotypes*** indis inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/es.h + * while the TEMPLATIZED code is define in make_pop.h in the src/do dir + */ + +// 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 + +/// The following function merely call the templatized do_* functions above + +// Init POP +/////////// +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +/////////// +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +/////////// +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} diff --git a/deprecated/eo/src/es/make_pop_real.cpp b/deprecated/eo/src/es/make_pop_real.cpp new file mode 100644 index 000000000..968e7251e --- /dev/null +++ b/deprecated/eo/src/es/make_pop_real.cpp @@ -0,0 +1,60 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of pop. init. fns + * of the library for evolution of ***eoReal*** indis inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/real.h + * while the TEMPLATIZED code is define in make_pop.h in the src/do dir + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions above + +// Init POP +/////////// +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} diff --git a/deprecated/eo/src/es/make_real.h b/deprecated/eo/src/es/make_real.h new file mode 100644 index 000000000..bc04ba1f1 --- /dev/null +++ b/deprecated/eo/src/es/make_real.h @@ -0,0 +1,107 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +/** 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, + * while the TEMPLATIZED code is define in the different make_XXX.h files + * 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 + * i.e. ***with*** mutation parameters attached to individuals + * + * Unlike most EO .h files, it does not (and should not) contain any code, + * just declarations + */ + +#ifndef real_h +#define real_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +//Representation dependent - rewrite everything anew for each representation +////////////////////////// + + +/** @addtogroup Builders + * @{ + */ +// the genotypes +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoReal _eo); +eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoReal _eo); + +// the operators +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoRealInitBounded >& _init); + +//Representation INdependent +//////////////////////////// +// you don't need to modify that part even if you use your own representation + +// init pop +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); + +// the continue's +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); + +// the checkpoint +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); + + +// the algo +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +// run +void run_ea(eoAlgo >& _ga, eoPop >& _pop); +void run_ea(eoAlgo >& _ga, eoPop >& _pop); + +// end of parameter input (+ .status + help) +// that one is not templatized +// Because of that, the source is in src/utils dir +void make_help(eoParser & _parser); + +/** @} */ +#endif diff --git a/deprecated/eo/src/es/make_run_es.cpp b/deprecated/eo/src/es/make_run_es.cpp new file mode 100644 index 000000000..59912a7f8 --- /dev/null +++ b/deprecated/eo/src/es/make_run_es.cpp @@ -0,0 +1,86 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of run funs + * of the library for evolution of ***ES genotypes*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/es.h + * while the TEMPLATIZED code is define in make_run.h in the src/do dir + */ + +// 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 +// the instanciating fitnesses +#include + +/// The following function merely call the templatized do_* functions above + +// run +///////// +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +///////// +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +///////// +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} diff --git a/deprecated/eo/src/es/make_run_real.cpp b/deprecated/eo/src/es/make_run_real.cpp new file mode 100644 index 000000000..2c61963c6 --- /dev/null +++ b/deprecated/eo/src/es/make_run_real.cpp @@ -0,0 +1,62 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// make_run_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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains ***INSTANCIATED DEFINITIONS*** of run funs + * of the library for evolution of ***eoReal*** inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 src/es/real.h + * while the TEMPLATIZED code is define in make_run.h in the src/do dir + */ + +// The templatized code +#include +// the instanciating EOType +#include +// the instanciating fitnesses +#include + +/// The following function merely call the templatized do_* functions above + +// run +///////// +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} diff --git a/deprecated/eo/src/es/matrices.h b/deprecated/eo/src/es/matrices.h new file mode 100644 index 000000000..82d890f73 --- /dev/null +++ b/deprecated/eo/src/es/matrices.h @@ -0,0 +1,45 @@ +#ifndef MATRICES_H +#define MATRICES_H + +#include + +/** @ingroup Utilities + */ +class lower_triangular_matrix { + + unsigned n; + std::vector data; + + public: + + lower_triangular_matrix(unsigned n_ = 0) : n(n_), data(n * (n+1) / 2) {}; + + void resize(unsigned n_) { + n = n_; + data.resize(n*(n+1)/2); + } + + std::vector::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; } +}; + +/** @ingroup Utilities + */ +class square_matrix { + unsigned n; + std::vector data; + + public: + + square_matrix(unsigned n_ = 0) : n(n_), data(n * n) {}; + + void resize(unsigned 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/deprecated/eo/src/ga.h b/deprecated/eo/src/ga.h new file mode 100644 index 000000000..6abb0181a --- /dev/null +++ b/deprecated/eo/src/ga.h @@ -0,0 +1,42 @@ +//----------------------------------------------------------------------------- +// 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 + 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 + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#ifndef _ga_h +#define _ga_h + +// all bitstring-specific files +#include + +// the operators +#include + +// #include to be corrected - thanks someone! + +//----------------------------------------------------------------------------- + +#endif diff --git a/deprecated/eo/src/ga/CMakeLists.txt b/deprecated/eo/src/ga/CMakeLists.txt new file mode 100644 index 000000000..22db30744 --- /dev/null +++ b/deprecated/eo/src/ga/CMakeLists.txt @@ -0,0 +1,35 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the ga target +###################################################################################### + +SET(GA_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) +SET(LIBRARY_OUTPUT_PATH ${GA_LIB_OUTPUT_PATH}) + +SET(GA_SOURCES + make_algo_scalar_ga.cpp + make_checkpoint_ga.cpp + make_continue_ga.cpp + make_genotype_ga.cpp + make_op_ga.cpp + make_pop_ga.cpp + make_run_ga.cpp + ) + +ADD_LIBRARY(ga STATIC ${GA_SOURCES}) +INSTALL(TARGETS ga ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +###################################################################################### +### 3) Optionnal +###################################################################################### + +SET(GA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(ga PROPERTIES VERSION "${GA_VERSION}") + +###################################################################################### diff --git a/deprecated/eo/src/ga/ChangeLog b/deprecated/eo/src/ga/ChangeLog new file mode 100644 index 000000000..56ed12d06 --- /dev/null +++ b/deprecated/eo/src/ga/ChangeLog @@ -0,0 +1,11 @@ +2007-08-21 Jochen Kpper + + * eoBitOp.h (eoNPtsBitXover::operator()): Make sure bit is within + allocated length of vector points: [0, max_size). + + + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/deprecated/eo/src/ga/Readme b/deprecated/eo/src/ga/Readme new file mode 100644 index 000000000..3d9b8663f --- /dev/null +++ b/deprecated/eo/src/ga/Readme @@ -0,0 +1,20 @@ +This directory contains: + +- 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. +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. +@see src/do/make_XXX.h files, and test/t-eoGA.cpp for an example use. + +Note: +Also are *defined* here two representation dependent make_XXX.h files +(together with their instanciations in make_XXX.cpp), namely the ones +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/deprecated/eo/src/ga/eoBit.h b/deprecated/eo/src/ga/eoBit.h new file mode 100644 index 000000000..c1bc9c75e --- /dev/null +++ b/deprecated/eo/src/ga/eoBit.h @@ -0,0 +1,128 @@ +/* + eoBit.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 + 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 +*/ + +/* MS, Nov. 23, 2000 + Added the calls to base class I/O routines that print the fitness + Left printing/reading of the size of the bitstring, + for backward compatibility, and as it is a general practice in EO + + MS, Feb. 7, 2001 + replaced all ...Bin... names with ...Bit... names - for bitstring + as it was ambiguous with bin...ary things +*/ + +#ifndef eoBit_h +#define eoBit_h + +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +#include "eoVector.h" + +/** @defgroup bitstring Bit strings + +Various functions for a bitstring representation. + +Example of a complete test program that use various bitstrings operators: +@include t-eobin.cpp + +@ingroup Representations +*/ + +/** Implementation of bitstring chromosome. + +@class eoBit eoBit.h ga/eoBit.h +@ingroup bitstring + +Based on STL's std::vector specialization. +*/ +template class eoBit: public eoVector +{ +public: + + using eoVector< FitT, bool >::begin; + using eoVector< FitT, bool >::end; + using eoVector< FitT, bool >::resize; + using eoVector< FitT, bool >::size; + + /** + * (Default) Constructor. + * @param size Size of the binary std::string. + * @param value Default value. + */ + eoBit(unsigned size = 0, bool value = false): + eoVector(size, value) {} + + /// My class name. + virtual std::string className() const + { + return "eoBit"; + } + + /** + * To print me on a stream. + * @param os The std::ostream. + */ + virtual void printOn(std::ostream& os) const + { + EO::printOn(os); + os << ' '; + os << size() << ' '; + std::copy(begin(), end(), std::ostream_iterator(os)); + } + + /** + * To read me from a stream. + * @param is The std::istream. + */ + virtual void readFrom(std::istream& is) + { + EO::readFrom(is); + unsigned s; + is >> s; + std::string bits; + is >> bits; + if (is) + { + resize(bits.size()); + std::transform(bits.begin(), bits.end(), begin(), + std::bind2nd(std::equal_to(), '1')); + } + } +}; + +//----------------------------------------------------------------------------- + +#endif //eoBit_h + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/ga/eoBitOp.h b/deprecated/eo/src/ga/eoBitOp.h new file mode 100644 index 000000000..15d77434d --- /dev/null +++ b/deprecated/eo/src/ga/eoBitOp.h @@ -0,0 +1,496 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoBitOp.h +// (c) GeNeura Team, 2000 - 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 + 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 + CVS Info: $Date: 2007-08-21 14:52:50 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/ga/eoBitOp.h,v 1.18 2007-08-21 14:52:50 kuepper Exp $ $Author: kuepper $ + */ +//----------------------------------------------------------------------------- + +#ifndef eoBitOp_h +#define eoBitOp_h + +//----------------------------------------------------------------------------- + +#include // swap_ranges +#include +#include // eoMonOp +#include + + +/** eoOneBitFlip --> changes 1 bit +\class eoOneBitFlip eoBitOp.h ga/eoBitOp.h +\ingroup bitstring + +@ingroup Variators +*/ + +template class eoOneBitFlip: public eoMonOp +{ + public: + /// The class name. + virtual std::string className() const { return "eoOneBitFlip"; } + + /** + * Change one bit. + * @param chrom The cromosome which one bit is going to be changed. + */ + bool operator()(Chrom& chrom) + { + unsigned i = eo::rng.random(chrom.size()); + chrom[i] = !chrom[i]; + return true; + } +}; + +/** eoDetBitFlip --> changes exactly k bits +\class eoDetBitFlip eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoDetBitFlip: public eoMonOp +{ + public: + /** + * (Default) Constructor. + * @param _num_bit The number of bits to change + * default is one - equivalent to eoOneBitFlip then + */ + eoDetBitFlip(const unsigned& _num_bit = 1): num_bit(_num_bit) {} + + /// The class name. + virtual std::string className() const { return "eoDetBitFlip"; } + + /** + * Change num_bit bits. + * @param chrom The cromosome which one bit is going to be changed. + */ + bool operator()(Chrom& chrom) + { + // for duplicate checking see eoDetSingleBitFlip + for (unsigned k=0; k changes exactly k bits with checking for duplicate +\class eoDetSingleBitFlip eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoDetSingleBitFlip: public eoMonOp +{ + public: + /** + * (Default) Constructor. + * @param _num_bit The number of bits to change + * default is one - equivalent to eoOneBitFlip then + */ + eoDetSingleBitFlip(const unsigned& _num_bit = 1): num_bit(_num_bit) {} + + /// The class name. + virtual std::string className() const { return "eoDetSingleBitFlip"; } + + /** + * Change num_bit bits. + * @param chrom The cromosome which one bit is going to be changed. + */ + bool operator()(Chrom& chrom) + { + std::vector< unsigned > selected; + + // check for duplicate + for (unsigned k=0; k classical mutation +\class eoBitMutation eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoBitMutation: public eoMonOp +{ + public: + /** + * (Default) Constructor. + * @param _rate Rate of mutation. + * @param _normalize use rate/chrom.size if true + */ + eoBitMutation(const double& _rate = 0.01, bool _normalize=false): + rate(_rate), normalize(_normalize) {} + + /// The class name. + virtual std::string className() const { return "eoBitMutation"; } + + /** + * Mutate a chromosome. + * @param chrom The chromosome to be mutated. + */ + bool operator()(Chrom& chrom) + { + double actualRate = (normalize ? rate/chrom.size() : rate); + bool changed_something = false; + for (unsigned i = 0; i < chrom.size(); i++) + if (eo::rng.flip(actualRate)) + { + chrom[i] = !chrom[i]; + changed_something = true; + } + + return changed_something; + } + + private: + double rate; + bool normalize; // divide rate by chromSize +}; + + +/** eoBitInversion: inverts the bits of the chromosome between an interval +\class eoBitInversion eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoBitInversion: public eoMonOp +{ + public: + /// The class name. + virtual std::string className() const { return "eoBitInversion"; } + + /** + * Inverts a range of bits in a binary chromosome. + * @param chrom The chromosome whos bits are going to be inverted (a range). + */ + bool operator()(Chrom& chrom) + { + + unsigned u1 = eo::rng.random(chrom.size() + 1) , u2; + do u2 = eo::rng.random(chrom.size() + 1); while (u1 == u2); + unsigned r1 = std::min(u1, u2), r2 = std::max(u1, u2); + + std::reverse(chrom.begin() + r1, chrom.begin() + r2); + return true; + } +}; + + +/** eoBitNext --> next value when bitstring considered as binary value +\class eoBitNext eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoBitNext: public eoMonOp +{ + public: + /// The class name. + virtual std::string className() const { return "eoBitNext"; } + + /** + * Change the bit std::string x to be x+1. + * @param chrom The chromosome to be added one. + */ + 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; + } + + return true; + } +}; + + +/** eoBitPrev --> previous value when bitstring treated as binary value +\class eoBitPrev eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoBitPrev: public eoMonOp +{ + public: + /// The class name. + virtual std::string className() const { return "eoBitPrev"; } + + /** + * Change the bit std::string x to be x-1. + * @param chrom The chromosome to be substracted one. + */ + 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; + } + + return true; + } +}; + + +/** eo1PtBitXover --> classic 1-point crossover +\class eo1PtBitCrossover eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eo1PtBitXover: public eoQuadOp +{ + public: + /// The class name. + virtual std::string className() const { return "eo1PtBitXover"; } + + /** + * 1-point crossover for binary chromosomes. + * @param chrom1 The first chromosome. + * @param chrom2 The first chromosome. + */ + bool operator()(Chrom& chrom1, Chrom& chrom2) + { + unsigned site = eo::rng.random(std::min(chrom1.size(), chrom2.size())); + + if (!std::equal(chrom1.begin(), chrom1.begin()+site, chrom2.begin())) + { + + std::swap_ranges(chrom1.begin(), chrom1.begin() + site, chrom2.begin()); + + return true; + } + return false; + } +}; + + +/** eoUBitXover --> classic Uniform crossover +\class eoUBitXover eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoUBitXover: public eoQuadOp +{ + public: + /// (Default) Constructor. + eoUBitXover(const float& _preference = 0.5): preference(_preference) + { + if ( (_preference <= 0.0) || (_preference >= 1.0) ) + std::runtime_error("UxOver --> invalid preference"); + } + /// The class name. + virtual std::string className() const { return "eoUBitXover"; } + + /** + * Uniform crossover for binary chromosomes. + * @param chrom1 The first chromosome. + * @param chrom2 The first chromosome. + * std::runtime_error if sizes don't match + */ + bool operator()(Chrom& chrom1, Chrom& chrom2) + { + if ( chrom1.size() != chrom2.size()) + std::runtime_error("UxOver --> chromosomes sizes don't match" ); + bool changed = false; + for (unsigned int i=0; i n-point crossover +\class eoNPtsBitXover eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ +template class eoNPtsBitXover : public eoQuadOp +{ +public: + + /** (Default) Constructor. */ + eoNPtsBitXover(const unsigned& _num_points = 2) : num_points(_num_points) + { + if (num_points < 1) + std::runtime_error("NxOver --> invalid number of points"); + } + + /** The class name */ + virtual std::string className() const { return "eoNPtsBitXover"; } + + /** n-point crossover for binary chromosomes. + + @param chrom1 The first chromosome. + @param chrom2 The first chromosome. + */ + bool operator()(Chrom& chrom1, Chrom& chrom2) { + unsigned max_size(std::min(chrom1.size(), chrom2.size())); + unsigned max_points(std::min(max_size - 1, num_points)); + std::vector points(max_size, false); + + // select ranges of bits to swap + do { + unsigned bit(eo::rng.random(max_size)); + if(points[bit]) + continue; + else { + points[bit] = true; + --max_points; + } + } while(max_points); + + // swap bits between chromosomes + bool change(false); + for (unsigned bit = 1; bit < points.size(); bit++) { + if (points[bit]) + change = !change; + if (change) { + typename Chrom::AtomType tmp = chrom1[bit]; + chrom1[bit] = chrom2[bit]; + chrom2[bit] = tmp; + } + } + return true; + } + +private: + + /** @todo Document this data member */ + unsigned num_points; +}; + + + +/** eoBitGxOver --> Npts crossover when bistd::string considered + as a std::string of binary-encoded genes (exchanges genes) +Is anybody still using it apart from historians ??? :-) +\class eoBitGxOver eoBitOp.h ga/eoBitOp.h +\ingroup bitstring +*/ + +template class eoBitGxOver: public eoQuadOp +{ + public: + /// Constructor. + eoBitGxOver(const unsigned _gene_size, const unsigned _num_points = 2): + gene_size(_gene_size), num_points(_num_points) + { + if (gene_size < 1) + std::runtime_error("GxOver --> invalid gene size"); + if (num_points < 1) + std::runtime_error("GxOver --> invalid number of points"); + } + + /// The class name + virtual std::string className() const { return "eoBitGxOver"; } + + /** + * Gene crossover for binary chromosomes. + * @param chrom1 The first chromosome. + * @param chrom2 The first chromosome. + */ + bool operator()(Chrom& chrom1, Chrom& chrom2) + { + unsigned max_genes = std::min(chrom1.size(), chrom2.size()) / gene_size; + unsigned cut_genes = std::min(max_genes, num_points); + + std::vector points(max_genes, false); + + // selects genes to swap + do { + 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); + + return true; + } + + private: + unsigned gene_size; + unsigned num_points; +}; + + + +//----------------------------------------------------------------------------- +//@} +#endif diff --git a/deprecated/eo/src/ga/eoBitOpFactory.h b/deprecated/eo/src/ga/eoBitOpFactory.h new file mode 100644 index 000000000..6511f9375 --- /dev/null +++ b/deprecated/eo/src/ga/eoBitOpFactory.h @@ -0,0 +1,172 @@ +// eoBitOpFactory.h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOpFactory.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOBITOPFACTORY_H +#define _EOBITOPFACTORY_H + +#include +#include + +//----------------------------------------------------------------------------- + +/** EO Factory. An instance of the factory class to create operators that act +on bitstring chromosomes. Only those chromosomes can instantiate the operators +that are created here +@see eoSelect + +@ingroup Variators +*/ +template< class EOT> +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) + { + 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 ); + } + + // 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( ); + } + + // 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( ); + } + + // 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 ); + } + + // 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; + }; + + +}; + + +#endif diff --git a/deprecated/eo/src/ga/eoBoolFlip.h b/deprecated/eo/src/ga/eoBoolFlip.h new file mode 100644 index 000000000..47c43ee06 --- /dev/null +++ b/deprecated/eo/src/ga/eoBoolFlip.h @@ -0,0 +1,49 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoBoolFlip_h +#define _eoBoolFlip_h + +#include + +/** a simple boolean mutation - to be used in generic eoOp's + * + @ingroup bitstring + @ingroup Variators + */ +class eoBoolFlip : public eoMonOp { +public: + /** simply flips the boolean argument */ + bool operator()(bool & _b) + { + _b = !_b; + return true; + } + + /** inherited className() */ + virtual string className() const {return "boolFlip";} + +}; + +#endif diff --git a/deprecated/eo/src/ga/eoPBILAdditive.h b/deprecated/eo/src/ga/eoPBILAdditive.h new file mode 100644 index 000000000..e57a05a2b --- /dev/null +++ b/deprecated/eo/src/ga/eoPBILAdditive.h @@ -0,0 +1,119 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPBILAdditive.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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoPBILAdditive_H +#define _eoPBILAdditive_H + +#include +#include + +/** + * Distribution Class for PBIL algorithm + * (Population-Based Incremental Learning, Baluja and Caruana 96) + * + * This class implements an extended update rule: + * in the original paper, the authors used + * + * p(i)(t+1) = (1-LR)*p(i)(t) + LR*best(i) + * + * here the same formula is applied, with some of the best individuals + * and for some of the worst individuals (with different learning rates) +*/ +template +class eoPBILAdditive : public eoDistribUpdater +{ +public: + /** Ctor with parameters + * 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 ) : + maxBound(1.0-_tolerance), minBound(_tolerance), + LR(0.0), nbBest(_nbBest), nbWorst(_nbWorst) + { + if (nbBest+nbWorst == 0) + throw std::runtime_error("Must update either from best or from worst in eoPBILAdditive"); + + if (_nbBest) + { + lrb = _LRBest/_nbBest; + LR += _LRBest; + } + else + lrb=0.0; // just in case + if (_nbWorst) + { + lrw = _LRWorst/_nbWorst; + LR += _LRWorst; + } + else + lrw=0.0; // just in case + } + + /** Update the distribution from the current population */ + virtual void operator()(eoDistribution & _distrib, eoPop& _pop) + { + eoPBILDistrib& distrib = dynamic_cast&>(_distrib); + + std::vector & p = distrib.value(); + + unsigned i, popSize=_pop.size(); + std::vector result; + _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]); + } + } + +private: + double maxBound, minBound; // proba stay away from 0 and 1 by at least tolerance + double LR; // learning rate + unsigned nbBest; // number of Best individuals used for update + unsigned nbWorst; // number of Worse individuals used for update + double lrb, lrw; // "local" learning rates (see operator()) +}; + +#endif diff --git a/deprecated/eo/src/ga/eoPBILDistrib.h b/deprecated/eo/src/ga/eoPBILDistrib.h new file mode 100644 index 000000000..56556ba05 --- /dev/null +++ b/deprecated/eo/src/ga/eoPBILDistrib.h @@ -0,0 +1,100 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPBILDistrib.h +// (c) Marc Schoenauer, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: Marc.Schoenauer@inria.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoPBILDistrib_H +#define _eoPBILDistrib_H + +#include + +/** + * 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 > : + * 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 > +{ +public: + /** Ctor with size of genomes, and update parameters */ + eoPBILDistrib(unsigned _genomeSize) : + eoDistribution(), + eoValueParam >(std::vector(_genomeSize, 0.5), "Distribution"), + genomeSize(_genomeSize) + {} + + /** the randomizer of indis */ + virtual void operator()(EOT & _eo) + { + _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; + } + } + + unsigned int size() {return genomeSize;} + + virtual std::string className() const {return "eoPBILDistrib";}; + +private: + unsigned genomeSize; // size of indis +}; + +#endif diff --git a/deprecated/eo/src/ga/eoPBILOrg.h b/deprecated/eo/src/ga/eoPBILOrg.h new file mode 100644 index 000000000..45b95c843 --- /dev/null +++ b/deprecated/eo/src/ga/eoPBILOrg.h @@ -0,0 +1,78 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPBILOrg.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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoPBILOrg_H +#define _eoPBILOrg_H + +#include +#include + +/** + * Distribution Class for PBIL algorithm + * (Population-Based Incremental Learning, Baluja and Caruana 95) + * + * This class implements the update rule from the original paper: + * + * p(i)(t+1) = (1-LR)*p(i)(t) + LR*best(i) +*/ + +template +class eoPBILOrg : public eoDistribUpdater +{ +public: + /** Ctor with size of genomes, and update parameters */ + eoPBILOrg(double _LR, double _tolerance=0.0 ) : + LR(_LR), maxBound(1.0-_tolerance), minBound(_tolerance) + {} + + + /** Update the distribution from the current population */ + virtual void operator()(eoDistribution & _distrib, eoPop& _pop) + { + const EOT & best = _pop.best_element(); + eoPBILDistrib& distrib = dynamic_cast&>(_distrib); + + std::vector & p = distrib.value(); + + for (unsigned g=0; g // for time(0) for random seeding +#include +#include +#include +#include + + +//////////////////////////DISTRIB CONSTRUCTION /////////////////////////////// +/** + * Templatized version of parser-based construct of the distribution + * for PBIL distribution evolution algorithm + * + * It must then be instantiated, and compiled on its own for a given EOType + * (see test/t-eoPBIL.cpp + * + * Last argument is template-disambiguating +*/ + + +template +eoPBILDistrib & do_make_PBILdistrib(eoParser & _parser, eoState& _state, EOT) +{ + // First the random seed + eoValueParam& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); + if (seedParam.value() == 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 + { + theSize = _parser.createParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); + } + else // it was read before, get its value + { + eoValueParam* ptChromSize = dynamic_cast*>(ptParam); + theSize = ptChromSize->value(); + } + + eoPBILDistrib * ptDistrib = new eoPBILDistrib(theSize); + _state.storeFunctor(ptDistrib); + + // now the initialization: read a previously saved distribution, or random + eoValueParam& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); + if (loadNameParam.value() != "") // something to load + { + // create another state for reading + eoState inState; // a state for loading - WITHOUT the parser + // register the rng and the distribution in the state, + // so they can be loaded, + // and the present run will be the exact continuation of the saved run + // eventually with different parameters + inState.registerObject(*ptDistrib); + inState.registerObject(rng); + inState.load(loadNameParam.value()); // load the distrib and the rng + } + else // nothing loaded from a file + { + rng.reseed(seedParam.value()); + } + + // for future stateSave, register the algorithm into the state + _state.registerObject(_parser); + _state.registerObject(*ptDistrib); + _state.registerObject(rng); + + return *ptDistrib; +} + +#endif diff --git a/deprecated/eo/src/ga/make_PBILupdate.h b/deprecated/eo/src/ga/make_PBILupdate.h new file mode 100644 index 000000000..a8572136d --- /dev/null +++ b/deprecated/eo/src/ga/make_PBILupdate.h @@ -0,0 +1,79 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + 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 + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_PBILupdate_h +#define _make_PBILupdate_h + +#include +#include +#include +#include + + +///////CONSTRUCTION of PBIL distribution updaters///////////////// +/** + * Templatized version of parser-based construct of the update rule for PBIL + * distributions (see eoPBILDistrib.h) + * + * It must then be instantiated, and compiled on its own for a given EOType + * (see test/t-eoPBIL.cpp) + * + * Last argument is template-disambiguating +*/ + + +template +eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, EOT) +{ + // 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(); + + unsigned nbBest = _parser.createParam(unsigned(1), "nbBest", "Number of good guys to update from", 'B', "Algorithm").value(); + double LRBest = _parser.createParam(0.1, "LRBest", "Learning Rate (from best guys)", 'L', "Algorithm").value(); + unsigned nbWorst = _parser.createParam(unsigned(0), "nbWorst", "Number of bad guys to update from", 'W', "Algorithm").value(); + double LRWorst = _parser.createParam(0.01, "LRWorst", "Learning Rate (from best guys)", 'L', "Algorithm").value(); + 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; + + if (UType == std::string("PBIL")) + { + if ( (nbWorst == 0) && (nbBest == 1) ) + ptUpdate = new eoPBILOrg(LRBest, tolerance); + else + ptUpdate = new eoPBILAdditive(LRBest, nbBest, tolerance, LRWorst, nbWorst); + } + else + 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); + return *ptUpdate; +} + +#endif diff --git a/deprecated/eo/src/ga/make_algo_scalar_ga.cpp b/deprecated/eo/src/ga/make_algo_scalar_ga.cpp new file mode 100644 index 000000000..631e6dadf --- /dev/null +++ b/deprecated/eo/src/ga/make_algo_scalar_ga.cpp @@ -0,0 +1,63 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of pop. init. + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 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, + * just declarations + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions above + +// Algo +/////// +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op, eoDistance >* _dist) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); +} diff --git a/deprecated/eo/src/ga/make_checkpoint_ga.cpp b/deprecated/eo/src/ga/make_checkpoint_ga.cpp new file mode 100644 index 000000000..eecc40caa --- /dev/null +++ b/deprecated/eo/src/ga/make_checkpoint_ga.cpp @@ -0,0 +1,62 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of operators + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 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, + * just declarations + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions + +// checkpoint +///////////// +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) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} diff --git a/deprecated/eo/src/ga/make_continue_ga.cpp b/deprecated/eo/src/ga/make_continue_ga.cpp new file mode 100644 index 000000000..fb4662c32 --- /dev/null +++ b/deprecated/eo/src/ga/make_continue_ga.cpp @@ -0,0 +1,62 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of operators + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 + * while the TEMPLATIZED code is define in make_continue.h in the src/do dir + * + * Unlike most EO .h files, it does not (and should not) contain any code, + * just declarations + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions above + +// continue +/////////// +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} diff --git a/deprecated/eo/src/ga/make_ga.h b/deprecated/eo/src/ga/make_ga.h new file mode 100644 index 000000000..206094881 --- /dev/null +++ b/deprecated/eo/src/ga/make_ga.h @@ -0,0 +1,99 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +/** 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, + * just declarations + */ + +#ifndef ga_h +#define ga_h + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +//Representation dependent - rewrite everything anew for each representation +////////////////////////// + +/** @addtogroup Builders + * @{ + */ + +// the genotypes +eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo, float _bias=0.5); + eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo, float _bias=0.5); + +// the operators +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoInit >& _init); +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoInit >& _init); + +//Representation INdependent +//////////////////////////// +// if you use your own representation, simply change the types of templates + +// init pop +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit >&); + +// the continue's +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval); + +// the checkpoint +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue); + + +// the algo +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _ccontinue, eoGenOp >& _op, eoDistance >* _dist = NULL); + +// run +void run_ea(eoAlgo >& _ga, eoPop >& _pop); +void run_ea(eoAlgo >& _ga, eoPop >& _pop); + +// end of parameter input (+ .status + help) +// that one is not templatized +// Because of that, the source is in src/utils dir +void make_help(eoParser & _parser); + +/** @} */ +#endif diff --git a/deprecated/eo/src/ga/make_genotype_ga.cpp b/deprecated/eo/src/ga/make_genotype_ga.cpp new file mode 100644 index 000000000..3344a8d87 --- /dev/null +++ b/deprecated/eo/src/ga/make_genotype_ga.cpp @@ -0,0 +1,55 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of operators + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 + * while the TEMPLATIZED code is define in make_genotype_ga.h + */ + +// the templatized code +#include + +/// The following function merely call the templatized do_* functions above + +eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo, float _bias) +{ + return do_make_genotype(_parser, _state, _eo, _bias); +} +eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo, float _bias) +{ + return do_make_genotype(_parser, _state, _eo, _bias); +} diff --git a/deprecated/eo/src/ga/make_genotype_ga.h b/deprecated/eo/src/ga/make_genotype_ga.h new file mode 100644 index 000000000..fad4f7563 --- /dev/null +++ b/deprecated/eo/src/ga/make_genotype_ga.h @@ -0,0 +1,79 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_genotype_h +#define _make_genotype_h + +#include +#include + // also need the parser and param includes +#include +#include + + +/////////////////// the bitstring //////////////// +/* + * 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 + * 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 + * 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 + * 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 + * that is ***not properly initialized*** + * + * @ingroup bitstring + * @ingroup Builders +*/ +template +eoInit & do_make_genotype(eoParser& _parser, eoState& _state, EOT, float _bias=0.5) +{ + // for bitstring, only thing needed is the size + // but it might have been already read in the definition fo the performance + unsigned theSize = _parser.getORcreateParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); + + // Then we can built a bitstring random initializer + // based on boolean_generator class (see utils/rnd_generator.h) + eoBooleanGenerator * gen = new eoBooleanGenerator(_bias); + _state.storeFunctor(gen); + eoInitFixedLength* init = new eoInitFixedLength(theSize, *gen); + // store in state + _state.storeFunctor(init); + return *init; +} + +#endif diff --git a/deprecated/eo/src/ga/make_op.h b/deprecated/eo/src/ga/make_op.h new file mode 100644 index 000000000..2035a4f85 --- /dev/null +++ b/deprecated/eo/src/ga/make_op.h @@ -0,0 +1,231 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_op_h +#define _make_op_h + +// the operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include + +// the specialized GA stuff +#include +#include + // also need the parser and param includes +#include +#include + + +/////////////////// bitstring operators /////////////// +// canonical (crossover + mutation) only at the moment // + +/* + * This function builds the operators that will be applied to the bitstrings + * + * It uses a parser (to get user parameters) and a state (to store the memory) + * the last argument is an individual, needed for 2 reasons + * it disambiguates the call after instanciations + * some operator might need some private information about the indis + * + * 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 + * about the gneotypes, the init has it all (e.g. bounds, ...) + * Simply do + * EOT myEO; + * _init(myEO); + * and myEO is then an ACTUAL object + * + * @ingroup bitstring + * @ingroup Builders +*/ + +template +eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init) +{ + // this is a temporary version, while Maarten codes the full tree-structured + // general operator input + // BTW we must leave that simple version available somehow, as it is the one + // that 90% people use! + 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"); + + // 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 + // crossover with pcross + mutation with pmut + + eoValueParam& pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ); + // minimum check + if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) ) + throw std::runtime_error("Invalid pCross"); + + eoValueParam& pMutParam = _parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" ); + // minimum check + if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) ) + throw std::runtime_error("Invalid pMut"); + + // the crossovers + ///////////////// + // the parameters + eoValueParam& onePointRateParam = _parser.createParam(double(1.0), "onePointRate", "Relative rate for one point crossover", '1', "Variation Operators" ); + // minimum check + if ( (onePointRateParam.value() < 0) ) + throw std::runtime_error("Invalid onePointRate"); + + eoValueParam& twoPointsRateParam = _parser.createParam(double(1.0), "twoPointRate", "Relative rate for two point crossover", '2', "Variation Operators" ); + // minimum check + if ( (twoPointsRateParam.value() < 0) ) + throw std::runtime_error("Invalid twoPointsRate"); + + eoValueParam& uRateParam = _parser.createParam(double(2.0), "uRate", "Relative rate for uniform crossover", 'U', "Variation Operators" ); + // minimum check + if ( (uRateParam.value() < 0) ) + throw std::runtime_error("Invalid uRate"); + + // minimum check + // bool bCross = true; // not used ? + if (onePointRateParam.value()+twoPointsRateParam.value()+uRateParam.value()==0) + { + std::cerr << "Warning: no crossover" << std::endl; + // bCross = false; + } + + // Create the CombinedQuadOp + eoPropCombinedQuadOp *ptCombinedQuadOp = NULL; + eoQuadOp *ptQuad = NULL; + // 1-point crossover for bitstring + 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); + ptCombinedQuadOp->add(*ptQuad, twoPointsRateParam.value()); + + // don't forget to store the CombinedQuadOp + _state.storeFunctor(ptCombinedQuadOp); + + // the mutations + ///////////////// + // the parameters + eoValueParam & pMutPerBitParam = _parser.createParam(0.01, "pMutPerBit", "Probability of flipping 1 bit in bit-flip mutation", 'b', "Variation Operators" ); + // minimum check + if ( (pMutPerBitParam.value() < 0) || (pMutPerBitParam.value() > 0.5) ) + throw std::runtime_error("Invalid pMutPerBit"); + + eoValueParam & bitFlipRateParam = _parser.createParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 's', "Variation Operators" ); + // minimum check + if ( (bitFlipRateParam.value() < 0) ) + throw std::runtime_error("Invalid bitFlipRate"); + + // oneBitFlip + eoValueParam & oneBitRateParam = _parser.createParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'd', "Variation Operators" ); + // minimum check + if ( (oneBitRateParam.value() < 0) ) + throw std::runtime_error("Invalid oneBitRate"); + + // kBitFlip + eoValueParam & kBitParam = _parser.createParam((unsigned)1, "kBit", "Number of bit for deterministic k bit-flip mutation", 0, "Variation Operators" ); + // minimum check + if ( ! kBitParam.value() ) + throw std::runtime_error("Invalid kBit"); + + eoValueParam & kBitRateParam = _parser.createParam(0.0, "kBitRate", "Relative rate for deterministic k bit-flip mutation", 0, "Variation Operators" ); + // minimum check + if ( (kBitRateParam.value() < 0) ) + throw std::runtime_error("Invalid kBitRate"); + + // minimum check + // bool bMut = true; // not used ? + if (bitFlipRateParam.value()+oneBitRateParam.value()==0) + { + std::cerr << "Warning: no mutation" << std::endl; + // bMut = false; + } + + // Create the CombinedMonOp + eoPropCombinedMonOp *ptCombinedMonOp = NULL; + eoMonOp *ptMon = NULL; + + // standard bit-flip mutation for bitstring + ptMon = new eoBitMutation(pMutPerBitParam.value()); + _state.storeFunctor(ptMon); + // create the CombinedMonOp + ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, bitFlipRateParam.value()); + + // mutate exactly 1 bit per individual + ptMon = new eoDetBitFlip; + _state.storeFunctor(ptMon); + ptCombinedMonOp->add(*ptMon, oneBitRateParam.value()); + + // mutate exactly k bit per individual + ptMon = new eoDetBitFlip(kBitParam.value()); + _state.storeFunctor(ptMon); + ptCombinedMonOp->add(*ptMon, kBitRateParam.value()); + + _state.storeFunctor(ptCombinedMonOp); + + // now build the eoGenOp: + // 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 + // a QuadCopy and our crossover + // with proba pMut, our mutation + + // the crossover - with probability pCross + eoProportionalOp * cross = new eoProportionalOp ; + _state.storeFunctor(cross); + ptQuad = new eoQuadCloneOp; + _state.storeFunctor(ptQuad); + cross->add(*ptCombinedQuadOp, pCrossParam.value()); // user crossover + cross->add(*ptQuad, 1-pCrossParam.value()); // clone operator + + // 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(*ptCombinedMonOp, pMutParam.value()); + + // that's it! + return *op; +} +#endif diff --git a/deprecated/eo/src/ga/make_op_ga.cpp b/deprecated/eo/src/ga/make_op_ga.cpp new file mode 100644 index 000000000..e3a53d651 --- /dev/null +++ b/deprecated/eo/src/ga/make_op_ga.cpp @@ -0,0 +1,61 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of operators + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 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, + * just declarations + */ + +// Templatized code +#include + +/// The following function merely call the templatized do_* functions above + +// oeprators +//////////// +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoInit >& _init) +{ + return do_make_op(_parser, _state, _init); +} + +eoGenOp >& make_op(eoParser& _parser, eoState& _state, eoInit >& _init) +{ + return do_make_op(_parser, _state, _init); +} diff --git a/deprecated/eo/src/ga/make_pop_ga.cpp b/deprecated/eo/src/ga/make_pop_ga.cpp new file mode 100644 index 000000000..319279793 --- /dev/null +++ b/deprecated/eo/src/ga/make_pop_ga.cpp @@ -0,0 +1,61 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of population init + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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/make_ga.h + * while the TEMPLATIZED code is define in make_pop.h in the src/do dir + * + */ + +// The templatized code +#include +// the instanciating EOType +#include + +/// The following function merely call the templatized do_* functions above + +// Init POP +/////////// +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} diff --git a/deprecated/eo/src/ga/make_run_ga.cpp b/deprecated/eo/src/ga/make_run_ga.cpp new file mode 100644 index 000000000..d64d2b025 --- /dev/null +++ b/deprecated/eo/src/ga/make_run_ga.cpp @@ -0,0 +1,65 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +/** This file contains all ***INSTANCIATED DEFINITIONS*** of operators + * of the library for ***BISTRING*** evolution inside EO. + * It should be included in the file that calls any of the corresponding fns + * 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 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, + * just declarations + */ + +// The templatized code +#include +// the instanciating EOType +#include +// the instanciating fitnesses +#include + +/// The following function merely call the templatized do_* functions above + +// run +///////// +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} diff --git a/deprecated/eo/src/gp/eoParseTree.h b/deprecated/eo/src/gp/eoParseTree.h new file mode 100644 index 000000000..88737d919 --- /dev/null +++ b/deprecated/eo/src/gp/eoParseTree.h @@ -0,0 +1,195 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoParseTree.h : eoParseTree class (for Tree-based Genetic Programming) +// (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 eoParseTree_h +#define eoParseTree_h + +#include +#include + +#include +#include +#include +#include + +using namespace gp_parse_tree; + +/** @defgroup ParseTree + +Various functions for tree-based Genetic Programming + +Example: +@include t-eoSymreg.cpp + +@ingroup Representations +*/ + + +/** Implementation of parse-tree for genetic programming + +@class eoParseTree eoParseTree.h gp/eoParseTree.h + +@ingroup ParseTree +*/ +template +class eoParseTree : public EO, public parse_tree +{ +public: + + using parse_tree::back; + using parse_tree::ebegin; + using parse_tree::eend; + using parse_tree::size; + + + typedef typename parse_tree::subtree Subtree; + + /* For Compatibility with the intel C++ compiler for Linux 5.x */ + typedef Node reference; + typedef const reference const_reference; + + /** + * Default Constructor + */ + eoParseTree(void) {} + + /** + * Copy Constructor + * @param tree The tree to copy + */ + eoParseTree(const parse_tree& tree) : parse_tree(tree) {} + +// eoParseTree(const eoParseTree& tree) : parse_tree(tree) {} + /** + * To prune me to a certain size + * @param _size My maximum size + */ + virtual void pruneTree(unsigned _size) + { + if (_size < 1) + return; + + while (size() > _size) + { + back() = this->operator[](size()-2); + } + } + + /** + * To read me from a stream + * @param is The std::istream + */ + + eoParseTree(std::istream& is) : EO(), parse_tree() + { + readFrom(is); + } + + /// My class name + std::string className(void) const { return "eoParseTree"; } + + /** + * To print me on a stream + * @param os The std::ostream + */ + void printOn(std::ostream& os) const + { + EO::printOn(os); + os << ' '; + + os << size() << ' '; + + std::copy(ebegin(), eend(), std::ostream_iterator(os, " ")); + } + + /** + * To read me from a stream + * @param is The std::istream + */ + void readFrom(std::istream& is) + { + + + EO::readFrom(is); + + unsigned sz; + is >> sz; + + + std::vector v(sz); + + unsigned i; + + for (i = 0; i < sz; ++i) + { + Node node; + is >> node; + v[i] = node; + } + parse_tree tmp(v.begin(), v.end()); + this->swap(tmp); + + /* + * old code which caused problems for paradisEO + * + * this can be removed once it has proved itself + EO::readFrom(is); + + // 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 + */ + +// friend function to print eoParseTree +template +std::ostream& operator<<(std::ostream& os, const eoParseTree& eot) +{ + eot.printOn(os); + return os; +} + +// friend function to read eoParseTree +template +std::istream& operator>>(std::istream& is, eoParseTree& eot) +{ + eot.readFrom(is); + return is; +} + +// for backward compatibility +#include +#include + +#endif diff --git a/deprecated/eo/src/gp/eoParseTreeDepthInit.h b/deprecated/eo/src/gp/eoParseTreeDepthInit.h new file mode 100644 index 000000000..18dc55b91 --- /dev/null +++ b/deprecated/eo/src/gp/eoParseTreeDepthInit.h @@ -0,0 +1,218 @@ +// -*- 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 +/* + This library is free software; you 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 + jeggermo@liacs.nl + + */ +//----------------------------------------------------------------------------- + +#ifndef eoParseTreeDepthInit_h +#define eoParseTreeDepthInit_h + +#include +#include +#include +#include +#include + +using namespace gp_parse_tree; + +/** eoParseTreeDepthInit : the initializer class for eoParseTree +\class eoParseTreeDepthInit eoParseTreeDepthInit.h gp/eoParseTreeDepthInit.h +\ingroup ParseTree +*/ + +// eoGpDepthInitializer is defined for backward compatibility +#define eoGpDepthInitializer eoParseTreeDepthInit + +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());}; + }; + + public : + + typedef eoParseTree EoType; + + /** + * Constructor + * @param _max_depth The maximum depth of a tree + * @param _initializor A std::vector containing the possible nodes + * @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( + unsigned _max_depth, + const std::vector& _initializor, + bool _grow = true, + 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) + { + if(initializor.empty()) + { + throw std::logic_error("eoParseTreeDepthInit: uhm, wouldn't you rather give a non-empty set of Nodes?"); + } + // lets sort the initializor std::vector according to arity (so we can be sure the terminals are in front) + // we use stable_sort so that if element i was in front of element j and they have the same arity i remains in front of j + stable_sort(initializor.begin(), initializor.end(), lt_arity()); + } + /// My class name + 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; + }; + + } + 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 + typename std::vector::iterator it; + for (it = initializor.begin(); it != initializor.end(); ++it) + { + if (it->arity() > 0) + break; + } + + last_terminal = it - initializor.begin(); + } + + 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); + + 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; +}; + +/** + * A template function for ramped half and half initialization of an eoParseTree population + * @param pop the population to be created + * @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; + + 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; + } +} + + +#endif diff --git a/deprecated/eo/src/gp/eoParseTreeOp.h b/deprecated/eo/src/gp/eoParseTreeOp.h new file mode 100644 index 000000000..0b623f3d8 --- /dev/null +++ b/deprecated/eo/src/gp/eoParseTreeOp.h @@ -0,0 +1,380 @@ +// -*- 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 +// (c) Jeroen Eggermont 2001 for other mutation operators + +/* + This library is free software; you 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 + jeggermo@liacs.nl + */ +//----------------------------------------------------------------------------- + +#ifndef eoParseTreeOp_h +#define eoParseTreeOp_h + +#include +#include + +#include + +/** eoSubtreeXOver --> subtree xover +\class eoSubtreeXOver eoParseTreeOp.h gp/eoParseTreeOp.h +\ingroup ParseTree +*/ +template +class eoSubtreeXOver: public eoQuadOp< eoParseTree > { +public: + + typedef eoParseTree EoType; + /** + * Constructor + * @param _max_length the maximum size of an individual + */ + eoSubtreeXOver( unsigned _max_length) + : eoQuadOp(), max_length(_max_length) {}; + + /// the ckassname + virtual std::string className() const { return "eoSubtreeXOver"; }; + + /// Dtor + virtual ~eoSubtreeXOver () {}; + + /** + * Perform crossover on two individuals + * param _eo1 The first parent individual + * param _eo2 The second parent individual + */ + bool operator()(EoType & _eo1, EoType & _eo2 ) + { + 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; + + _eo1.pruneTree(max_length); + _eo2.pruneTree(max_length); + + return true; + } + private: + unsigned max_length; +}; + +/** eoBranchMutation --> replace a subtree with a randomly created subtree +\class eoBranchMutation eoParseTreeOp.h gp/eoParseTreeOp.h +\ingroup ParseTree + */ +template +class eoBranchMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + /** + * Constructor + * @param _init An instantiation of eoGpDepthInitializer + * @param _max_length the maximum size of an individual + */ + 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()); + + EoType eo2; + initializer(eo2); + + int j = rng.random(eo2.size()); + + _eo1[i] = eo2[j]; // insert subtree + + _eo1.pruneTree(max_length); + + return true; + } + +private : + + unsigned max_length; + eoInit& initializer; +}; + +// Additional Mutation operators from +// TITLE:"Genetic Programming~An Introduction" +// AUTHORS: Banzhaf, Nordin, Keller, Francone +// ISBN: 3-920993-58-6 +// ISBN: 1-55860-510-X +// +// For the eoParseTree class + +/** eoPointMutation --> replace a Node with a Node of the same arity +\class eoPointMutation eoParseTreeOp.h gp/eoParseTreeOp.h +\ingroup ParseTree +*/ + +template +class eoPointMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + + /** + * Constructor + * @param _initializor The std::vector of Nodes given to the eoGpDepthInitializer + */ + eoPointMutation( std::vector& _initializor) + : eoMonOp(), initializor(_initializor) + {}; + + /// the class name + virtual std::string className() const { return "eoPointMutation"; }; + + /// Dtor + virtual ~eoPointMutation() {}; + + /** + * Mutate an individual + * @param _eo1 The individual that is to be changed + */ + 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; + } + +private : + std::vector& initializor; + +}; + +/** eoExpansionMutation --> replace a terminal with a randomly created subtree +\class eoExpansionMutation eoParseTreeOp.h gp/eoParseTreeOp.h +\ingroup ParseTree + */ + +template +class eoExpansionMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + + /** + * Constructor + * @param _init An instantiation of eoGpDepthInitializer + * @param _max_length the maximum size of an individual + */ + eoExpansionMutation(eoInit& _init, unsigned _max_length) + : eoMonOp(), max_length(_max_length), initializer(_init) + {}; + + /// The class name + virtual std::string className() const { return "eoExpansionMutation"; }; + + /// Dtor + virtual ~eoExpansionMutation() {}; + /** + * Mutate an individual + * @param _eo1 The individual that is to be changed + */ + bool operator()(EoType& _eo1 ) + { + 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()); + }; + + + _eo1[i] = eo2[j]; // insert subtree + + _eo1.pruneTree(max_length); + + return true; + } + +private : + + unsigned max_length; + eoInit& initializer; +}; + +/** eoCollapseSubtree --> replace a subtree with a randomly chosen terminal +\class eoCollapseSubtreeMutation eoParseTreeOp.h gp/eoParseTreeOp.h +\ingroup ParseTree + */ + +template +class eoCollapseSubtreeMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + /** + * Constructor + * @param _init An instantiation of eoGpDepthInitializer + * @param _max_length the maximum size of an individual + */ + eoCollapseSubtreeMutation(eoInit& _init, unsigned _max_length) + : eoMonOp(), max_length(_max_length), initializer(_init) + {}; + + /// The class name + virtual std::string className() const { return "eoCollapseSubtreeMutation"; }; + + /// Dtor + virtual ~eoCollapseSubtreeMutation() {}; + /** + * Mutate an individual + * @param _eo1 The individual that is to be changed + */ + bool operator()(EoType& _eo1 ) + { + 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()); + }; + + _eo1[i] = eo2[j]; // insert subtree + + // we don't have to prune because the subtree is always smaller + _eo1.pruneTree(max_length); + + return true; + } + +private : + + unsigned max_length; + eoInit& initializer; +}; + + +/** 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 > +{ +public: + + typedef eoParseTree EoType; + + /** + * Constructor + */ + eoHoistMutation() + : eoMonOp() + {}; + + /// The class name + virtual std::string className() const { return "eoHoistMutation"; }; + + /// Dtor + virtual ~eoHoistMutation() {}; + /** + * Mutate an individual + * @param _eo1 The individual that is to be changed + */ + 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; + + return true; + } + +private : + +}; + + +#endif diff --git a/deprecated/eo/src/gp/eoStParseTreeDepthInit.h b/deprecated/eo/src/gp/eoStParseTreeDepthInit.h new file mode 100644 index 000000000..37b178873 --- /dev/null +++ b/deprecated/eo/src/gp/eoStParseTreeDepthInit.h @@ -0,0 +1,194 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStParseTreeDepthInit.h : initializor strongly type GP +// (c) Jeroen Eggermont 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + jeggermo@liacs.nl + + */ +//----------------------------------------------------------------------------- + +#ifndef eoStParseTreeDepthInit_h +#define eoStParseTreeDepthInit_h + +#include +#include +#include +#include + +#include + +using namespace gp_parse_tree; + +#define TERMINAL 0 + +#define NONTERMINAL 4 +#define ALL 5 + + /** +\defgroup StParseTree + + Various functions for strongly typed tree-based Genetic Programming. + The StParseTree functions use the same eoParseTree class for the + 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 +*/ + +/** eoStParseTreeDepthInit : the initializer class for strongly typed tree-based genetic programming +\class eoStParseTreeDepthInit eoStParseTreeDepthInit.h gp/eoStParseTreeDepthInit.h +\ingroup StParseTree +*/ + +template +class eoStParseTreeDepthInit : public eoInit< eoParseTree > +{ + public : + + typedef eoParseTree EoType; + + /** + * Constructor + * @param _max_depth The maximum depth of a tree + * @param _node A std::vector containing the possible nodes + * @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( + unsigned _max_depth, + const std::vector& _node, + const int& _return_type, + bool _grow = true) + : + eoInit(), + 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; + + } + + + } + /// My class name + 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); + + 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; + + } + + + + + unsigned max_depth; + std::map < int, std::map < int, std::vector > > node; + + int return_type; + bool grow; +}; + +#endif diff --git a/deprecated/eo/src/gp/eoStParseTreeOp.h b/deprecated/eo/src/gp/eoStParseTreeOp.h new file mode 100644 index 000000000..88020448d --- /dev/null +++ b/deprecated/eo/src/gp/eoStParseTreeOp.h @@ -0,0 +1,312 @@ +// -*- 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 + +/* + This library is free software; you 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 + jeggermo@liacs.nl + */ +//----------------------------------------------------------------------------- + +#ifndef eoStParseTreeOp_h +#define eoStParseTreeOp_h + +#include +#include +#include +#include +#include + +#include + +// a help function +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); +} + + +/** eoStSubtreeXOver --> subtree xover for strongly typed tree-based genetic programming +\class eoStSubtreeXOver eoStParseTreeOp.h gp/eoStParseTreeOp.h +\ingroup StParseTree +*/ +template +class eoStSubtreeXOver: public eoQuadOp< eoParseTree > { +public: + + typedef eoParseTree EoType; + /** + * Constructor + * @param _max_length the maximum size of an individual + */ + eoStSubtreeXOver( unsigned _max_length) + : eoQuadOp(), max_length(_max_length) {}; + + /// the ckassname + virtual std::string className() const { return "eoStSubtreeXOver"; }; + + /// Dtor + virtual ~eoStSubtreeXOver () {}; + + /** + * Perform crossover on two individuals + * param _eo1 The first parent individual + * param _eo2 The second parent individual + */ + 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 ?? + + // 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; + } + private: + unsigned max_length; +}; + +/** eoStBranchMutation --> replace a strongly typed subtree with a randomly created strongly typed subtree +\class eoStBranchMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h +\ingroup StParseTree + */ +template +class eoStBranchMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + /** + * Constructor + * @param _init An instantiation of eoGpDepthInitializer + * @param _max_length the maximum size of an individual + */ + 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; + + EoType eo2; + + 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; + } + +private : + + unsigned max_length; + eoInit& initializer; +}; + + +/** eoStPointMutation --> replace a Node with a Node of the same arity and type +\class eoStPointMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h +\ingroup StParseTree + */ +template +class eoStPointMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + + /** + * Constructor + * @param _node The std::vector of Nodes given to the eoGpDepthInitializer + */ + eoStPointMutation( std::vector& _node) + : eoMonOp() + { + 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; + + }; + }; + + /// the class name + virtual std::string className() const { return "eoStPointMutation"; }; + + /// Dtor + virtual ~eoStPointMutation() {}; + + /** + * Mutate an individual + * @param _eo1 The individual that is to be changed + */ + 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()); + + + _eo1[i] = node[type][arity][j]; + return true; + } + +private : + + std::map < int, std::map < int, std::vector > > node; +}; + + + /** eoStHoistMutation --> replace the individual with one of its strongly typed subtree's +\class eoStHoistMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h +\ingroup StParseTree + */ +template +class eoStHoistMutation: public eoMonOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + /** + * Constructor + * @param _init An instantiation of eoStDepthInit + * @param _max_length the maximum size of an individual + */ + 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 + */ + bool operator()(EoType& _eo1 ) + { + + 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; + + return true; + } + +private : + + unsigned max_length; + eoInit& initializer; +}; + + +#endif diff --git a/deprecated/eo/src/gp/node_pool.h b/deprecated/eo/src/gp/node_pool.h new file mode 100644 index 000000000..8935e7e2e --- /dev/null +++ b/deprecated/eo/src/gp/node_pool.h @@ -0,0 +1,313 @@ +/** + + * Pool allocator for the subtree and parse tree classes (homebrew and not compliant to ANSI allocator requirements) + * (c) copyright Maarten Keijzer 1999, 2000 + + * 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. + + +*/ + +#ifndef node_pool_h +#define node_pool_h + +class MemPool +{ +public : + + MemPool(unsigned int sz) : esize(sznext; + delete p; + } + } + + void* allocate() + { + if (head == 0) grow(); + Link* p = head; + head = p->next; + return static_cast(p); + } + + void deallocate(void* b) + { + Link* p = static_cast(b); + p->next = head; + head = p; + } + +private : + + void grow() + { + Chunk* n = new Chunk; + n->next = chunks; + chunks = n; + + const int nelem = Chunk::size/esize; + char* start = n->mem; + char* last = &start[(nelem-1)*esize]; + for (char* p = start; p < last; p += esize) + { + reinterpret_cast(p)->next = + reinterpret_cast(p + esize); + } + + reinterpret_cast(last)->next = 0; + head = reinterpret_cast(start); + } + + struct Link + { + Link* next; + }; + + struct Chunk + { + enum {size = 8 * 1024 - 16}; + Chunk* next; + char mem[size]; + }; + + Chunk* chunks; + const unsigned int esize; + Link* head; +}; + +template +class Node_alloc +{ +public : + + T* allocate(void) + { + T* t = static_cast(mem.allocate()); + t = new (t) T; + return t; + } + + T* construct(const T& org) + { + T* t = static_cast(mem.allocate()); + t = new (t) T(org); + return t; + } + + void deallocate(T* t) + { + t->~T(); // call destructor + mem.deallocate(static_cast(t)); + } + +private : + static MemPool mem; +}; + + +template +class Standard_alloc +{ +public : + Standard_alloc() {} + + T* allocate(size_t arity = 1) + { + if (arity == 0) + return 0; + + return new T [arity]; + } + + T* construct(size_t arity, T* org) + { + if (arity == 0) + return 0; + + T* t = new T [arity]; + + for (int i = 0; i < arity; ++i) + { + t = T(org[i]); + } + } + + void deallocate(T* t, size_t arity = 1) + { + if (arity == 0) + return ; + + delete [] t; + } + +}; + +template +class Standard_Node_alloc +{ +public : + Standard_Node_alloc() {} + + T* allocate(void) + { + return new T;// [arity]; + } + + T* construct(const T& org) + { + return new T(org); + } + + void deallocate(T* t) + { + delete t; + } + +}; + +template +class Tree_alloc +{ +public : + Tree_alloc() {} + + T* allocate(size_t arity) + { + T* t; + + switch(arity) + { + + case 0 : return 0; + case 1 : + { + t = static_cast(mem1.allocate()); + new (t) T; + break; + } + case 2 : + { + t = static_cast(mem2.allocate()); + new (t) T; + new (&t[1]) T; + break; + } + case 3 : + { + t = static_cast(mem3.allocate()); + new (t) T; + new (&t[1]) T; + new (&t[2]) T; + break; + } + default : + { + return new T[arity]; + } + } + + return t; + } + + T* construct(size_t arity, T* org) + { + T* t; + + switch(arity) + { + + case 0 : return 0; + case 1 : + { + t = static_cast(mem1.allocate()); + new (t) T(*org); + break; + } + case 2 : + { + t = static_cast(mem2.allocate()); + new (t) T(*org); + new (&t[1]) T(org[1]); + break; + } + case 3 : + { + t = static_cast(mem3.allocate()); + new (t) T(*org); + new (&t[1]) T(org[1]); + new (&t[1]) T(org[2]); + break; + } + default : + { + t = new T[arity]; // does call default ctor + for (int i = 0; i < arity; ++i) + { + t[i] = T(org[i]); // constructs now + } + } + } + + return t; + } + + + + void deallocate(T* t, size_t arity) + { + switch(arity) + { + case 0: return; + case 3 : + { + t[2].~T(); t[1].~T(); t[0].~T(); + mem3.deallocate(static_cast(t)); + return; + } + case 2 : + { + t[1].~T(); t[0].~T(); + mem2.deallocate(static_cast(t)); + return; + } + case 1 : + { + t[0].~T(); + mem1.deallocate(static_cast(t)); + return; + } + default : + { + delete [] t; + return; + } + } + } + + +private : + static MemPool mem1; + static MemPool mem2; + static MemPool mem3; +}; + +// static (non thread_safe) memory pools +template MemPool Node_alloc::mem = sizeof(T); + +template MemPool Tree_alloc::mem1 = sizeof(T); +template MemPool Tree_alloc::mem2 = sizeof(T) * 2; +template MemPool Tree_alloc::mem3 = sizeof(T) * 3; + +#endif diff --git a/deprecated/eo/src/gp/parse_tree.h b/deprecated/eo/src/gp/parse_tree.h new file mode 100644 index 000000000..84ec04d35 --- /dev/null +++ b/deprecated/eo/src/gp/parse_tree.h @@ -0,0 +1,1012 @@ +#ifndef PARSE_TREE_HH +#define PARSE_TREE_HH + +/** + + * Parse_tree and subtree classes + * (c) copyright Maarten Keijzer 1999, 2000 + + * 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 as well as this one are retained, and a notice that the code was + * modified is included with the above copyright notice. + + + + Usage information. + + class Node (your node in the tree) must have the following implemented: + + ****** Arity ****** + \code + int arity(void) const + \endcode + + 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) + + is the simplest evaluation, it will call + + \code + RetVal Node::operator()(RetVal, subtree::const_iterator) + \endcode + + (Unfortunately the first RetVal argument is mandatory (although you + might not need it. This is because MSVC does not support member template + functions properly. If it cannot deduce the template arguments (as is + the case in templatizing over return value) you are not allowed to + specify them. calling tree.apply() would result in a syntax + error. That is why you have to call tree.apply(double()) instead.) + + + 2) parse_tree::apply(RetVal v, It values) + + will call: + + \code + RetVal Node::operator()(RetVal, subtree<... , It values) + \endcode + + where It is whatever type you desire (most of the time + this will be a std::vector containing the values of your + variables); + + 3) parse_tree::apply(RetVal, It values, It2 moreValues) + + will call: + + \code + RetVal Node::operator()(RetVal, subtree<... , It values, It2 moreValues) + \endcode + + although I do not see the immediate use of this, however... + + 4) parse_tree::apply(RetVal, It values, It2 args, It3 adfs) + + that calls: + + \code + RetVal Node::operator()(subtree<... , It values, It2 args, It3 adfs) + \endcode + + 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: + + \code + template + RetVal operator()(RetVal dummy, It begin) const + \endcode + + ****** Internal Structure ****** + + A parse_tree has two template arguments: the Node and the ReturnValue + produced by evaluating the node. The structure of the tree is defined + through a subtree class that has the same two template arguments. + + The nodes are stored in a tree like : + + node4 + / \ + node3 node2 + / \ + node1 node0 + + where nodes 2 and 4 have arity 2 and nodes 0,1 and 3 arity 0 (terminals) + + The nodes are subtrees, containing the structure of the tree, together + with its size and depth. They contain a Node, the user defined template + argument. To access these nodes from a subtree, use operator-> or operator*. + + The numbers behind the nodes define a reverse-polish or postfix + traversel through the tree. The parse_tree defines iterators + on the tree such that + + tree.begin() points at the subtree at node0 and + tree.back() returns the subtree at node4, the complete tree + + Likewise operator[] is defined on the tree, such that: + + tree[0] will return the subtree at node0, while + tree[2] will return the subtree at node2 + + Assigments of subtrees is protected so that the code: + + tree[2] = tree[0]; + + will not crash and result in a tree structured as: + + node4 + / \ + node3 node0 + + Note that the rank numbers no longer specify their place in the tree: + + tree[0] still points at node0, but + tree[1] now points to node3 and + tree[2] points at the root node4 + + Embedded iterators are implemented to iterate over nodes rather + than subtrees. So an easy way to copy your tree to a std::vector is: + + std::vector vec(tree.size()); + copy(tree.ebegin(), tree.eend(), vec.begin()); + + You can also copy it to an std::ostream_iterator with this + technique, given that your Node implements an appropriate + operator<<. Reinitializing a tree with the std::vector is also + simple: + + tree.clear(); + copy(vec.begin(), vec.end(), back_inserter(tree)); + + or from an std::istream: + +\code + copy(std::istream_iterator(my_stream), std::istream_iterator(), back_inserter(tree)); +\endcode + + Note that the back_inserter must be used as there is no + resize member in the parse_tree. back_inserter will use + the push_back member from the parse_tree + +*/ + +#include +#include // for swap + +#ifdef _MSC_VER +#pragma warning(disable : 4786) // disable this nagging warning about the limitations of the mirkosoft debugger +#endif + +namespace gp_parse_tree +{ + +#include "node_pool.h" + +/// This ones defined because gcc does not always implement namespaces +template +inline void do_the_swap(T& a, T& b) +{ + T tmp = a; + a = b; + b = tmp; +} + +template class parse_tree +{ + public : + + +class subtree +{ + +/** + a bit nasty way to use a pool allocator (which would otherwise use slooow new and delete) + @todo use the std::allocator interface +*/ + +#if (defined(__GNUC__) || defined(_MSC_VER)) && !(defined(_MT) || defined(MACOSX) || defined(__APPLE__)) // not multithreaded (or MACOSX - J. Eggermont) + Node_alloc node_allocator; + Tree_alloc tree_allocator; +#else + Standard_Node_alloc node_allocator; + Standard_alloc tree_allocator; +#endif + +public : + + typedef subtree* iterator; + typedef const subtree* const_iterator; + + /* 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), + parent(0), + _cumulative_size(1), + _depth(1), + _size(1) + { + copy(s); + } + + subtree(const T& t) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + { copy(t); } + + template + subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + { // initialize in prefix order for efficiency reasons + init(b, --e); + } + + virtual ~subtree(void) { tree_allocator.deallocate(args, arity()); node_allocator.deallocate(content); } + + subtree& operator=(const subtree& s) + { + 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); + updateAfterInsert(); + return *this; + } + + subtree& operator=(const T& t) { copy(t); updateAfterInsert(); return *this; } + + /* 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== */ + + 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; + } + + return true; + } + + bool operator !=(const subtree& other) const + { + return !operator==(other); + } + + /* 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()); } + + template + void apply(RetVal& v, It values) const + { + (*content)(v, begin(), values); + } + + template + void apply_mem_func(RetVal& v, It misc, void (T::* f)(RetVal&, typename subtree::iterator, It)) + { + (content->*f)(v, begin(), misc); + } + + +/* template + 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 find_nodes(std::vector& result, Pred& p) + { + if (p(*content)) + { + result.push_back(this); + } + + for (int i = 0; i < arity(); ++i) + { + args[i].find_nodes(result, p); + } + } + + template + void find_nodes(std::vector& result, Pred& p) const + { + if (p(*content)) + { + result.push_back(this); + } + + for (int i = 0; i < arity(); ++i) + { + args[i].find_nodes(result, p); + } + } + + /* Iterators */ + + iterator begin(void) { return args; } + const_iterator begin(void) const { return args; } + + 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); } + + /* Some statistics */ + + size_t size(void) const { return _size; } + + size_t cumulative_size(void) const { return _cumulative_size; } + size_t depth(void) const { return _depth; } + + const subtree& select_cumulative(size_t which) const + { return imp_select_cumulative(which); } + + subtree& select_cumulative(size_t which) + { return const_cast(imp_select_cumulative(which)); } + + subtree& get_node(size_t which) + { return const_cast(imp_get_node(which));} + const subtree& get_node(size_t which) const + { return imp_get_node(which); } + + 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 swap(subtree& y) + { + do_the_swap(content, y.content); + do_the_swap(args, y.args); + + adopt(); + y.adopt(); + + do_the_swap(parent, y.parent); + + do_the_swap(_cumulative_size, y._cumulative_size); + do_the_swap(_depth, y._depth); + do_the_swap(_size, y._size); + updateAfterInsert(); + } + +protected : + + virtual void updateAfterInsert(void) + { + _depth = 0; + _size = 1; + _cumulative_size = 0; + + for (iterator it = begin(); it != end(); ++it) + { + _size += it->size(); + _cumulative_size += it->_cumulative_size; + _depth = it->_depth > _depth? it->_depth: _depth; + } + _cumulative_size += _size; + _depth++; + + if (parent) + parent->updateAfterInsert(); + } + +private : + + const subtree& imp_select_cumulative(size_t which) const + { + if (which >= (_cumulative_size - size())) + return *this; + // 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; + } + + return *this; // error! + } + + const subtree& imp_get_node(size_t which) const + { + if (which == size() - 1) + 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); + which -= c_size; + } + + return *this; // error! + } + + const subtree* get_root(void) const + { + if (parent == 0) + return this; + // else + + return parent->get_root(); + } + subtree& copy(const subtree& s) + { + int old_arity = arity(); + + int new_arity = s.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]); + args[i].parent = this; + } + } + } + + *content = *s.content; + _size = s._size; + _depth = s._depth; + _cumulative_size = s._cumulative_size; + + return *this; + } + + subtree& copy(const T& t) + { + int oldArity = arity(); + + if (content != &t) + *content = t; + else + oldArity = -1; + + int ar = arity(); + + if (ar != oldArity) + { + if (oldArity != -1) + tree_allocator.deallocate(args, oldArity); + + args = tree_allocator.allocate(ar); + + //if (ar > 0) + // args = new subtree [ar]; + //else + // args = 0; + } + + adopt(); + updateAfterInsert(); + 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 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; + } + } + } + } + + template + void init(It b, It& last) + { + *this = *last; + +#ifndef NDEBUG + if (last == b && arity() > 0) + { + throw "subtree::init()"; + } +#endif + + for (int i = 0; i < arity(); ++i) + { + args[i].parent = 0; + args[i].init(b, --last); + args[i].parent = this; + } + + updateAfterInsert(); + } + + T* content; + subtree* args; + subtree* parent; + + size_t _cumulative_size; + size_t _depth; + size_t _size; +}; + +// Continuing with parse_tree + + typedef T value_type; + + /* Constructors and Assignments */ + + parse_tree(void) : _root(), pushed() {} + parse_tree(const parse_tree& org) : _root(org._root), pushed(org.pushed) { } + parse_tree(const subtree& sub) : _root(sub), pushed() { } + + template + parse_tree(It b, It e) : _root(b, e), pushed() {} + + virtual ~parse_tree(void) {} + + parse_tree& operator=(const parse_tree& org) { return copy(org); } + parse_tree& operator=(const subtree& sub) + { return copy(sub); } + + + /* Equality and inequality */ + + bool operator==(const parse_tree& other) const + { return _root == other._root; } + + bool operator !=(const parse_tree& other) const + { return !operator==(other); } + + /* Simple tree statistics */ + + size_t size(void) const { return _root.size(); } + 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 */ + + template + void apply(RetVal& v) const + { _root.apply(v); } + + 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)) + { + _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, It3 evenMoreValues) const + // { _root.apply(v, varValues, moreValues, evenMoreValues); } + + template + void find_nodes(std::vector& result, Pred& p) + { + _root.find_nodes(result, p); + } + + template + void find_nodes(std::vector& result, Pred& p) const + { + _root.find_nodes(p); + } + + /* Customized Swap */ + void swap(parse_tree& other) + { + do_the_swap(pushed, other.pushed); + _root.swap(other._root); + } + + /* Definitions of the iterators */ + + class base_iterator + { + public : + + base_iterator() {} + base_iterator(subtree* n) { node = n; } + + base_iterator& operator=(const base_iterator& org) + { node = org.node; return *this; } + + bool operator==(const base_iterator& org) const + { return node == org.node; } + bool operator!=(const base_iterator& org) const + { return !operator==(org); } + + base_iterator operator+(size_t n) const + { + base_iterator tmp = *this; + + for(;n != 0; --n) + { + ++tmp; + } + + return tmp; + } + + base_iterator& operator++(void) + { + subtree* parent = node->get_parent(); + + if (parent == 0) + { + node = 0; + return *this; + } + // else + typename subtree::iterator it; + for (it = parent->begin(); it != parent->end(); ++it) + { + if (node == &(*it)) + break; + } + + if (it == parent->begin()) + node = parent; + else + { + node = &(--it)->get_node(0); + } + + return *this; + } + + base_iterator operator++(int) + { + base_iterator tmp = *this; + operator++(); + return tmp; + } + + protected : + subtree* node; + }; + + class iterator : public base_iterator + { + public: + + using base_iterator::node; + + typedef std::forward_iterator_tag iterator_category; + typedef subtree value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef subtree* pointer; + typedef subtree& reference; + + iterator() : base_iterator() {} + iterator(subtree* n): base_iterator(n) {} + iterator& operator=(const iterator& org) + { base_iterator::operator=(org); return *this; } + + subtree& operator*(void) { return *node; } + subtree* operator->(void) { return node; } + }; + + + + class embedded_iterator : public base_iterator + { + public: + + using base_iterator::node; + + typedef std::forward_iterator_tag iterator_category; + typedef T value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef T* pointer; + typedef T& reference; + + embedded_iterator() : base_iterator() {} + embedded_iterator(subtree* n): base_iterator(n) {} + embedded_iterator& operator=(const embedded_iterator& org) + { base_iterator::operator=(org); return *this; } + + T& operator*(void) { return **node; } + T* operator->(void) { return &**node; } + }; + + class base_const_iterator + { + public: + + base_const_iterator() {} + base_const_iterator(const subtree* n) { node = n; } + + base_const_iterator& operator=(const base_const_iterator& org) + { node = org.node; return *this; } + + bool operator==(const base_const_iterator& org) const + { return node == org.node; } + bool operator!=(const base_const_iterator& org) const + { return !operator==(org); } + + base_const_iterator& operator++(void) + { + const subtree* parent = node->get_parent(); + + if (parent == 0) + { + node = 0; + return *this; + } + // else + typename subtree::const_iterator it; + + for (it = parent->begin(); it != parent->end(); ++it) + { + if (node == &(*it)) + break; + } + + if (it == parent->begin()) + node = parent; + else + node = &(--it)->get_node(0); + return *this; + } + + base_const_iterator operator++(int) + { + base_const_iterator tmp = *this; + operator++(); + return tmp; + } + + protected : + + const subtree* node; + }; + + class const_iterator : public base_const_iterator + { + public: + + using base_const_iterator::node; + + typedef std::forward_iterator_tag iterator_category; + typedef const subtree value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef const subtree* pointer; + typedef const subtree& reference; + + const_iterator() : base_const_iterator() {} + const_iterator(const subtree* n): base_const_iterator(n) {} + const_iterator& operator=(const const_iterator& org) + { base_const_iterator::operator=(org); return *this; } + + const subtree& operator*(void) { return *node; } + const subtree* operator->(void) { return node; } + }; + + class embedded_const_iterator : public base_const_iterator + { + public: + + 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; + + 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; + + for(;n != 0; --n) + { + ++tmp; + } + + return tmp; + } + + const T& operator*(void) const { return **node; } + const T* operator->(void) const { return node->operator->(); } + }; + + /* Iterator access */ + + iterator begin(void) { return iterator(&operator[](0)); } + const_iterator begin(void) const { return const_iterator(&operator[](0)); } + iterator end(void) { return iterator(0); } + const_iterator end(void) const { return const_iterator(0);} + + embedded_iterator ebegin(void) { return embedded_iterator(&operator[](0)); } + embedded_const_iterator ebegin(void) const { return embedded_const_iterator(&operator[](0)); } + embedded_iterator eend(void) { return embedded_iterator(0); } + embedded_const_iterator eend(void) const { return embedded_const_iterator(0);} + + bool empty(void) const { return size() == 0; } + bool valid(void) const { return pushed.empty(); } + + /* push_back */ + + void push_back(const parse_tree& tree) + { + if (!empty()) + pushed.push_back(_root); + + _root = tree.back(); + } + + void push_back(const T& t) + { + if (!empty()) + pushed.push_back(_root); + + _root = t; + + for (typename subtree::iterator it = _root.begin(); it != _root.end(); it++) + { + *it = pushed.back(); + pushed.pop_back(); + } + + } + + /* Access to subtrees */ + + subtree& back(void) { return _root; } + const subtree& back(void) const { return _root; } + subtree& root(void) { return _root; } + const subtree& root(void) const { return _root; } + + subtree& front(void) { return _root[0]; } + const subtree& front(void) const { return _root[0]; } + + subtree& operator[](size_t i) + { return const_cast(_root.get_node(i)); } + const subtree& operator[](size_t i) const + { return _root.get_node(i); } + + subtree& get_cumulative(size_t i) + { return const_cast(_root.get_cumulative(i)); } + const subtree& get_cumulative(size_t i) const + { return get_cumulative(i); } + + private : + + parse_tree& copy(const parse_tree& org) + { + _root = org._root; + pushed = org.pushed; + + return *this; + } + + parse_tree& copy(const subtree& sub) + { _root = sub; pushed.resize(0); return *this; } + + subtree _root; + std::vector pushed; +}; // end class parse_tree + + +} // end namespace gp_parse_tree + +namespace std +{ // for use with stlport on MSVC + +template inline +std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::embedded_iterator) +{ + return std::forward_iterator_tag(); +} + +template inline +ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::embedded_iterator) +{ + return 0; +} + +template inline +std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::iterator) +{ + return std::forward_iterator_tag(); +} + +template inline +ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::iterator) +{ + return 0; +} + +/* Put customized swaps also in std... + +template inline +void swap(gp_parse_tree::parse_tree& a, gp_parse_tree::parse_tree& b) +{ + a.swap(b); +} + +template inline +void iter_swap(std::vector >::iterator a, std::vector > b) +{ + a->swap(*b); +}*/ + + +} // namespace std + + +#endif diff --git a/deprecated/eo/src/other/eoExternalEO.h b/deprecated/eo/src/other/eoExternalEO.h new file mode 100644 index 000000000..4440b428f --- /dev/null +++ b/deprecated/eo/src/other/eoExternalEO.h @@ -0,0 +1,100 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoExternalEO.h + Definition of an object that allows an external struct to be inserted in EO + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoExternalEO_h +#define eoExternalEO_h + +#include // EO + +/** + * Definition of an object that allows an external struct + * to be inserted in EO. This struct or class can be of any + * form, the only thing this class does is attach a fitness + * value to it and makes it the appropriate type (derives it from EO). + * + * @ingroup Utilities +*/ +template +class eoExternalEO : public EO, virtual public External +{ +public : + + eoExternalEO() + : External(), EO() + {} + + /** Init externalEo with the struct itself and set fitness to zero */ + eoExternalEO(const External& ext) + : EO(), External(ext) + {} + + eoExternalEO(std::istream& is, const External& ext) + : EO(), External(ext) + { readFrom(is); } + + /** + * Read object, the external struct needs to have an operator>> defined + */ + virtual void readFrom(std::istream& _is) + { + EO::readFrom(_is); + _is >> static_cast(*this); + } + + /** + * Write object. Called printOn since it prints the object _on_ a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + EO::printOn(_os); + _os << static_cast(*this); + } + +}; +/** @example t-eoExternalEO.cpp + */ + +/** To remove ambiguities between EO and External, streaming operators are defined yet again + * @ingroup Utilities + */ +template +std::ostream& operator<<(std::ostream& os, const eoExternalEO& eo) +{ + eo.printOn(os); + return os; +} + +/** To remove ambiguities between EO and External, streaming operators are defined yet again + * @ingroup Utilities + */ +template +std::istream& operator>>(std::istream& is, eoExternalEO& eo) +{ + eo.readFrom(is); + return is; +} + +#endif diff --git a/deprecated/eo/src/other/eoExternalOpFunctions.h b/deprecated/eo/src/other/eoExternalOpFunctions.h new file mode 100644 index 000000000..d86b49c45 --- /dev/null +++ b/deprecated/eo/src/other/eoExternalOpFunctions.h @@ -0,0 +1,180 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoExternalOpFunc.h + Defines eoExternalInitOpFunc, eoExternalMonOpFunc, eoExternalBinOpFunc, eoExternalQuadOpFunc + that are used to wrap a function pointer to externally defined initialization + and 'genetic' operators + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoExternalOpFunc_h +#define eoExternalOpFunc_h + +#include +#include +#include +#include + +/** + Initialization of external struct, ctor expects a function of the following + signature: + + External func(); + + Where External is the user defined struct or class + + @ingroup Utilities +*/ +template > +class eoExternalInit : public eoInit +{ + +public : + + eoExternalInit(External (*_init)(void)) : init(_init) {} + + + void operator()(ExternalEO& _eo) + { + _eo.External::operator=( (*init)() ); + _eo.invalidate(); + } + +private : + + External (*init)(void); +}; + +/** + Evaluation of external struct, ctor expects a function of the following + signature: + + Fit func(External&); + + Where External is the user defined struct or class and Fit the fitness type + +@ingroup Utilities +*/ +template > +class eoExternalEvalFunc : public eoEvalFunc +{ + public : + + eoExternalEvalFunc(F (*_eval)(const External&)) : eval(_eval) {} + + void operator()(ExternalEO& eo) + { + if (eo.invalid()) + eo.fitness( (*eval)(eo) ); + } + + private : + + F (*eval)(const External&); +}; + +/** + Mutation of external struct, ctor expects a function of the following + signature: + + bool func(External&); + + + Where External is the user defined struct or class. + The function should return true when it changed something, false otherwise + + @ingroup Utilities +*/ + +template > +class eoExternalMonOp : public eoMonOp +{ + public : + + eoExternalMonOp(bool (*_mutate)(External&)) : mutate(_mutate) {} + + bool operator()(ExternalEO& eo) + { + return (*mutate)(eo); + } + + private : + + bool (*mutate)(External&); +}; + +/** + Crossover of external struct, ctor expects a function of the following + signature: + + bool func(External&, const External&); + + Where External is the user defined struct or class + The function should return true when it changed something, false otherwise + + @ingroup Utilities +*/ +template > +class eoExternalBinOp : public eoBinOp +{ + public : + + eoExternalBinOp(bool (*_binop)(External&, const External&)) : binop(_binop) {} + + bool operator()(ExternalEO& eo1, const ExternalEO& eo2) + { + return (*binop)(eo1, eo2); + } + + private : + + bool (*binop)(External&, const External&); +}; + +/** + Crossover of external struct, ctor expects a function of the following + signature: + + bool func(External&, External&); + + Where External is the user defined struct or class + The function should return true when it changed something, false otherwise + + @ingroup Utilities +*/ +template > +class eoExternalQuadOp : public eoQuadOp +{ + public : + + eoExternalQuadOp(bool (*_quadop)(External&, External&)) : quadop(_quadop) {} + + bool operator()(ExternalEO& eo1, ExternalEO& eo2) + { + return (*quadop)(eo1, eo2); + } + + private : + + bool (*quadop)(External&, External&); +}; + +#endif diff --git a/deprecated/eo/src/other/eoString.h b/deprecated/eo/src/other/eoString.h new file mode 100644 index 000000000..3071d1ee6 --- /dev/null +++ b/deprecated/eo/src/other/eoString.h @@ -0,0 +1,84 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoString.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoString_H +#define _eoString_H + +// STL libraries +#include +#include +#include + + +#include + +//----------------------------------------------------------------------------- +// eoString +//----------------------------------------------------------------------------- + +/** Adaptor that turns an STL std::string into an EO + + @ingroup Representations + @ingroup Utilities + */ +template +class eoString: public EO, public std::string +{ +public: + + typedef char Type; + typedef char AtomType; + typedef std::string ContainerType; + + + /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator + //@{ + /// ctor + eoString( const std::string& _str ="" ) + : std::string( _str ) {}; + + /// printing... + virtual void printOn(std::ostream& os) const + { + EO::printOn(os); + os << ' '; + + os << size() << ' ' << substr() << std::endl; + + } + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual std::string className() const {return "eoString";}; + //@} + + +}; + +#endif diff --git a/deprecated/eo/src/other/external_eo b/deprecated/eo/src/other/external_eo new file mode 100644 index 000000000..aeaaaab6b --- /dev/null +++ b/deprecated/eo/src/other/external_eo @@ -0,0 +1,2 @@ +#include +#include diff --git a/deprecated/eo/src/pyeo/AUTHORS b/deprecated/eo/src/pyeo/AUTHORS new file mode 100644 index 000000000..e1d909968 --- /dev/null +++ b/deprecated/eo/src/pyeo/AUTHORS @@ -0,0 +1,3 @@ + +Maarten Keijzer (mkeijzer@cs.vu.nl) + diff --git a/deprecated/eo/src/pyeo/BUILDING b/deprecated/eo/src/pyeo/BUILDING new file mode 100644 index 000000000..3db7de1b7 --- /dev/null +++ b/deprecated/eo/src/pyeo/BUILDING @@ -0,0 +1,174 @@ + + +To build PyEO, a number of steps are neccessary. PyEO depends on Boost.Python v2, +which in turn expects the presence of python2.2. As we can't expect people to have +this installed some instructions are in order to help people build PyEO.so + +First of all, currently Windows is not supported. I don't develop on windows and +don't have access to a compiler on it. + +PyEO has been developed on Debian, using gcc 2.95-4. + +My primary platform is debian, so the default Makefile provides for that. Below you +will also find instructions for rpm-based distributions. As far as I know this includes +RedHat, Mandrake, Suse, Yellowdog, and probably a lot more. If I recall correctly, the RPM +format is the LSB default. + +===== Building PyEO on Debian ===== + +Point your /etc/apt/sources.list to the unstable distribution (if it's not there already), +and install: + +for Python: + +$ apt-get install python2.2 +$ apt-get install python2.2-dev + +It might also be a good idea to install the numeric library + +$ apt-get install python2.2-numeric + + +For Boost.Python: + +$ apt-get install libboost-python1.29.0 +$ apt-get install libboost-python-dev + +If all goes well, this will also install libstlport. If it doesn't, + +$ apt-get install libstlport4.5 + +and maybe + +$ apt-get install libstlport4.5-dev + +but I'm not sure about the latter. + +Now you can type + +$ make + +And after (a long) wait, a file called PyEO.so will be produced. + +===== Building PyEO on an RPM-based Distro ===== + +The following recipe has only been tested on a RedHat 7.1 installation, on other +systems some stuff might be different. + +== Getting Python2.2 == + +If you don't have python2.2 installed (newer distro's install this by default), +you can either install it from a binary specifically build for your distro, or +you can build it from source by going to: + +http://www.python.org/2.2.1/rpms.html + +and getting the source by clicking the link to python2-2.2.1-2.src.rpm + +This actually links to: + +http://www.python.org/ftp/python/2.2.1/rpms/python2-2.2.1-2.src.rpm + +for your convenience I mirrored this file at: + +http://www.cs.vu.nl/~mkeijzer/PyEO/python2-2.2.1-2.src.rpm + +by usuing the command: + +$ rpm --rebuild python2-2.2.1-2.src.rpm + +or with newer versions of rpm + +$ rpmbuild python2-2.2.1-2.src.rpm + +It will build a binary rpm for your computer. On this Redhat 7.1 box it put the +RPMS it build in + +/usr/src/redhat/RPMS/i386/ + +The ones you need to install are: + +python2-2.2.1-2.i386.rpm +python2-devel-2.2.1-2.i386.rpm + +But you might want to install the rest as well. + +== Getting Boost.Python == + +First of all, do a quick check. At the prompt type: + +$ python + +If you see something like: + +Python 2.2.2 (#4, Oct 15 2002, 04:21:28) +[GCC 2.95.4 20011002 (Debian prerelease)] on linux2 +Type "help", "copyright", "credits" or "license" for more information. + +(don't mind the second line, It's the version info we're interested in) + +You're set to go. Unfortunately, on this Redhat 7.1 box I tested things on, /usr/bin/python +insisted on pointing to /usr/bin/python1.5 . Unfortunately, the boost source rpm depends +on python to provide 2.2. If this is the case on your machine as well, there are two +possible fixes (of which one I tested). + +/usr/bin/python is a symlink, let it point to /usr/bin/python2.2 (this one I tested) + +DON'T forget to repoint /usr/bin/python to /usr/bin/python1.5 after you build the boost libraries: Redhat tools +depend on this! + +or + +alias python=/usr/bin/python2.2 (which would be better if it works, but untested.) + +So given that you are in a shell that uses python2.2 if you issue +the command 'python', get two boost source rpms at: + +http://www.starostik.de/malte/boost/ + +namely + +boost-jam-3.1.3-1.src.rpm +boost-1.29.0-2.src.rpm + +Which I also mirrored at + +http://www.cs.vu.nl/~mkeijzer/PyEO/boost-jam-3.1.3-1.src.rpm +http://www.cs.vu.nl/~mkeijzer/PyEO/boost-1.29.0-2.src.rpm + +First build and install jam using either rpm --rebuild or rpmbuild. + +The file you have to install is: + +boost-jam-3.1.3-1.i386.rpm + +This is the 'make' replacement that is used by boost. + +Next, build boost-1.29.0.src.rpm using 'rpm --rebuild' or 'rpmbuild' + +The only rpm's that this procedure produces that you need to install is: + +boost-python-1.29.0-2.i386.rpm +boost-python-devel-1.29.0-2.i386.rpm + + +When installing boost-python-devel, I got a dependency problem with libpython-dev, +this was probably caused by the same problem I had with python2.2, python1.5. I ignored +it by using: + +$ rpm -i --nodep boost-python-devel-1.29.0-2.i386.rpm + +and you're all set to type + +$ make -fMakefile.rpm + +in the PyEO build directory + +==== Testing PyEO========== + +After building go to the test directory and type + +$ ./run_tests.sh + +If you don't see errors, all is well and you're ready to go + diff --git a/deprecated/eo/src/pyeo/CMakeLists.txt b/deprecated/eo/src/pyeo/CMakeLists.txt new file mode 100644 index 000000000..697c96a16 --- /dev/null +++ b/deprecated/eo/src/pyeo/CMakeLists.txt @@ -0,0 +1,63 @@ +# -------------------------------------------------------------------------- +# +# 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) +# +# ---------------------------------------------------------------------------- + +CMAKE_MINIMUM_REQUIRED(VERSION 2.8) + +PROJECT(PyEO) + +FIND_PACKAGE(Boost 1.42 COMPONENTS python) +FIND_PACKAGE(PythonLibs) + +INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) + +LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) + +IF(APPLE) + # osx internal + FIND_LIBRARY(APPLE_CARBON Carbon) +ENDIF(APPLE) + +# includes +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +#INCLUDE_DIRECTORIES(../) + +# source +FILE(GLOB SOURCES *.cpp) + +# EO dependencies +SET(EO_SOURCES + ${EO_SOURCE_DIR}/src/eoFunctorStore.cpp + ${EO_SOURCE_DIR}/src/utils/eoLogger.cpp + ${EO_SOURCE_DIR}/src/utils/eoParallel.cpp + ) + +# shared library +ADD_LIBRARY(PyEO MODULE ${SOURCES} ${EO_SOURCES}) +INSTALL(TARGETS PyEO LIBRARY DESTINATION local/${LIB} COMPONENT libraries) + +# python 2.5 must have pyd +IF(WIN32 AND NOT CYGWIN) + 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}) +ELSE(APPLE) + TARGET_LINK_LIBRARIES(PyEO ${PYTHON_LIBRARY} ${Boost_LIBRARIES}) +ENDIF(APPLE) diff --git a/deprecated/eo/src/pyeo/COPYING b/deprecated/eo/src/pyeo/COPYING new file mode 100644 index 000000000..d60c31a97 --- /dev/null +++ b/deprecated/eo/src/pyeo/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our 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 + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/deprecated/eo/src/pyeo/Makefile b/deprecated/eo/src/pyeo/Makefile new file mode 100644 index 000000000..61c4f89f4 --- /dev/null +++ b/deprecated/eo/src/pyeo/Makefile @@ -0,0 +1,35 @@ +# Note for however is foolish enough to attempt to build this thing +# +# You need: +# Python 2.2 +# Boost.Python v2 +# + +CXX = g++ +CPPFLAGS = -Wall -O2 #-g #-O2 +LDFLAGS = +COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c +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 + +LIB=../libeo.a ../utils/libeoutils.a + +all: PyEO/PyEO.so + +clean: + rm PyEO/*.so *.o test/*.pyc + +PyEO/PyEO.so: $(OBJECTS) + $(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) diff --git a/deprecated/eo/src/pyeo/Makefile.rpm b/deprecated/eo/src/pyeo/Makefile.rpm new file mode 100644 index 000000000..4db4bccac --- /dev/null +++ b/deprecated/eo/src/pyeo/Makefile.rpm @@ -0,0 +1,29 @@ +# Makefile for people that build boost using the rpm-recipe + +CXX = g++ #-3.2 +CXXFLAGS = #-g #-DNDEBUG +CPPFLAGS = -Wall -O2 +LDFLAGS = -L/usr/lib/python2.2/config/ +COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c +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 \ + 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 + +all: PyEO.so + +clean: + rm *.so *.o test/*.pyc + +PyEO.so: $(OBJECTS) + $(LINK) -o PyEO.so $(OBJECTS) -lboost_python -lpython2.2 -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) diff --git a/deprecated/eo/src/pyeo/NEWS b/deprecated/eo/src/pyeo/NEWS new file mode 100644 index 000000000..e69de29bb diff --git a/deprecated/eo/src/pyeo/PyEO.cpp b/deprecated/eo/src/pyeo/PyEO.cpp new file mode 100644 index 000000000..7c3f1b93f --- /dev/null +++ b/deprecated/eo/src/pyeo/PyEO.cpp @@ -0,0 +1,231 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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" +#include + +using namespace std; +//using namespace boost::python; + +// static member, needs to be instantiated somewhere +std::vector PyFitness::objective_info; + +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 + } + // else aval < bval + dom = true; // for the moment: goto next objective + } + //else they're equal in this objective, goto next + } + + return dom; +} + +bool dominates(const PyEO& a, const PyEO& b) +{ + return PyFitness(a.fitness()).dominates(b.fitness()); +} + +ostream& operator<<(ostream& os, const PyEO& _eo) +{ + os << _eo.to_string(); + return os; +} + +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]) ); + + 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]) ); + } + } +}; + + +template +boost::python::str to_string(T& _p) +{ + std::ostringstream os; + _p.printOn(os); + return boost::python::str(os.str().c_str()); +} + +void pop_sort(eoPop& pop) { pop.sort(); } +void pop_shuffle(eoPop& pop) { pop.shuffle(); } + +void translate_index_error(index_error const& e) +{ + 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"); + + int i = x(); + + if (static_cast(i) >= pop.size()) + { + throw index_error("Index out of bounds"); + } + return pop[i]; +} + +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"); + + int i = x(); + + if (static_cast(i) >= pop.size()) + { + throw index_error("Index out of bounds"); + } + + pop[i] = value; +} + +void pop_push_back(eoPop& pop, PyEO& p) { pop.push_back(p); } +void pop_resize( eoPop& pop, unsigned i) { pop.resize(i); } +int pop_size( eoPop& pop) { return pop.size(); } + +extern void abstract1(); +extern void algos(); +extern void random_numbers(); +extern void geneticOps(); +extern void selectOne(); +extern void continuators(); +extern void reduce(); +extern void replacement(); +extern void selectors(); +extern void breeders(); +extern void mergers(); +extern void valueParam(); +extern void perf2worth(); +extern void monitors(); +extern void statistics(); + +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) + ; + + 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()) + ; + + + // Other definitions in different compilation units, + // this to avoid having g++ to choke on the load + random_numbers(); + valueParam(); + abstract1(); + geneticOps(); + selectOne(); + selectors(); + perf2worth(); + monitors(); + statistics(); + continuators(); + reduce(); + replacement(); + breeders(); + mergers(); + algos(); + + // 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); +} + + +// to avoid having to build with libeo.a +ostream & operator << ( ostream& _os, const eoPrintable& _o ) +{ + _o.printOn(_os); + return _os; +}; diff --git a/deprecated/eo/src/pyeo/PyEO.h b/deprecated/eo/src/pyeo/PyEO.h new file mode 100644 index 000000000..188b7f8da --- /dev/null +++ b/deprecated/eo/src/pyeo/PyEO.h @@ -0,0 +1,156 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifndef PYEO_H +#define PYEO_H + +#include +#include +#include +#include + +#include + +struct index_error : public std::exception +{ + index_error(std::string w) : what(w) {}; + virtual ~index_error() throw() {} + std::string what; +}; + +class PyFitness : public boost::python::object +{ +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"); + } + + 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; + } + } + + 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; + } + + bool operator<(const PyEO& other) const { return EO::operator<(other); } + bool operator>(const PyEO& other) const { return EO::operator>(other); } + +}; + +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) + { + return boost::python::make_tuple(_eo.getFitness(), _eo.genome); + } + + static void setstate(PyEO& _eo, boost::python::tuple pickled) + { + _eo.setFitness( Fitness(pickled[0]) ); + _eo.genome = pickled[1]; + } +}; + +#endif diff --git a/deprecated/eo/src/pyeo/PyEO/__init__.py b/deprecated/eo/src/pyeo/PyEO/__init__.py new file mode 100644 index 000000000..2818319b6 --- /dev/null +++ b/deprecated/eo/src/pyeo/PyEO/__init__.py @@ -0,0 +1,83 @@ +from PyEO import * + +try: + import Gnuplot +except ImportError: + print "Python support for Gnuplot not found" +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) + + while len(self.values) <= i: + self.values.append( [] ) + + 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') + + 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; + + def __call__(self): + pass + +class eoStat(eoStatBase, eoValueParam): + def __init__(self): + eoStatBase.__init__(self) + eoValueParam.__init__(self) + +class eoSortedStat(eoSortedStatBase, eoValueParam): + def __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 /= len(pop) + self.object = sum + +class eoBestFitnessStat(eoSortedStat): + def __call__(self, pop): + self.object = pop[0].fitness diff --git a/deprecated/eo/src/pyeo/README b/deprecated/eo/src/pyeo/README new file mode 100644 index 000000000..072fe3ad2 --- /dev/null +++ b/deprecated/eo/src/pyeo/README @@ -0,0 +1,4 @@ + +See BUILDING for details on how to build this thing + + diff --git a/deprecated/eo/src/pyeo/abstract1.cpp b/deprecated/eo/src/pyeo/abstract1.cpp new file mode 100644 index 000000000..43c0dadb9 --- /dev/null +++ b/deprecated/eo/src/pyeo/abstract1.cpp @@ -0,0 +1,52 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +using namespace boost::python; + +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()); + + def_abstract_functor >("eoPopEvalFunc"); +} diff --git a/deprecated/eo/src/pyeo/algos.cpp b/deprecated/eo/src/pyeo/algos.cpp new file mode 100644 index 000000000..caa2fcd33 --- /dev/null +++ b/deprecated/eo/src/pyeo/algos.cpp @@ -0,0 +1,126 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +using namespace boost::python; + +void algos() +{ + def_abstract_functor >("eoAlgo"); + + /* Algorithms */ + 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&>()) + ; + */ +} diff --git a/deprecated/eo/src/pyeo/breeders.cpp b/deprecated/eo/src/pyeo/breeders.cpp new file mode 100644 index 000000000..c66b6bccd --- /dev/null +++ b/deprecated/eo/src/pyeo/breeders.cpp @@ -0,0 +1,59 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +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()) + +void breeders() +{ + def_abstract_functor >("eoBreed"); + + DEF3(eoSelectTransform, eoSelect&, eoTransform&); + + DEF3(eoGeneralBreeder, eoSelectOne&, eoGenOp&) + .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] ); +} diff --git a/deprecated/eo/src/pyeo/continuators.cpp b/deprecated/eo/src/pyeo/continuators.cpp new file mode 100644 index 000000000..d31613d2c --- /dev/null +++ b/deprecated/eo/src/pyeo/continuators.cpp @@ -0,0 +1,96 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include +#include +#include +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +using namespace boost::python; + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoContinue::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoContinue::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoContinue::operator()) + +void add_checkpoint(); + +void continuators() +{ + /* Counters, wrappers etc */ + + 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()) + ; + + DEF2(eoFitContinue, object); // object is the fitness type + + DEF3(eoSteadyFitContinue, unsigned long, unsigned long); + + add_checkpoint(); +} + +void addContinue(eoCheckPoint& c, eoContinue& cc) { c.add(cc); } +void addMonitor(eoCheckPoint& c, eoMonitor& m) { c.add(m);} +void addStat(eoCheckPoint& c, eoStatBase& s) { c.add(s);} +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()) + ; +} diff --git a/deprecated/eo/src/pyeo/def_abstract_functor.h b/deprecated/eo/src/pyeo/def_abstract_functor.h new file mode 100644 index 000000000..4c3101dfd --- /dev/null +++ b/deprecated/eo/src/pyeo/def_abstract_functor.h @@ -0,0 +1,139 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifndef MAKE_ABSTRACT_FUNCTOR_H +#define MAKE_ABSTRACT_FUNCTOR_H + +#include + +// 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) {} + + typename Proc::result_type operator()(void) + { + 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) {} + + 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 + +template +void def_abstract_functor(std::string name) +{ + eoutils::make_abstract_functor(name, Functor::functor_category()); +} + +template +void def_abstract_functor_ref(std::string name) +{ + eoutils::make_abstract_functor_ref(name, Functor::functor_category()); +} + +#endif diff --git a/deprecated/eo/src/pyeo/geneticOps.cpp b/deprecated/eo/src/pyeo/geneticOps.cpp new file mode 100644 index 000000000..40617680e --- /dev/null +++ b/deprecated/eo/src/pyeo/geneticOps.cpp @@ -0,0 +1,158 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +using namespace boost::python; + +class GenOpWrapper : public eoGenOp +{ +public: + + PyObject* self; + GenOpWrapper(PyObject* p) : self(p) {} + unsigned max_production(void) + { + return call_method(self,"max_production"); + } + std::string className() const + { + return "GenOpDerivative"; // never saw the use of className anyway + } + + void apply(eoPopulator& populator ) + { + boost::python::call_method(self,"apply", boost::ref( populator ) ); + } +}; + +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"); + } + + const PyEO& select() + { + return call_method(self,"select"); + } +}; + +class MonOpWrapper : public eoMonOp +{ +public: + PyObject* self; + MonOpWrapper(PyObject* p) : self(p) {} + bool operator()(PyEO& _eo) + { return boost::python::call_method(self, "__call__", boost::ref( _eo )); } +}; +class BinOpWrapper : public eoBinOp +{ +public: + PyObject* self; + BinOpWrapper(PyObject* p) : self(p) {} + bool operator()(PyEO& _eo, const PyEO& _eo2) + { return boost::python::call_method(self, "__call__", boost::ref( _eo ), boost::ref(_eo2)); } +}; +class QuadOpWrapper : public eoQuadOp +{ +public: + PyObject* self; + QuadOpWrapper(PyObject* p) : self(p) {} + bool operator()(PyEO& _eo, PyEO& _eo2) + { return boost::python::call_method(self, "__call__", boost::ref( _eo ), boost::ref(_eo2)); } +}; + +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) + ; + + class_, bases > > + ("eoSeqPopulator", init&, eoPop&>() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; + + class_, bases > > + ("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) + ; + + class_ >("eoOp", init::OpType>()) + .def("getType", &eoOp::getType); + + class_, MonOpWrapper, bases >, boost::noncopyable>("eoMonOp", init<>()) + .def("__call__", &MonOpWrapper::operator(), "an example docstring"); + class_, BinOpWrapper, bases >, boost::noncopyable>("eoBinOp", init<>()) + .def("__call__", &BinOpWrapper::operator()); + class_, QuadOpWrapper, bases >, boost::noncopyable>("eoQuadOp", init<>()) + .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()) + ; + + class_, bases >, boost::noncopyable>("eoSequentialOp", init<>()) + .def("add", &eoSequentialOp::add, WC1) + .def("apply", &eoSequentialOp::apply) + ; + + class_, bases >, boost::noncopyable>("eoProportionalOp", init<>()) + .def("add", &eoProportionalOp::add, WC1) + .def("apply", &eoProportionalOp::apply) + ; + + /* Cloning */ + class_, bases > >("eoMonCloneOp").def("__call__", &eoMonCloneOp::operator()); + class_, bases > >("eoBinCloneOp").def("__call__", &eoBinCloneOp::operator()); + class_, bases > >("eoQuadCloneOp").def("__call__", &eoQuadCloneOp::operator()); + +} diff --git a/deprecated/eo/src/pyeo/mergers.cpp b/deprecated/eo/src/pyeo/mergers.cpp new file mode 100644 index 000000000..f41af0490 --- /dev/null +++ b/deprecated/eo/src/pyeo/mergers.cpp @@ -0,0 +1,40 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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" +#include "def_abstract_functor.h" + +using namespace boost::python; + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoMerge::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoMerge::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init() ).def("__call__", &eoMerge::operator()) + +void mergers() +{ + def_abstract_functor >("eoMerge"); + + DEF2(eoElitism, double) + .def( init() ); + DEF(eoNoElitism); + DEF(eoPlus); + +} diff --git a/deprecated/eo/src/pyeo/monitors.cpp b/deprecated/eo/src/pyeo/monitors.cpp new file mode 100644 index 000000000..02d011d89 --- /dev/null +++ b/deprecated/eo/src/pyeo/monitors.cpp @@ -0,0 +1,71 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include "PyEO.h" + +using namespace boost::python; + +class MonitorWrapper : public eoMonitor +{ +public: + PyObject* self; + list objects; + + MonitorWrapper(PyObject* p) :self(p) {} + + eoMonitor& operator()() + { + call_method(self, "__call__"); + return *this; + } + + 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 + * 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) + ; +} diff --git a/deprecated/eo/src/pyeo/perf2worth.cpp b/deprecated/eo/src/pyeo/perf2worth.cpp new file mode 100644 index 000000000..a257b0cd9 --- /dev/null +++ b/deprecated/eo/src/pyeo/perf2worth.cpp @@ -0,0 +1,89 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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" + +using namespace boost::python; + +struct Perf2WorthWrapper : public eoPerf2Worth +{ + PyObject* self; + Perf2WorthWrapper(PyObject* p) : self(p) {} + + void operator()( const eoPop& 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]); + + return numeric::array(result); +} + +struct CachedPerf2WorthWrapper : public eoPerf2WorthCached +{ + PyObject* self; + CachedPerf2WorthWrapper(PyObject* p) : self(p) {} + + void calculate_worths(const eoPop& pop) + { + call_method(self, "calculate_worths", boost::ref(pop)); + } +}; + +void perf2worth() +{ + //numeric::array::set_module_and_type("Numeric", "ArrayType"); + + 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); +} diff --git a/deprecated/eo/src/pyeo/pickle.h b/deprecated/eo/src/pyeo/pickle.h new file mode 100644 index 000000000..0e30654a9 --- /dev/null +++ b/deprecated/eo/src/pyeo/pickle.h @@ -0,0 +1,70 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#ifndef PICKLE_H +#define PICKLE_h + +// #ifndef WIN32 +// #include +// #endif + +#include +#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(); + } + + static + boost::python::tuple getstate(const T& t) + { + 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); + } +}; + +/** Defines persistency through pickle support by using std::strings + * so while we're at it, we will .def("__str__") as well + */ +template +boost::python::class_& pickle(boost::python::class_& c) +{ + return c.def_pickle(T_pickle_suite()) + .def("__str__", T_pickle_suite::print_to_string); +} + +#endif diff --git a/deprecated/eo/src/pyeo/random_numbers.cpp b/deprecated/eo/src/pyeo/random_numbers.cpp new file mode 100644 index 000000000..c9047385d --- /dev/null +++ b/deprecated/eo/src/pyeo/random_numbers.cpp @@ -0,0 +1,112 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 + +using namespace boost::python; + +#include +#include + +using namespace boost::python; + +// initialize static constants +const uint32_t eoRng::K(0x9908B0DFU); +const int eoRng::M(397); +const int eoRng::N(624); + +namespace eo +{ + eoRng rng(time(0)); +} + +eoRng& get_rng() { return rng; } +double normal(eoRng& rng) { return rng.normal(); } + +std::string rng_to_string(const eoRng& _rng) +{ + std::ostringstream os; + _rng.printOn(os); + os << std::ends; + return os.str(); +} + + +void rng_from_string(eoRng& _rng, std::string s) +{ + std::istringstream is(s); + _rng.readFrom(is); +} + +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))); + } + static + void setstate(eoRng& _rng, boost::python::tuple pickled) + { + 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? + } + } + + double chance = _rng.uniform() * total; + + int i = 0; + while (chance >= 0.0) + chance -= extract(values[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("rng", get_rng, return_value_policy()); +} diff --git a/deprecated/eo/src/pyeo/reduce.cpp b/deprecated/eo/src/pyeo/reduce.cpp new file mode 100644 index 000000000..6c9b78c64 --- /dev/null +++ b/deprecated/eo/src/pyeo/reduce.cpp @@ -0,0 +1,63 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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" + +using namespace boost::python; + +// unfortunately have to define it specially +class eoReduceWrapper : public eoReduce +{ +public: + PyObject* self; + eoReduceWrapper(PyObject* s) : self(s) {} + void operator()(eoPop& pop, unsigned i) + { + boost::python::call_method(self, "__call__", pop, i ); + } +}; + +void reduce() +{ + // ref trick in def_abstract_functor does not work for unsigned int :-( + class_, eoReduceWrapper, boost::noncopyable>("eoReduce", init<>()) + .def("__call__", &eoReduceWrapper::operator()); + + class_, bases > >("eoTruncate", init<>() ) + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoRandomReduce") + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoEPReduce", init()) + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoLinearTruncate") + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoDetTournamentTruncate", init()) + .def("__call__", &eoReduce::operator()) + ; + class_, bases > >("eoStochTournamentTruncate", init()) + .def("__call__", &eoReduce::operator()) + ; +} diff --git a/deprecated/eo/src/pyeo/replacement.cpp b/deprecated/eo/src/pyeo/replacement.cpp new file mode 100644 index 000000000..eb1bc5d70 --- /dev/null +++ b/deprecated/eo/src/pyeo/replacement.cpp @@ -0,0 +1,72 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +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]) \ + .def("__call__", &eoReplacement::operator()) + +void replacement() +{ + def_abstract_functor >("eoReplacement"); + + // eoReplacement.h + DEF(eoGenerationalReplacement); + + class_, bases > > + ("eoWeakElitistReplacement", + init< eoReplacement& >()[WC1]); + + // eoMergeReduce.h + DEF3(eoMergeReduce, eoMerge&, eoReduce& ); + DEF(eoPlusReplacement); + DEF(eoCommaReplacement); + DEF2(eoEPReplacement, unsigned); + + // eoReduceMerge.h + DEF3(eoReduceMerge, eoReduce&, eoMerge& ); + DEF(eoSSGAWorseReplacement); + DEF2(eoSSGADetTournamentReplacement, unsigned); + DEF2(eoSSGAStochTournamentReplacement, double); + + // eoReduceMergeReduce.h + //class_, bases > >("eoReplacement", + // init&, + // eoHowMany, eoReduce&, eoReduce&>()) + // .def("__call__", &eoReplacement::operator()); + + //eoMGGReplacement + DEF(eoMGGReplacement) + .def( init() ) + .def( init() ); +} diff --git a/deprecated/eo/src/pyeo/selectOne.cpp b/deprecated/eo/src/pyeo/selectOne.cpp new file mode 100644 index 000000000..5a28fcff3 --- /dev/null +++ b/deprecated/eo/src/pyeo/selectOne.cpp @@ -0,0 +1,108 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include +#include +#include + +#include "PyEO.h" +#include "pickle.h" +#include "def_abstract_functor.h" + +using namespace boost::python; + +class eoSelectOneWrapper : public eoSelectOne +{ +public: + PyObject* self; + eoSelectOneWrapper(PyObject* p) : self(p) {} + const PyEO& operator()(const eoPop& pop) + { + return boost::python::call_method< const PyEO& >(self, "__call__", boost::ref(pop)); + } +}; + +template +void add_select(std::string name) +{ + class_ > >(name.c_str(), init<>() ) + .def("__call__", &Select::operator(), return_internal_reference<>() ) + ; +} + +template +void add_select(std::string name, Init init) +{ + class_ > >(name.c_str(), init) + .def("__call__", &Select::operator(), return_internal_reference<>() ) + ; +} + +template +void add_select(std::string name, Init1 init1, Init2 init2) +{ + class_ > >(name.c_str(), init1) + .def( init2 ) + .def("__call__", &Select::operator(), return_internal_reference<>() ) + .def("setup", &Select::setup); +} + +void selectOne() +{ + /* Concrete classes */ + + pickle(class_("eoHowMany", init<>()) + .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] + ); + + // 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/deprecated/eo/src/pyeo/selectors.cpp b/deprecated/eo/src/pyeo/selectors.cpp new file mode 100644 index 000000000..7c8f4096a --- /dev/null +++ b/deprecated/eo/src/pyeo/selectors.cpp @@ -0,0 +1,60 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 +#include +#include +#include +#include +#include + +#include "PyEO.h" +#include "def_abstract_functor.h" + +using namespace boost::python; + +#define DEF(x) class_, bases > >(#x).def("__call__", &eoSelect::operator()) +#define DEF2(x, i1) class_, bases > >(#x, init()[WC1] ).def("__call__", &eoSelect::operator()) +#define DEF3(x, i1, i2) class_, bases > >(#x, init()[WC1] ).def("__call__", &eoSelect::operator()) + +void selectors() +{ + def_abstract_functor >("eoSelect"); + + DEF(eoDetSelect).def( init() ).def( init() ); + DEF3(eoSelectMany, eoSelectOne&, double) + .def( init< eoSelectOne&, double, bool>()[WC1] ) + .def( init< eoSelectOne&, eoHowMany>()[WC1] ); + + DEF2(eoSelectNumber, eoSelectOne&) + .def( init< eoSelectOne&, unsigned>()[WC1]); + + DEF2(eoSelectPerc, eoSelectOne&) + .def( init&, float>()[WC1] ); + + DEF3(eoTruncSelect, eoSelectOne&, eoHowMany); + + class_, bases > >("eoTruncatedSelectMany", + 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/deprecated/eo/src/pyeo/statistics.cpp b/deprecated/eo/src/pyeo/statistics.cpp new file mode 100644 index 000000000..fbad92694 --- /dev/null +++ b/deprecated/eo/src/pyeo/statistics.cpp @@ -0,0 +1,61 @@ +#include + +#include "PyEO.h" +#include "valueParam.h" + +using namespace boost::python; + +class StatBaseWrapper : public eoStatBase +{ +public: + PyObject* self; + StatBaseWrapper(PyObject* p) : self(p) {} + + void operator()(const eoPop& pop) + { + call_method(self, "__call__", boost::ref(pop)); + } +}; + +class SortedStatBaseWrapper : public eoSortedStatBase +{ +public: + PyObject* self; + SortedStatBaseWrapper(PyObject* p) : self(p) {} + + void operator()(const std::vector& pop) + { + call_method(self, "__call__", boost::ref(pop)); + } +}; + +typedef std::vector eoPopView; + +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]; +} + +void statistics() +{ + class_, StatBaseWrapper, boost::noncopyable> + ("eoStatBase", init<>()) + .def("lastCall", &eoStatBase::lastCall) + .def("__call__", &StatBaseWrapper::operator()) + ; + + class_< eoPopView >("eoPopView") + .def("__getitem__", popview_getitem, return_internal_reference<>() ) + .def("__len__", &eoPopView::size) + ; + + class_, SortedStatBaseWrapper, boost::noncopyable> + ("eoSortedStatBase", init<>()) + .def("lastCall", &eoSortedStatBase::lastCall) + .def("__call__", &SortedStatBaseWrapper::operator()) + ; +} diff --git a/deprecated/eo/src/pyeo/test/maxone.py b/deprecated/eo/src/pyeo/test/maxone.py new file mode 100644 index 000000000..0c4bbd012 --- /dev/null +++ b/deprecated/eo/src/pyeo/test/maxone.py @@ -0,0 +1,88 @@ +import sys +sys.path.append('..') + +print 'importing pyeo' +from libPyEO import * +print 'done' + +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) + +class EvalFunc(eoEvalFunc): + def __call__(self, eo): + 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) + +class Init(eoInit): + def __init__(self, genome_length = 10): + eoInit.__init__(self) + self.length = genome_length + def __call__(self, eo): + eo.genome = [rng().flip(0.5) for x in range(self.length)] + +class Mutate(eoMonOp): + def __call__(self, eo): + 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 + +class Crossover(eoQuadOp): + def __call__(self, eo1, eo2): + eo1.genome = copy(eo1.genome); + eo2.genome = copy(eo2.genome); + + point = rng().random( len(eo1.genome) ); + + eo1.genome[:point] = eo2.genome[:point]; + eo2.genome[point:] = eo1.genome[point:]; + + return 1 + +evaluate = EvalFunc() +init = Init(3) +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 + + print + print + print + + pop = eoPop(1, init) + + pop[0] = eo; + + mutate(pop[0]) + pop[0].invalidate() + evaluate(pop[0]) + + print pop[0], eo diff --git a/deprecated/eo/src/pyeo/test/run_tests.sh b/deprecated/eo/src/pyeo/test/run_tests.sh new file mode 100755 index 000000000..8a2ebca13 --- /dev/null +++ b/deprecated/eo/src/pyeo/test/run_tests.sh @@ -0,0 +1,7 @@ +#!/bin/sh + +for i in *.py +do + python2 $i > /dev/null + +done diff --git a/deprecated/eo/src/pyeo/test/test_breeders.py b/deprecated/eo/src/pyeo/test/test_breeders.py new file mode 100644 index 000000000..c23d47873 --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_breeders.py @@ -0,0 +1,30 @@ +from maxone import * +import unittest + +class TestBreeders(unittest.TestCase): + def runtest(self, breed): + pop = eoPop(50, Init(20)) + evaluate = EvalFunc() + 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() + + def testGeneralBreeder(self): + seq = eoSequentialOp(); + seq.add(Crossover(), 0.7) + seq.add(Mutate(), 0.1) + + breed = eoGeneralBreeder(eoDetTournamentSelect(3), seq) + self.runtest(breed) + +def suite(): + return unittest.makeSuite(TestSGA,'test') + +if __name__=='__main__': + unittest.main() diff --git a/deprecated/eo/src/pyeo/test/test_mo.py b/deprecated/eo/src/pyeo/test/test_mo.py new file mode 100644 index 000000000..5a7a79a41 --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_mo.py @@ -0,0 +1,166 @@ +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 + 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 + +g = Gnuplot.Gnuplot() +g.reset() + +def do_plot(pop): + l1 = [] + l2 = [] + + for indy in pop: + l1.append(indy.fitness[0]) + 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() + populator = eoSelectivePopulator(pop, newpop, self.selectOne); + + while len(newpop) < sz: + self.seq(populator) + + 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 + 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); + setObjectivesValue(1,1); + + eo1 = EO(); + eo2 = EO(); + + eo1.fitness = [0,1]; + eo2.fitness = [1,1]; + + self.failUnlessEqual(dominates(eo1, eo2), 0) + self.failUnlessEqual(dominates(eo2, eo1), 1) + self.failUnlessEqual(dominates(eo2, eo2), 0) + + setObjectivesValue(0,-1) + setObjectivesValue(1,-1); + + 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) + + pop[5].fitness = [0.15,0.87] + pop[4].fitness = [0.1,0.9] + pop[3].fitness = [0,1]; + pop[2].fitness = [1,0]; + pop[1].fitness = [1,1]; + pop[0].fitness = [2,1]; + + srt = eoNDSorting_II() + + srt(pop) + srt.sort_pop(pop) + + 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/deprecated/eo/src/pyeo/test/test_pickling.py b/deprecated/eo/src/pyeo/test/test_pickling.py new file mode 100644 index 000000000..81b3b9f5f --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_pickling.py @@ -0,0 +1,91 @@ +from maxone import * +import unittest +import cPickle +import tempfile +import os + +class TestPickling(unittest.TestCase): + def do_pickle(self, object): + filename = tempfile.mktemp() + file = open(filename, 'wb') + pickler = cPickle.Pickler(file) + + pickler.dump(object); + del pickler + file.close() + + file = open(filename) + + unpickler = cPickle.Unpickler(file) + + object2 = unpickler.load() + + del unpickler + file.close() + os.remove(filename) + + 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 + + eo2 = self.do_pickle(eo) + + self.failUnlessEqual( str(eo), str(eo2) ) + + def testPop(self): + pop = eoPop(40, init) + 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) + + self.failUnlessEqual(howmany(10), howmany2(10)) + 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(eoValueParamFloat(4.2,'float')) + + v = eoValueParamVec() + v.value = Numeric.arange(10) + self.vParam(v) + + v = eoValueParamPair() + v.value = (0.3,0.5) + self.vParam(v) + +if __name__=='__main__': + unittest.main() diff --git a/deprecated/eo/src/pyeo/test/test_populator.py b/deprecated/eo/src/pyeo/test/test_populator.py new file mode 100644 index 000000000..12335956a --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_populator.py @@ -0,0 +1,82 @@ +print 'importing maxone' +from maxone import * +print 'done' +import unittest + +class Mut(Mutate): + def __init__(self): + Mutate.__init__(self) + self.cnt = 0; + def __call__(self, eo): + self.cnt += 1; + return Mutate.__call__(self, eo) + +class Xover(Crossover): + def __init__(self): + Crossover.__init__(self) + self.cnt = 0; + def __call__(self, eo1, eo2): + self.cnt += 1; + 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() + + seq.add(mutate, 0.4) + seq.add(xover, 0.8) + + 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 + self.runOpContainer(eoSequentialOp) + + def test_proportionalOp(self): + print '*'*20, "ProportionalOp", '*'*20 + self.runOpContainer(eoProportionalOp) + +if __name__=='__main__': + unittest.main() diff --git a/deprecated/eo/src/pyeo/test/test_reduce.py b/deprecated/eo/src/pyeo/test/test_reduce.py new file mode 100644 index 000000000..3e279168a --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_reduce.py @@ -0,0 +1,32 @@ +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: + red = ReduceClass() + + red(pop, 5); + + self.failUnlessEqual( len(pop), 5) + + def test_eoTruncate(self): + self.run_test(eoTruncate) + def test_eoRandomeReduce(self): + self.run_test(eoRandomReduce) + def test_eoEPRReduce(self): + self.run_test(eoEPReduce, 2) + def test_eoLinearTruncate(self): + self.run_test(eoLinearTruncate) + def test_eoDetTournamentTruncate(self): + self.run_test(eoDetTournamentTruncate, 2) + def test_eoStochTournamentTruncate(self): + self.run_test(eoStochTournamentTruncate, 0.9) + +if __name__=='__main__': + unittest.main() diff --git a/deprecated/eo/src/pyeo/test/test_selectone.py b/deprecated/eo/src/pyeo/test/test_selectone.py new file mode 100644 index 000000000..f71913b98 --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_selectone.py @@ -0,0 +1,62 @@ +from maxone import * +import unittest + +class Init(eoInit): + def __call__(self, eo): + pass + +class TestSGA(unittest.TestCase): + def __init__(self, a): + unittest.TestCase.__init__(self, a) + self.pop = eoPop(4, Init()) + + 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))] + + 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) + + def test_eoRandomSelect(self): + selectOne = eoRandomSelect() + self.do_test(selectOne) + + def test_eoBestSelect(self): + selectOne = eoBestSelect() + (sel, nTries) = self.do_test(selectOne) + + self.failUnlessEqual(sel[0], 0); + self.failUnlessEqual(sel[-1], nTries); + + def test_eoNoSelect(self): + selectOne = eoNoSelect() + self.do_test(selectOne) + + def test_eoStochTournament(self): + selectOne = eoStochTournamentSelect(0.75) + self.do_test(selectOne) + + def test_eoSequentialSelect(self): + selectOne = eoSequentialSelect(); + self.do_test(selectOne) + + def test_eoEliteSequentialSelect(self): + selectOne = eoEliteSequentialSelect(); + self.do_test(selectOne) + +if __name__=='__main__': + unittest.main() diff --git a/deprecated/eo/src/pyeo/test/test_sga.py b/deprecated/eo/src/pyeo/test/test_sga.py new file mode 100644 index 000000000..5f6d1c22a --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_sga.py @@ -0,0 +1,45 @@ +from maxone import * +import unittest + +class TestSGA(unittest.TestCase): + def dotestSGA(self, evaluate): + init = Init(20) + mutate = Mutate() + xover = Crossover() + + 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); + + sga(pop) + + print pop.best() + + def testSGA_Max(self): + evaluate = EvalFunc() + self.dotestSGA(evaluate) + + def testSGA_Min(self): + evaluate = MinEvalFunc() + self.dotestSGA(evaluate) + +if __name__=='__main__': + unittest.main() diff --git a/deprecated/eo/src/pyeo/test/test_transform.py b/deprecated/eo/src/pyeo/test/test_transform.py new file mode 100644 index 000000000..7359342e5 --- /dev/null +++ b/deprecated/eo/src/pyeo/test/test_transform.py @@ -0,0 +1,62 @@ +"""Test script for the eoSGATranform class""" + +from copy import deepcopy +from libPyEO import * +from maxone import * + +pop = eoPop() + +for i in range(10): + 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 + + transform(pop) + + print "GM pop:" + print pop + +def test2(pop, transform): + pop = deepcopy(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) + + 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: + test2(pop, transform) + except: + import sys + print + print "Caught an exception:" + print sys.exc_type, sys.exc_value + print diff --git a/deprecated/eo/src/pyeo/valueParam.cpp b/deprecated/eo/src/pyeo/valueParam.cpp new file mode 100644 index 000000000..59ed1a472 --- /dev/null +++ b/deprecated/eo/src/pyeo/valueParam.cpp @@ -0,0 +1,191 @@ +/* + PyEO + + Copyright (C) 2003 Maarten Keijzer + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + 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 + +// Here's 'len'. Why? dunno +#include "valueParam.h" +#include + +using namespace boost::python; + +class ParamWrapper : public eoParam +{ +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 getValue() const + { + return call_method(self, "getValueAsString"); + } + + void setValue(const std::string& s) + { + call_method(self, "setValueAsString", s); + } +}; + +template +struct ValueParam_pickle_suite : boost::python::pickle_suite +{ + static + boost::python::tuple getstate(const eoValueParam& _param) + { + str v(_param.getValue()); + str d(_param.description()); + str def(_param.defValue()); + str l(_param.longName()); + object s(_param.shortName()); + object r(_param.required()); + return make_tuple(v,d,def,l,s,r); + } + static + void setstate(eoValueParam& _param, boost::python::tuple pickled) + { + std::string v = extract(pickled[0]); + std::string d = extract(pickled[1]); + std::string def = extract(pickled[2]); + std::string l = extract(pickled[3]); + char s = extract(pickled[4]); + bool r = extract(pickled[5]); + + _param = eoValueParam(T(), l, d, s, r); + _param.defValue(d); + _param.setValue(v); + } +}; + +template +U getv(const eoValueParam& v) { return v.value(); } + +template +void setv(eoValueParam& v, U val) { v.value() = val; } + +template <> +numeric::array getv< std::vector, numeric::array > +(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) +{ + 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(); + } +} + +template <> +tuple getv, tuple > + (const eoValueParam< std::pair >& p) +{ + return make_tuple(p.value().first, p.value().second); +} + +template <> +void setv< std::pair, tuple > +(eoValueParam< std::pair >& p, tuple val) +{ + extract first(val[0]); + extract second(val[1]); + + if (!first.check()) + throw std::runtime_error("doubles expected"); + if (!second.check()) + throw std::runtime_error("doubles expected"); + + p.value().first = first(); + p.value().second = second(); +} + +template +void define_valueParam(std::string prefix) +{ + std::string name = "eoValueParam"; + name += prefix; + + class_, bases >(name.c_str(), init<>()) + .def(init()) + .def(init()) + .def(init()) + .def(init()) + .def("getValueAsString", &eoValueParam::getValue) + .def("__str__", &eoValueParam::getValue) + .def("setValueAsString", &eoValueParam::setValue) + .def("getValue", getv) + .def("setValue", setv) + .add_property("value", getv, setv) + .def_pickle(ValueParam_pickle_suite()) + ; +} + +void valueParam() +{ + class_("eoParam", init<>()) + .def(init< std::string, std::string, std::string, char, bool>()) + .def("getValueAsString", &ParamWrapper::getValue) + .def("setValueAsString", &ParamWrapper::setValue) + .def("longName", &eoParam::longName, return_value_policy()) + //.def("defValue", &eoParam::defValue, return_value_policy()) + .def("description", &eoParam::description, return_value_policy()) + .def("shortName", &eoParam::shortName) + .def("required", &eoParam::required) + ; + + define_valueParam("Int"); + define_valueParam("Float"); + define_valueParam, numeric::array >("Vec"); + define_valueParam< std::pair, tuple >("Pair"); + //define_valueParam< object, object >("Py"); + + class_ >("eoValueParam", init<>()) + //.def(init()) + //.def(init()) + //.def(init()) + .def(init()) + .def("getValueAsString", &ValueParam::getValue) + .def("__str__", &ValueParam::getValue) + .def("setValueAsString", &ValueParam::setValue) + .add_property("object", &ValueParam::getObj, &ValueParam::setObj) + ; +} diff --git a/deprecated/eo/src/pyeo/valueParam.h b/deprecated/eo/src/pyeo/valueParam.h new file mode 100644 index 000000000..940a43518 --- /dev/null +++ b/deprecated/eo/src/pyeo/valueParam.h @@ -0,0 +1,41 @@ +#ifndef VALUEPARAM_H +#define VALUEPARAM_H + +#include +#include + +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()); + } + + std::string getValue() const + { + boost::python::str s = boost::python::str(obj); + return std::string(boost::python::extract(s)); + } + + void setValue(const std::string& v) + { + std::cerr << "not implemented yet" << std::endl; + } + + boost::python::object getObj() const { return obj;} + void setObj(boost::python::object o) { obj = o; } +}; + +#endif diff --git a/deprecated/eo/src/utils/CMakeLists.txt b/deprecated/eo/src/utils/CMakeLists.txt new file mode 100644 index 000000000..ccb7efe81 --- /dev/null +++ b/deprecated/eo/src/utils/CMakeLists.txt @@ -0,0 +1,46 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the ga target +###################################################################################### + +SET(EOUTILS_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) +SET(LIBRARY_OUTPUT_PATH ${EOUTILS_LIB_OUTPUT_PATH}) + +SET(EOUTILS_SOURCES + eoData.cpp + eoFileMonitor.cpp + eoGnuplot.cpp + eoGnuplot1DMonitor.cpp + eoGnuplot1DSnapshot.cpp + eoIntBounds.cpp + eoParser.cpp + eoRealBounds.cpp + eoRNG.cpp + eoState.cpp + eoOStreamMonitor.cpp + eoUpdater.cpp + make_help.cpp + pipecom.cpp + eoLogger.cpp + eoParallel.cpp + eoSignal.cpp + ) + +ADD_LIBRARY(eoutils STATIC ${EOUTILS_SOURCES}) +INSTALL(TARGETS eoutils ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + + +###################################################################################### +### 3) Optionnal +###################################################################################### + +SET(EOUTILS_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(eoutils PROPERTIES VERSION "${EOUTILS_VERSION}") + +###################################################################################### diff --git a/deprecated/eo/src/utils/ChangeLog b/deprecated/eo/src/utils/ChangeLog new file mode 100644 index 000000000..dac74c49c --- /dev/null +++ b/deprecated/eo/src/utils/ChangeLog @@ -0,0 +1,42 @@ +2007-08-22 Jochen Kpper + + * eoRNG.h (eoRng::random): Add comment on truncation as standard way of + floating point to integer conversion. + +2006-12-04 Jochen Kpper + + * eoRNG.h (eoRng::normal(stdev)): Revert erroneous change. + +2006-12-02 Jochen Kpper + + * eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned. + + * eoRNG.h: Cleanup docs and document /all/ members. + + * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. + +2006-12-01 Jochen Kpper + + * eoRNG.cpp: Use C++ style cast. + + * Makefile.am: Add missing header for distribution. + +2006-11-30 Jochen Kpper + + * eoRNG.h: Generally include + +2006-11-16 Jochen Kpper + + * 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. + + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/deprecated/eo/src/utils/checkpointing b/deprecated/eo/src/utils/checkpointing new file mode 100644 index 000000000..f7fd0e55b --- /dev/null +++ b/deprecated/eo/src/utils/checkpointing @@ -0,0 +1,56 @@ +/* + ----------------------------------------------------------------------------- + checkpointing + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef _CHECKPOINTING_ +#define _CHECKPOINTING_ + +#include +#include +#include +#include +#include +#include +#include +#ifndef _MSC_VER +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// and make_help - any better suggestion to include it? +void make_help(eoParser & _parser); + +#endif // !_CHECKPOINTING_ + +// Local Variables: +// mode: C++ +// End: diff --git a/deprecated/eo/src/utils/compatibility.h b/deprecated/eo/src/utils/compatibility.h new file mode 100644 index 000000000..937ab8a03 --- /dev/null +++ b/deprecated/eo/src/utils/compatibility.h @@ -0,0 +1,82 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + compatibility.h + File to store some compiler specific stuff in. Currently handles, or + least tries to handle the min() max() problems when using MSVC + + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef COMPAT_H +#define COMPAT_H + +#include +#include + +#ifdef __GNUC__ +#if __GNUC__ < 3 + // check for stdlibc++v3 which does have ios_base + #ifndef _CPP_BITS_IOSBASE_H + typedef ios ios_base; // not currently defined in GCC + #endif +#endif +#endif + +#if defined(_MSC_VER) && (_MSC_VER < 1300) +/* +Maarten: added this code here because Mirkosoft has the +nasty habit of #define min and max in stdlib.h (and windows.h) +I'm trying to undo this horrible macro magic (microsoft yet macrohard) +here. Sure hope it works +Olivier: this has been removed in .NET :) One step more standard... +*/ +#pragma warning(disable:4786) + +#include + +#ifdef min +#undef min +#undef max // as they come in std::pairs +#endif + +// add min and max to std... +namespace std +{ + template const T& min(const T& a, const T& b) + { + if(a < b) + return a; + // else + return b; + } + + template const T& max(const T& a, const T& b) + { + if(a > b) + return a; + // else + return b; + } +} + +#endif + // _MSC_VER +#endif diff --git a/deprecated/eo/src/utils/eoAssembledFitnessStat.h b/deprecated/eo/src/utils/eoAssembledFitnessStat.h new file mode 100644 index 000000000..44586932b --- /dev/null +++ b/deprecated/eo/src/utils/eoAssembledFitnessStat.h @@ -0,0 +1,117 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAssembledFitnessStat.h +// Marc Wintermantel & Oliver Koenig +// IMES-ST@ETHZ.CH +// April 2003 + +//----------------------------------------------------------------------------- +// eoStat.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoAssembledFitnessStat_h +#define _eoAssembledFitnessStat_h + +#include +#include + +/** @addtogroup Stats + * @{ + */ + +/** + Average fitness values of a population, where the fitness is + of type eoScalarAssembledFitness. Specify in the constructor, + for which fitness term (index) the average should be evaluated. + Only values of object where the failed boolean = false is set are counted. +*/ +template +class eoAssembledFitnessAverageStat : public eoStat +{ +public : + + using eoStat::value; + + typedef typename EOT::Fitness Fitness; + + + eoAssembledFitnessAverageStat(unsigned _whichTerm=0, std::string _description = "Average Fitness") + : eoStat(Fitness(), _description), whichFitnessTerm(_whichTerm) + {} + + + virtual void operator()(const eoPop& _pop) { + if( whichFitnessTerm >= _pop[0].fitness().size() ) + throw std::logic_error("Fitness term requested out of range"); + + double result =0.0; + unsigned count = 0; + for (typename eoPop::const_iterator it = _pop.begin(); it != _pop.end(); ++it){ + if ( it->fitness().failed == false ){ + result+= it->fitness()[whichFitnessTerm]; + ++count; + } + } + + value() = result / (double) count; + } + +private: + // Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled + unsigned whichFitnessTerm; +}; + +/** + Fitness values of best individuum in a population, where the fitness is + of type eoScalarAssembledFitness. Specify in the constructor, + for which fitness term (index) the value should be evaluated. +*/ +template +class eoAssembledFitnessBestStat : public eoStat +{ +public: + + using eoStat::value; + + typedef typename EOT::Fitness Fitness; + + eoAssembledFitnessBestStat(unsigned _whichTerm=0, std::string _description = "Best Fitness") + : eoStat(Fitness(), _description), whichFitnessTerm(_whichTerm) + {} + + virtual void operator()(const eoPop& _pop) { + if( whichFitnessTerm >= _pop[0].fitness().size() ) + throw std::logic_error("Fitness term requested out of range"); + + value() = _pop.best_element().fitness()[whichFitnessTerm]; + } + +private: + + // Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled + unsigned whichFitnessTerm; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/eoCheckPoint.h b/deprecated/eo/src/utils/eoCheckPoint.h new file mode 100644 index 000000000..ea562e8bf --- /dev/null +++ b/deprecated/eo/src/utils/eoCheckPoint.h @@ -0,0 +1,183 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoCheckPoint.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoCheckPoint_h +#define _eoCheckPoint_h + +#include +#include +#include +#include + +/** @defgroup Checkpoints Checkpointing + * + * Checkpoints are supposed to be called perodically (for instance at each generation) and + * will call every functors you put in them. + * + * Use them with eoStats, eoUpdater and eoMonitor to get statistics at each generation. + * + * @see eoStat + * @see eoMonitor + * @see eoUpdater + * + * Example of a test program using checkpointing: + * @include t-eoCheckpointing.cpp + * + * @ingroup Utilities + * + * @{ + */ + +/** eoCheckPoint is a container class. + It contains std::vectors of (pointers to) + eoContinue (modif. MS July 16. 2002) + eoStats, eoUpdater and eoMonitor + it is an eoContinue, so its operator() will be called every generation - + and will return the contained-combined-eoContinue result + but before that it will call in turn every single + {statistics, updaters, monitors} that it has been given, + and after that, if stopping, all lastCall methods of the above. +*/ +template +class eoCheckPoint : public eoContinue +{ +public : + + eoCheckPoint(eoContinue& _cont) + { + continuators.push_back(&_cont); + } + + bool operator()(const eoPop& _pop); + + void add(eoContinue& _cont) { continuators.push_back(&_cont); } + void add(eoSortedStatBase& _stat) { sorted.push_back(&_stat); } + void add(eoStatBase& _stat) { stats.push_back(&_stat); } + void add(eoMonitor& _mon) { monitors.push_back(&_mon); } + void add(eoUpdater& _upd) { updaters.push_back(&_upd); } + + virtual std::string className(void) const { return "eoCheckPoint"; } + std::string allClassNames() const ; + +private : + + std::vector*> continuators; + std::vector*> sorted; + std::vector*> stats; + std::vector monitors; + std::vector updaters; +}; + +template +bool eoCheckPoint::operator()(const eoPop& _pop) +{ + unsigned i; + + std::vector sorted_pop; + if (!sorted.empty()) + { + _pop.sort(sorted_pop); + + for (i = 0; i < sorted.size(); ++i) + { + (*sorted[i])(sorted_pop); + } + } + + for (i = 0; i < stats.size(); ++i) + (*stats[i])(_pop); + + for (i = 0; i < updaters.size(); ++i) + (*updaters[i])(); + + for (i = 0; i < monitors.size(); ++i) + (*monitors[i])(); + + bool bContinue = true; + for (i = 0; i < continuators.size(); ++i) + if ( !(*continuators[i])(_pop) ) + bContinue = false; + + if (! bContinue) // we're going to stop: lastCall, gentlemen + { + if (!sorted.empty()) + { + for (i = 0; i < sorted.size(); ++i) + { + sorted[i]->lastCall(sorted_pop); + } + } + for (i = 0; i < stats.size(); ++i) + stats[i]->lastCall(_pop); + + for (i = 0; i < updaters.size(); ++i) + updaters[i]->lastCall(); + + for (i = 0; i < monitors.size(); ++i) + monitors[i]->lastCall(); + } + return bContinue; +} + +/** returns a string with all className() + * of data separated with "\n" (for debugging) + */ +template +std::string eoCheckPoint::allClassNames() const +{ + unsigned i; + std::string s = "\n" + className() + "\n"; + + s += "Sorted Stats\n"; + for (i = 0; i < sorted.size(); ++i) + s += sorted[i]->className() + "\n"; + s += "\n"; + + s += "Stats\n"; + for (i = 0; i < stats.size(); ++i) + s += stats[i]->className() + "\n"; + s += "\n"; + + s += "Updaters\n"; + for (i = 0; i < updaters.size(); ++i) + s += updaters[i]->className() + "\n"; + s += "\n"; + + s += "Monitors\n"; + for (i = 0; i < monitors.size(); ++i) + s += monitors[i]->className() + "\n"; + s += "\n"; + + s += "Continuators\n"; + for (i = 0; i < continuators.size(); ++i) + s += continuators[i]->className() + "\n"; + s += "\n"; + + return s; +} + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/eoData.cpp b/deprecated/eo/src/utils/eoData.cpp new file mode 100644 index 000000000..7e4457075 --- /dev/null +++ b/deprecated/eo/src/utils/eoData.cpp @@ -0,0 +1,11 @@ +// Copyright (C) 2005 Jochen Kpper + + +#include "eoData.h" + + + +// Local Variables: +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/eoData.h b/deprecated/eo/src/utils/eoData.h new file mode 100644 index 000000000..876b00955 --- /dev/null +++ b/deprecated/eo/src/utils/eoData.h @@ -0,0 +1,47 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +----------------------------------------------------------------------------- + eoData.h + + (c) GeNeura Team & Maarten Keijzer, 1998, 1999, 2000 + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef EODATA_H +#define EODATA_H + +#ifndef _MSC_VER +#include +#define _isnan isnan +#endif + + +//----------------------------------------------------------------------------- +// some defines to make things easier to get at first sight + +// to be used in selection / replacement procedures to indicate whether +// the argument (rate, a double) shoudl be treated as a rate (number=rate*popSize) +// or as an absolute integer (number=rate regardless of popsize). +// the default value shoudl ALWAYS be true (eo_as_a_rate). +// +// this construct is mandatory because in some cases you might not know the +// population size that will enter the replacement for instance - so you +// cannot simply have a pre-computed (double) rate of 1/popSize +#define eo_is_a_rate true +#define eo_is_an_integer false + +#endif diff --git a/deprecated/eo/src/utils/eoDistance.h b/deprecated/eo/src/utils/eoDistance.h new file mode 100644 index 000000000..b26f249d6 --- /dev/null +++ b/deprecated/eo/src/utils/eoDistance.h @@ -0,0 +1,104 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoDistance.h +// (c) GeNeura Team, 1998, Marc Schoenauer 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoDistance_H +#define _eoDistance_H + +#include + +/** @addtogroup Stats + * @{ + * */ + +/** + This is a generic class for distance functors: + takes 2 things and returns a double +*/ +template< class EOT > +class eoDistance : public eoBF +{}; + + +/** + This is a generic class for Euclidain distance (L2 norm) computation: + assumes the 2 things are std::vectors of something that is double-castable +*/ +template< class EOT > +class eoQuadDistance : public eoDistance +{ +public: + double operator()(const EOT & _v1, const EOT & _v2) + { + double sum=0.0; + for (unsigned i=0; i<_v1.size(); i++) + { + double r = static_cast (_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 + that is double-castable + For bitstrings, this is the Hamming distance +*/ +template< class EOT > +class eoHammingDistance : public eoDistance +{ +public: + double operator()(const EOT & _v1, const EOT & _v2) + { + double sum=0.0; + for (unsigned i=0; i<_v1.size(); i++) + { + double r = static_cast (_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 ... + * except for some testing + */ +template< class EOT > +class eoFitnessDistance : public eoDistance +{ +public: + double operator()(const EOT & _v1, const EOT & _v2) + { + double d = _v1.fitness() - _v2.fitness(); + return sqrt(d*d); + } +}; + + +/** @} */ + +#endif diff --git a/deprecated/eo/src/utils/eoFDCStat.h b/deprecated/eo/src/utils/eoFDCStat.h new file mode 100644 index 000000000..1d2050b78 --- /dev/null +++ b/deprecated/eo/src/utils/eoFDCStat.h @@ -0,0 +1,144 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFDCStat.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFDCStat_h +#define _eoFDCStat_h + +#include +#include +#include + +/** + The Fitness Distance Correlation computation. + + Stores the values into eoValueParam +so they can be snapshot by some eoGnuplotSnapshot ... + +@ingroup Stats +*/ +template +class eoFDCStat : public eoStat +{ +public: + + using eoStat::value; + + /** Ctor without the optimum */ + eoFDCStat(eoDistance & _dist, std::string _description = "FDC") : + eoStat(0, _description), dist(_dist), boolOpt(false) {} + + /** Ctor with the optimum + */ + eoFDCStat(eoDistance & _dist, EOT & _theBest, + std::string _description = "FDC") : + eoStat(0, _description), dist(_dist), + theBest(_theBest), boolOpt(true) {} + + /** Compute the FDC - either from best in pop, or from absolute best + * if it was passed in the constructor + */ + virtual void operator()(const eoPop& _pop) + { + unsigned i; + if (!boolOpt) // take the local best + theBest = _pop.best_element(); + unsigned int pSize = _pop.size(); + distToBest.value().resize(pSize); + fitnesses.value().resize(pSize); + double sumFit = 0.0, sumDist = 0.0; + for (i=0; i > + */ + const eoValueParam > & theDist() + { return distToBest; } + const eoValueParam > & theFit() + { return fitnesses; } + + +private: + eoDistance & dist; + EOT theBest; + bool boolOpt; // whether the best is known or not + eoValueParam > distToBest; + eoValueParam > fitnesses; +}; + +/** Specific class for FDCStat monitoring: + * As I failed to have FDC stat as an eoStat, this is the trick + * to put the 2 eoParam > into a monitor + * This class does nothing else. + +@ingroup Stats + */ +template +class eoFDCFileSnapshot : public eoFileSnapshot // is an eoMonitor +{ +public: + /** Ctor: in addition to the parameters of the ctor of an eoFileSnapshot + we need here an eoFDCStat. The 2 std::vectors (distances to optimum + and fitnesses) are added to the monitor so they can be processed + later to a file - and eventually by gnuplot + */ + eoFDCFileSnapshot(eoFDCStat & _FDCstat, + std::string _dirname = "tmpFDC", unsigned _frequency = 1, + std::string _filename = "FDC", std::string _delim = " "): + eoFileSnapshot(_dirname, _frequency, _filename, _delim), + FDCstat(_FDCstat) + { + eoFileSnapshot::add(FDCstat.theDist()); + eoFileSnapshot::add(FDCstat.theFit()); + } + + /** just to be sure the add method is not called further + */ + virtual void add(const eoParam& _param) + { throw std::runtime_error("eoFDCFileSnapshot::add(). Trying to add stats to an eoFDCFileSnapshot"); } + +private: + eoFDCStat & FDCstat; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoFeasibleRatioStat.h b/deprecated/eo/src/utils/eoFeasibleRatioStat.h new file mode 100644 index 000000000..cbbe17386 --- /dev/null +++ b/deprecated/eo/src/utils/eoFeasibleRatioStat.h @@ -0,0 +1,66 @@ +/* + +(c) 2010 Thales group + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; version 2 + of the License. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: + Johann Dréo + +*/ + +#ifndef _eoFeasibleRatioStat_h_ +#define _eoFeasibleRatioStat_h_ + +#include + +#include +#include + +#include "eoStat.h" + +/** Ratio of the number of individuals with a feasible dual fitness in the population (@see eoDualFitness) + * + * @ingroup Stats + */ +template +class eoFeasibleRatioStat : public eoStat< EOT, double > +{ +public: + using eoStat::value; + + eoFeasibleRatioStat( std::string description = "FeasibleRatio" ) : eoStat( 0.0, description ) {} + + 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; + eo::log << eo::xdebug << "eoFeasibleRatioStat: " << count << " / " << size << " = " << ratio << std::endl; + value() = ratio; +#else + 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/deprecated/eo/src/utils/eoFileMonitor.cpp b/deprecated/eo/src/utils/eoFileMonitor.cpp new file mode 100644 index 000000000..3cc96deb1 --- /dev/null +++ b/deprecated/eo/src/utils/eoFileMonitor.cpp @@ -0,0 +1,89 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include +#include +#include + +#include +#include +#include + +using namespace std; + +void eoFileMonitor::printHeader(std::ostream& os) +{ + iterator it = vec.begin(); + + os << (*it)->longName(); + + ++it; + + for (; it != vec.end(); ++it) + { + // use the longName of the eoParam for the header + os << delim.c_str() << (*it)->longName(); + } + os << std::endl; +} + +void eoFileMonitor::printHeader() +{ + // create file + ofstream os(filename.c_str()); + + if (!os) + { + string str = "eoFileMonitor could not open: " + filename; + throw runtime_error(str); + } + + printHeader(os); +} + +eoMonitor& eoFileMonitor::operator()(void) +{ + ofstream os(filename.c_str(), + overwrite ? + ios_base::out|ios_base::trunc // truncate + : + ios_base::out|ios_base::app // append + ); + + if (!os) + { + string str = "eoFileMonitor could not write to: " + filename; + throw runtime_error(str); + } + + if ( + header // we want to write headers + && firstcall // we do not want to write headers twice + && !keep // if we append to an existing file, headers are useless + && !overwrite // we do not want to write headers if the file is to be overwriten + ) { + printHeader(); + firstcall = false; + } + + return operator()(os); +} + +eoMonitor& eoFileMonitor::operator()(std::ostream& os) +{ + + iterator it = vec.begin(); + + os << (*it)->getValue(); + + for(++it; it != vec.end(); ++it) + { + os << delim.c_str() << (*it)->getValue(); + } + + os << std::endl; + + return *this; +} diff --git a/deprecated/eo/src/utils/eoFileMonitor.h b/deprecated/eo/src/utils/eoFileMonitor.h new file mode 100644 index 000000000..9438d25c3 --- /dev/null +++ b/deprecated/eo/src/utils/eoFileMonitor.h @@ -0,0 +1,121 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFileMonitor.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef EO_eoFileMonitor_h +#define EO_eoFileMonitor_h + +#include +#include +#include + +#include "utils/eoMonitor.h" +#include "eoObject.h" + + +/** Prints statistics to file + +Modified the default behavior, so that it erases existing files. Can +be modified in the ctor. + +@version MS 25/11/00 +@ingroup Monitors +*/ +class eoFileMonitor : public eoMonitor +{ +public : + + /*! Constructor + * + * Try to create the file in writing mode, erasing it if asked. + * + * @param _filename complete filename to write to + * @param _delim delimiter string to use between each item of the registered vector (e.g. of eoStats) + * @param _keep_existing if true, overwrite any existing file with the same name prior to any output + * @param _header print the header (with the descriptions of registered eoStats) at the beginning of the file (WARNING: true will discards header printing) + * @param _overwrite if true, overwrite the existing file + */ + eoFileMonitor( + std::string _filename, + std::string _delim = " ", + bool _keep_existing = false, + bool _header = false, + bool _overwrite = false + ) + : filename(_filename), + delim(_delim), + keep(_keep_existing), + header(_header), + firstcall(true), + overwrite(_overwrite) + { + if (!_keep_existing) { + std::ofstream os (filename.c_str ()); + + if (!os) { + std::string str = "Error, eoFileMonitor could not open: " + filename; + throw std::runtime_error (str); + } + } // if ! keep + } + + //! Called first, try to open the file in append mode and write the header if asked + virtual eoMonitor& operator()(void); + + /*! Main call, normally called at each generation. + Write the content of the registered vector into the file, each item being separated by delim + */ + virtual eoMonitor& operator()(std::ostream& os); + + //! Try to open the file, and then call printHeader(file) + void printHeader(void); + + //! Print long names of the registered items, separated by delim. + virtual void printHeader(std::ostream& os); + + virtual std::string getFileName() { return filename;} + +private : + + //! complete filename to write to + std::string filename; + + //! delimiter to use between each write + std::string delim; + + //! should we append or create a new file + bool keep; + + //! printing header at begin of file? + bool header; + + //! flag to avoid calling twice operator()(void) + bool firstcall; + + //! erase the entire file prior to writing in it (mode eos_base:: + bool overwrite; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoFileSnapshot.h b/deprecated/eo/src/utils/eoFileSnapshot.h new file mode 100644 index 000000000..cdd2e36cc --- /dev/null +++ b/deprecated/eo/src/utils/eoFileSnapshot.h @@ -0,0 +1,200 @@ +//----------------------------------------------------------------------------- +// eoFileSnapshot.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFileSnapshot_h +#define _eoFileSnapshot_h + +#include +#include +#include + +#include +#include +#include + + +/** + Prints snapshots of fitnesses to a (new) file every N generations + +Assumes that the parameters that are passed to the monitor +(method add in eoMonitor.h) are eoValueParam > of same size. + +A dir is created and one file per snapshot is created there - +so you can later generate a movie! + +@todo The counter is handled internally, but this should be changed +so that you can pass e.g. an evalcounter (minor) + +I failed to templatize everything so that it can handle eoParam > +for any type T, simply calling their getValue method ... + +@ingroup Monitors +*/ +class eoFileSnapshot : public eoMonitor +{ +public : + typedef std::vector vDouble; + typedef eoValueParam > vDoubleParam; + + eoFileSnapshot(std::string _dirname, unsigned _frequency = 1, std::string _filename = "gen", + std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true): + dirname(_dirname), frequency(_frequency), + filename(_filename), delim(_delim), counter(_counter), boolChanged(true) + { + std::string s = "test -d " + dirname; + + int res = system(s.c_str()); + // test for (unlikely) errors + if ( (res==-1) || (res==127) ) + throw std::runtime_error("Problem executing test of dir in eoFileSnapshot"); + // now make sure there is a dir without any genXXX file in it + if (res) // no dir present + { + s = std::string("mkdir ")+dirname; + } + else if (!res && _rmFiles) + { + s = std::string("/bin/rm ")+dirname+ "/" + filename + "*"; + } + else + s = " "; + + res=system(s.c_str()); + // all done + } + + /** accessor: has something changed (for gnuplot subclass) + */ + virtual bool hasChanged() {return boolChanged;} + + /** accessor to the counter: needed by the gnuplot subclass + */ + unsigned getCounter() {return counter;} + + /** accessor to the current filename: needed by the gnuplot subclass + */ + std::string getFileName() {return currentFileName;} + + /** sets the current filename depending on the counter + */ + void setCurrentFileName() + { + std::ostringstream oscount; + oscount << counter; + currentFileName = dirname + "/" + filename + oscount.str(); + } + + /** The operator(void): opens the std::ostream and calls the write method + */ + eoMonitor& operator()(void) + { + if (counter % frequency) + { + boolChanged = false; // subclass with gnuplot will do nothing + counter++; + return (*this); + } + counter++; + boolChanged = true; + setCurrentFileName(); + std::ofstream os(currentFileName.c_str()); + + if (!os) + { + std::string str = "eoFileSnapshot: Could not open " + currentFileName; + throw std::runtime_error(str); + } + + return operator()(os); + } + + /** The operator(): write on an std::ostream + */ + eoMonitor& operator()(std::ostream& _os) + { + const eoValueParam > * ptParam = + static_cast >* >(vec[0]); + + const std::vector v = ptParam->value(); + 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 >*>(&_param)) + { + throw std::logic_error(std::string("eoFileSnapshot: I can only monitor std::vectors of doubles, sorry. The offending parameter name = ") + _param.longName()); + } + eoMonitor::add(_param); + } + +private : + std::string dirname; + unsigned frequency; + std::string filename; + std::string delim; + unsigned int counter; + std::string currentFileName; + bool boolChanged; +}; + +#endif + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/eoFuncPtrStat.h b/deprecated/eo/src/utils/eoFuncPtrStat.h new file mode 100644 index 000000000..c77281577 --- /dev/null +++ b/deprecated/eo/src/utils/eoFuncPtrStat.h @@ -0,0 +1,80 @@ +#ifndef eoFuncPtrStat_h +#define eoFuncPtrStat_h + +#include +#include + + + +/** Wrapper to turn any stand-alone function and into an eoStat. + * + * The function should take an eoPop as argument. + * + * @ingroup Stats + */ +template +class eoFuncPtrStat : public eoStat +{ +public : + typedef T (*func_t)(const eoPop&); + + + eoFuncPtrStat(func_t f, std::string _description = "func_ptr") + : eoStat(T(), _description), func(f) + {} + + using eoStat::value; + + void operator()(const eoPop& pop) { + value() = func(pop); + } + +private: + func_t func; +}; + +/** + * @ingroup Stats + */ +template +eoFuncPtrStat& makeFuncPtrStat( T (*func)(const eoPop&), eoFunctorStore& store, std::string description = "func") { + return store.storeFunctor( + new eoFuncPtrStat( func, description) + ); +} + +/** Wrapper to turn any stand-alone function and into an eoStat. + * + * The function should take an eoPop as argument. + * + * @ingroup Stats + */ +template +class eoFunctorStat : public eoStat +{ +public : + eoFunctorStat(eoUF< const eoPop&, T >& f, std::string _description = "functor") + : eoStat(T(), _description), func(f) + {} + + using eoStat::value; + + void operator()(const eoPop& pop) { + value() = func(pop); + } + +private: + eoUF< const eoPop&, T >& func; +}; + +/** + * @ingroup Stats + */ +template +eoFunctorStat& makeFunctorStat( eoUF< const eoPop&, T >& func, eoFunctorStore& store, std::string description = "func") { + return store.storeFunctor( + new eoFunctorStat( func, description) + ); +} + +#endif diff --git a/deprecated/eo/src/utils/eoGenCounter.h b/deprecated/eo/src/utils/eoGenCounter.h new file mode 100644 index 000000000..a06949c21 --- /dev/null +++ b/deprecated/eo/src/utils/eoGenCounter.h @@ -0,0 +1,46 @@ +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + (c) Thales group 2011 + + Author: johann.dreo@thalesgroup.com + */ + +#ifndef _eoGenCounter_h +#define _eoGenCounter_h + +#include +#include + +/** + An eoStat that simply gives the current generation index + + @ingroup Stats +*/ +class eoGenCounter : public eoUpdater, public eoValueParam +{ +public: + eoGenCounter( unsigned int start = 0, std::string label = "Gen" ) : eoValueParam(start, label), _nb(start) {} + + virtual void operator()() + { + value() = _nb++; + } + +private: + unsigned int _nb; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoGnuplot.cpp b/deprecated/eo/src/utils/eoGnuplot.cpp new file mode 100644 index 000000000..2905e6161 --- /dev/null +++ b/deprecated/eo/src/utils/eoGnuplot.cpp @@ -0,0 +1,99 @@ +//----------------------------------------------------------------------------- +// (c) Marc Schoenauer, 2001 +// Copyright (C) 2005 Jochen Kpper +/* + This library is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free + Software Foundation; either version 2 of the License, or (at your option) any + later version. + + This library is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + details. + + You should have received a copy of the GNU Lesser General Public License + along with this library; if not, write to the Free Software Foundation, Inc., + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include "eoGnuplot.h" + + +unsigned eoGnuplot::numWindow=0; + + + +eoGnuplot::eoGnuplot(std::string _title, std::string _extra) + : firstTime(true) +{ + initGnuPlot(_title, _extra); +} + + + +eoGnuplot::~eoGnuplot() +{ +#ifdef HAVE_GNUPLOT + if( gpCom ) { + PipeComSend( gpCom, "quit\n" ); + PipeComClose( gpCom ); + gpCom =NULL; + } +#endif +} + + + +void eoGnuplot::gnuplotCommand(const char *_command) +{ +#ifdef HAVE_GNUPLOT + if(gpCom) { + PipeComSend( gpCom, _command ); + PipeComSend( gpCom, "\n" ); + } +#endif +} + + + +void eoGnuplot::initGnuPlot(std::string _title, std::string _extra) +{ +#ifdef HAVE_GNUPLOT + std::ostringstream os; + os << "250x150-0+" << 170 * numWindow++; + char *args[6]; + args[0] = strdup( GNUPLOT_PROGRAM ); + args[1] = strdup( "-geometry" ); + args[2] = strdup( os.str().c_str()); + args[3] = strdup( "-title" ); + args[4] = strdup( _title.c_str() ); + args[5] = 0; + gpCom = PipeComOpenArgv( GNUPLOT_PROGRAM, args ); + if(! gpCom ) + throw std::runtime_error("Cannot spawn gnuplot\n"); + else { + PipeComSend( gpCom, "set grid\n" ); + PipeComSend( gpCom, _extra.c_str() ); + PipeComSend( gpCom, "\n" ); + } +#endif +} + + + +// Local Variables: +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/eoGnuplot.h b/deprecated/eo/src/utils/eoGnuplot.h new file mode 100644 index 000000000..783d44ccb --- /dev/null +++ b/deprecated/eo/src/utils/eoGnuplot.h @@ -0,0 +1,101 @@ +//----------------------------------------------------------------------------- +// eoGnuplot1DMonitor.h +// (c) Marc Schoenauer, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- +#ifndef EO_eoGnuplot_H +#define EO_eoGnuplot_H + +#include + +#include "pipecom.h" + + +/** Base class for calls to gnuplot + +This class is the abstract class that will be used by further gnuplot +calls to plots what is already written by some eoMonitor into a file + +@author Marc Schoenauer +@version 0.0 (2001) + +@ingroup Monitors +*/ +class eoGnuplot +{ +public: + + /** Open pipe to Gnuplot. + + @param _title Title for gnuplot window. + @param _extra Extra parameters to gnuplot (default to none: ""). + */ + eoGnuplot(std::string _title, std::string _extra = std::string("")); + + /** Destructor + + Close the gnuplot windows if pipe was correctly opened + */ + virtual ~eoGnuplot(); + + /** Class name */ + virtual std::string className() const + { return "eoGnuplot"; } + + /** Send command to gnuplot */ + void gnuplotCommand(const char * _command); + + /** Send command to gnuplot + + @overload + */ + void gnuplotCommand(std::string _command) + { gnuplotCommand(_command.c_str()); } + + +protected: + + /** Initialize gnuplot + + @param _title Title for gnuplot window. + @param _extra Extra parameters to gnuplot. + */ + void initGnuPlot(std::string _title, std::string _extra); + + /** The stats might be unknown in Ctor */ + bool firstTime; + + /** Communication with gnuplot OK */ + PCom *gpCom; + + /** Internal counter for gnuplot windows */ + static unsigned numWindow; +}; + + +#endif // EO_eoGnuplot_H + + + +// Local Variables: +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// mode: C++ +// End: diff --git a/deprecated/eo/src/utils/eoGnuplot1DMonitor.cpp b/deprecated/eo/src/utils/eoGnuplot1DMonitor.cpp new file mode 100644 index 000000000..c0cff842c --- /dev/null +++ b/deprecated/eo/src/utils/eoGnuplot1DMonitor.cpp @@ -0,0 +1,85 @@ +//----------------------------------------------------------------------------- +// eoGnuplot1DMonitor.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +#include "utils/eoGnuplot1DMonitor.h" +#include "utils/eoParam.h" + + +eoMonitor& eoGnuplot1DMonitor::operator() (void) +{ + // update file using the eoFileMonitor + eoFileMonitor::operator()(); +#ifdef HAVE_GNUPLOT + // sends plot order to gnuplot + // assumes successive plots will have same nb of columns!!! + if (firstTime) + { + FirstPlot(); + firstTime = false; + } + else + { + if( gpCom ) { + PipeComSend( gpCom, "replot\n" ); + } + } +#endif + return *this; +} + + + +void eoGnuplot1DMonitor::FirstPlot() +{ + if (this->vec.size() < 2) + { + throw std::runtime_error("Must have some stats to plot!\n"); + } +#ifdef HAVE_GNUPLOT + std::ostringstream os; + os << "plot"; + for (unsigned i=1; ivec.size(); i++) { + os << " '" << getFileName().c_str() << + "' using 1:" << i+1 << " title '" << (this->vec[i])->longName() << "' with lines" ; + if (ivec.size()-1) + os << ", "; + } + os << '\n'; + PipeComSend( gpCom, os.str().c_str()); +#endif +} + + + +// Local Variables: +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/eoGnuplot1DMonitor.h b/deprecated/eo/src/utils/eoGnuplot1DMonitor.h new file mode 100644 index 000000000..e32e22275 --- /dev/null +++ b/deprecated/eo/src/utils/eoGnuplot1DMonitor.h @@ -0,0 +1,85 @@ +//----------------------------------------------------------------------------- +// eoGnuplot1DMonitor.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- +#ifndef EO_eoGnuplot1DMonitor_H +#define EO_eoGnuplot1DMonitor_H + +#include +#include + +#include "eoObject.h" +#include "utils/eoFileMonitor.h" +#include "utils/eoGnuplot.h" +#include "utils/pipecom.h" + +/** Plot eoStat + +@author Marc Schoenauer +@version 0.0 (2000) + +This class plots through gnuplot the eoStat given as argument + +eoGnuplot1DMonitor plots stats through gnuplot + +Assumes that the same file is appened every so and so, and replots it +everytime + +@ingroup Monitors +*/ +class eoGnuplot1DMonitor : public eoFileMonitor, public eoGnuplot +{ +public: + + // this "using" directive generates a compiler internal error in GCC 4.0.0 ... + // it's been removed, and the only call to vec was replaced by this->vec in eoGnuplot1DMonitor.cpp + // using eoMonitor::vec; + + /** Constructor */ + eoGnuplot1DMonitor(std::string _filename, bool _top=false) : + eoFileMonitor(_filename, " "), + eoGnuplot(_filename,(_top?"":"set key bottom")) + {} + + /** Destructor */ + virtual ~eoGnuplot1DMonitor(){} + + virtual eoMonitor& operator()(); + + virtual void FirstPlot(); + + /** Class name */ + virtual std::string className() const + { return "eoGnuplot1DMonitor"; } +}; + + +#endif // EO_eoGnuplot1DMonitor_H + + + +// Local Variables: +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// mode: C++ +// End: diff --git a/deprecated/eo/src/utils/eoGnuplot1DSnapshot.cpp b/deprecated/eo/src/utils/eoGnuplot1DSnapshot.cpp new file mode 100644 index 000000000..b41477a22 --- /dev/null +++ b/deprecated/eo/src/utils/eoGnuplot1DSnapshot.cpp @@ -0,0 +1,33 @@ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "eoGnuplot1DSnapshot.h" + + + +eoMonitor& eoGnuplot1DSnapshot::operator()() +{ + // update file using the eoFileMonitor method + eoFileSnapshot::operator()(); +#ifdef HAVE_GNUPLOT + // sends plot order to gnuplot + std::ostringstream os; + os << "set title 'Gen. " << getCounter() << "'; plot '" + // mk: had to use getFilename().c_str(), + // because it seems the string(stream) lib is screwed in gcc3.2 + << getFileName().c_str() << "' notitle with points ps " << pointSize + << std::endl; + PipeComSend(gpCom, os.str().c_str()); +#endif + return *this; +} + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/eoGnuplot1DSnapshot.h b/deprecated/eo/src/utils/eoGnuplot1DSnapshot.h new file mode 100644 index 000000000..38c5af745 --- /dev/null +++ b/deprecated/eo/src/utils/eoGnuplot1DSnapshot.h @@ -0,0 +1,121 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGnuplot1DSnapshot.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + + +#ifndef EO_eoGnuplot1DSnapshot_H +#define EO_eoGnuplot1DSnapshot_H + +#include +#include +#include + +#include +#include "eoRealVectorBounds.h" +#include +#include +#include + +/** Plot stats through gnuplot + +@author Marc Schoenauer 2000 +@version 0.0 + +This class plots through gnuplot the eoStat given as argument + +Assumes that the same file is re-written every so and so, and plots it +from scratch everytime it's called + +@ingroup Monitors + */ +class eoGnuplot1DSnapshot: public eoFileSnapshot, public eoGnuplot +{ + public: + // Ctor + eoGnuplot1DSnapshot(std::string _dirname, unsigned _frequency = 1, + std::string _filename = "gen", std::string _delim = " ", + unsigned _counter = 0, bool _rmFiles = true) : + eoFileSnapshot(_dirname, _frequency, _filename, _delim, _counter, _rmFiles), + eoGnuplot(_filename,"set data style points"), + pointSize(5) + {} + + // Ctor + eoGnuplot1DSnapshot(std::string _dirname, eoRealVectorBounds & _bounds, + unsigned _frequency = 1, std::string _filename = "gen", + std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true ) : + eoFileSnapshot(_dirname, _frequency, _filename, _delim, _counter, _rmFiles), + eoGnuplot(_filename,"set data style points"), + pointSize(5) + { + handleBounds(_bounds); + } + // Ctor + eoGnuplot1DSnapshot(eoFileSnapshot & _fSnapshot) : + eoFileSnapshot(_fSnapshot), + eoGnuplot(_fSnapshot.baseFileName(),"set data style points"), + pointSize(5) + {} + + // Ctor with range + eoGnuplot1DSnapshot(eoFileSnapshot & _fSnapshot, eoRealVectorBounds & _bounds) : + eoFileSnapshot(_fSnapshot), + eoGnuplot(_fSnapshot.baseFileName(),"set data style points"), + pointSize(5) + { + handleBounds(_bounds); + } + + // Dtor + virtual ~eoGnuplot1DSnapshot(){} + + virtual eoMonitor& operator()(); + + /// Class name. + virtual std::string className() const { return "eoGnuplot1DSnapshot"; } + + virtual void handleBounds(eoRealVectorBounds & _bounds) + { + std::ostringstream os; + os << "set autoscale\nset yrange [" ; + if (_bounds.isMinBounded(0)) + os << _bounds.minimum(0); + os << ":" ; + if (_bounds.isMaxBounded(0)) + os << _bounds.maximum(0); + os << "]\n"; + gnuplotCommand(os.str()); + } + + void setPointSize(unsigned _pointSize) + { pointSize = _pointSize; } + +protected: + + unsigned pointSize; +}; + + +#endif diff --git a/deprecated/eo/src/utils/eoHowMany.h b/deprecated/eo/src/utils/eoHowMany.h new file mode 100644 index 000000000..1105f3b73 --- /dev/null +++ b/deprecated/eo/src/utils/eoHowMany.h @@ -0,0 +1,205 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoHowMany_h.h +// Base class for choosing a number of guys to apply something from a popsize +// (c) Marc Schoenauer, 2000 +// (c) Thales group, 2010 (Johann Dréo ) + +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +*/ +//----------------------------------------------------------------------------- + +#ifndef eoHowMany_h +#define eoHowMany_h + +#include + +#include + + +/** A helper class, to determine a number of individuals from another one + * Typically, is used in selection / replacement procedures, e.g. + * the number of offspring from the number of parents, or + * the number of survivors for an eoReduce functor, ... + * + * Such construct is very useful because in some cases you might not know the + * population size that will enter the replacement. For instance, you + * cannot simply have a pre-computed (double) rate of 1/popSize + * if you want to select or kill just 1 guy. Using an eoHowMany + * allows one to modify the population size without touching anything else. + * + * There are 4 possible way to compute the return value from the argument: + * - an absolute POSITIVE integer --> return it (regardless of popsize) + * - a POSITIVE rate --> return rate*popSize + * - an absolute NEGATIVE integer --> return popsize-rate (if positive) + * - a NEGATIVE rate in [-1,0] --> store and use 1-|rate| (positive) + * Note that a negative rate should be have been necessary because a rate is + * relative, but it is there for consistency reasons - and because it + * is needed in eoG3Replacement + * + * It has 2 private members, a double and an integer to cover all cases + * + * Example use: in eoGeneralBreeder.h + * Example reading from parser: in + * do/make_algo_scalar.h line 141 + + * MS 10/04/2002: + * Added the possibility to have a negative number - + * when treated as a number: returns then (size - count) + * Should not modify anything when a positive number is passed in the ctor + * + * MS 20/06/2002: + * Added the negative rate and the operator-() (for + * eoG3Repalcement) + * + * It is an eoPersistent because we need to be able to use eoParamValue + * + * @ingroup Core + */ +class eoHowMany : public eoPersistent +{ +public: + /** Original Ctor from direct rate + bool + @param _rate the rate, OR the integer to store, depending on 2nd arg. + @param _interpret_as_rate to tell whether the rate actually is a rate + */ + eoHowMany(double _rate = 0.0, bool _interpret_as_rate = true): + rate(_rate), count(0) + { + if (_interpret_as_rate) + { + if (_rate<0) + { + rate = 1.0+_rate; + if (rate < 0) // was < -1 + throw std::logic_error("rate<-1 in eoHowMany!"); + } + } + else + { + rate = 0.0; // just in case, but shoud be unused + count = int(_rate); // negative values are allowed here + if (count != _rate) + eo::log << eo::warnings << "Number was rounded in eoHowMany"; + } + } + + /** Ctor from an int - both from int and unsigned int are needed + * to avoid ambiguity with the Ctor from a double */ + eoHowMany(int _count) : rate(0.0), count(_count) {} + + /** Ctor from an unsigned int - both from int and unsigned int are needed + * to avoid ambiguity with the Ctor from a double */ + eoHowMany(unsigned int _count) : rate(0.0), count(_count) {} + + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoHowMany() {} + + /** Does what it was designed for + * - count==0 : return rate*_size + * - else + * - count>0 : return count (regardless of _size) + * - count<0 : return _size-|count| + */ + unsigned int operator()(unsigned int _size) + { + if (count == 0) + { + unsigned int res = static_cast( std::ceil( rate * _size ) ); + + if( res == 0 ) { + eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (rate=" << rate << ", size=" << _size << ")" << std::endl; + } + + return res; + } + if (count < 0) + { + unsigned int combloc = -count; + if (_size> value; + readFrom(value); + return; + } + + void readFrom(std::string _value) + { + // check for % + bool interpret_as_rate = false; // == no % + size_t pos = _value.find('%'); + if (pos < _value.size()) // found a % + { + interpret_as_rate = true; + _value.resize(pos); // get rid of % + } + + std::istringstream is(_value); + is >> rate; + // now store + if (interpret_as_rate) + { + count = 0; + rate /= 100.0; + } + else + count = int(rate); // and rate will not be used + + // minimal check + if ( rate < 0.0 ) + throw std::runtime_error("Negative rate read in eoHowMany::readFrom"); + } + + /** The unary - operator: reverses the computation */ + eoHowMany operator-() + { + if (!count) // only rate is used + rate = 1.0-rate; + else + count = -count; + return (*this); + } + +private : + double rate; + int count; +}; + + + +#endif diff --git a/deprecated/eo/src/utils/eoIntBounds.cpp b/deprecated/eo/src/utils/eoIntBounds.cpp new file mode 100644 index 000000000..11cd942d2 --- /dev/null +++ b/deprecated/eo/src/utils/eoIntBounds.cpp @@ -0,0 +1,98 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include "eoIntBounds.h" + + +// the global dummy bounds +// (used for unbounded variables when bounds are required) +eoIntNoBounds eoDummyIntNoBounds; + +///////////// helper read functions defined in eoRealBounds.cpp +extern bool remove_leading(std::string & _s, const std::string _delim); +extern double read_double(std::string _s); +extern long int read_int(std::string _s); + + +/** the constructor for eoGeneralIntBound - from a string + */ +eoIntBounds* eoGeneralIntBounds::getBoundsFromString(std::string _value) +{ + // now read + std::string delim(",; "); + std::string beginOrClose("[(])"); + if (!remove_leading(_value, delim)) // only delimiters were left + throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); + + // look for opening char + size_t posDeb = _value.find_first_of(beginOrClose); // allow ]a,b] + if (posDeb >= _value.size()) // nothing left to read + throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); + + // ending char: next {}() after posDeb + size_t posFin = _value.find_first_of(beginOrClose,posDeb+1); + if (posFin >= _value.size()) // not found + throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); + + // the bounds + std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1); + // and remove from original string + _value = _value.substr(posFin+1); + + remove_leading(sBounds, delim); + size_t posDelim = sBounds.find_first_of(delim); + if (posDelim >= sBounds.size()) + throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); + + bool minBounded=false, maxBounded=false; + long int minBound=0, maxBound=0; + + // min bound + std::string sMinBounds = sBounds.substr(0,posDelim); + + if ( (sMinBounds != std::string("-inf")) && + (sMinBounds != std::string("-infinity")) + ) + { + minBounded = true; + minBound = read_int(sMinBounds); + } + + // max bound + size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); + + std::string sMaxBounds = sBounds.substr(posEndDelim); + + if ( (sMaxBounds != std::string("+inf")) && + (sMaxBounds != std::string("+infinity")) + ) + { + maxBounded = true; + maxBound = read_int(sMaxBounds); + } + + // now create the embedded eoIntBounds object + eoIntBounds * locBound; + if (minBounded && maxBounded) + { + if (maxBound <= minBound) + throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); + locBound = new eoIntInterval(minBound, maxBound); + } + else if (!minBounded && !maxBounded) // no bound at all + locBound = new eoIntNoBounds; + else if (!minBounded && maxBounded) + locBound = new eoIntAboveBound(maxBound); + else if (minBounded && !maxBounded) + locBound = new eoIntBelowBound(minBound); + return locBound; +} diff --git a/deprecated/eo/src/utils/eoIntBounds.h b/deprecated/eo/src/utils/eoIntBounds.h new file mode 100644 index 000000000..2127c92f7 --- /dev/null +++ b/deprecated/eo/src/utils/eoIntBounds.h @@ -0,0 +1,729 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoIntBounds.h +// (c) Marc Schoenauer 2001, Maarten Keijzer 2000, GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoIntBounds_h +#define _eoIntBounds_h + +#include // std::exceptions! +#include + +/** +\class eoIntBounds eoIntBounds.h es/eoIntBounds.h +\ingroup Real +\ingroup Bounds + + Defines bound classes for real numbers. + +Scalar type: +------------ +Basic class is eoIntBounds, a pure virtual. + +The following pure virtual methods are to be used in mutations: +- void foldsInBounds(long int &) that folds any value that falls out of + the bounds back into the bounds, by bouncing on the limit (if any) +- bool isInBounds(long int) that simply says whether or not the argument + is in the bounds +- void truncate(long int &) that set the argument to the bound value it +it exceeds it + +So mutation can choose +- iterate trying until they fall in bounds, +- only try once and "restd::pair" by using the foldsInBounds method +- only try once and restd::pair using the truncate method (will create a + huge bias toward the bound if the soluiton is not far from the bounds) + +There is also a uniform() method that generates a uniform value +(if possible, i.e. if bounded) in the interval. + +Derived class are +eoIntInterval that holds a minimum and maximum value, +eoIntNoBounds the "unbounded bounds" (-infinity, +infinity) +eoIntBelowBound the half-bounded interval [min, +infinity) +eoIntAboveBound the half-bounded interval (-infinity, max] + +THis file also contains the declaration of *the* global object that +is the unbounded bound +*/ +class eoIntBounds : public eoPersistent +{ +public: + virtual ~eoIntBounds(){} + + /** Self-Test: true if ***both*** a min and a max + */ + virtual bool isBounded(void) const = 0; + + /** Self-Test: true if no min ***and*** no max + * hence no further need to test/truncate/fold anything + */ + virtual bool hasNoBoundAtAll(void) const = 0; + + /** Self-Test: bounded from below??? + */ + virtual bool isMinBounded(void) const = 0; + + /** Self-Test: bounded from above??? + */ + virtual bool isMaxBounded(void) const = 0; + + /** Test on a value: is it in bounds? + */ + virtual bool isInBounds(double) const = 0; + + /** Put value back into bounds - by folding back and forth + */ + virtual void foldsInBounds(double &) const = 0; + + /** foldsInBounds for ints: + * call the method for double and convert back */ + virtual void foldsInBounds(long int & i) const + { + double r = double(i); + foldsInBounds(r); + i = (long int)(r); + } + + /** Put value back into bounds - by truncating to a boundary value + */ + virtual void truncate(double &) const = 0; + + /** truncate for ints: call the method for double and convert back + */ + virtual void truncate(long int & i) const + { + double r = double(i); + truncate(r); + i = (long int)(r); + } + + /** get minimum value + * std::exception if does not exist + */ + virtual long int minimum() const = 0 ; + /** get maximum value + * std::exception if does not exist + */ + virtual long int maximum() const = 0 ; + /** get range + * std::exception if unbounded + */ + virtual long int range() const = 0; + + /** random generator of uniform numbers in bounds + * uses same naming convention than eo::rng + * std::exception if unbounded + */ + virtual double uniform(eoRng & _rng = eo::rng) const = 0; + virtual long int random(eoRng & _rng = eo::rng) const = 0; + + /** for memory managements - ugly */ + virtual eoIntBounds * dup() const = 0; +}; + +/** A default class for unbounded variables + * + * @ingroup Real + * @ingroup Bounds + */ +class eoIntNoBounds : public eoIntBounds +{ +public: + virtual ~eoIntNoBounds(){} + + virtual bool isBounded(void) const {return false;} + virtual bool hasNoBoundAtAll(void) const {return true;} + virtual bool isMinBounded(void) const {return false;} + virtual bool isMaxBounded(void) const {return false;} + virtual void foldsInBounds(double &) const {return;} + virtual void truncate(double &) const {return;} + virtual bool isInBounds(double) const {return true;} + + virtual long int minimum() const + { + throw std::logic_error("Trying to get minimum of unbounded eoIntBounds"); + } + virtual long int maximum() const + { + throw std::logic_error("Trying to get maximum of unbounded eoIntBounds"); + } + virtual long int range() const + { + throw std::logic_error("Trying to get range of unbounded eoIntBounds"); + } + + virtual double uniform(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in unbounded eoIntBounds"); + } + + virtual long int random(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in unbounded eoIntBounds"); + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoIntVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoIntBounds::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[-inf,+inf]"; + } + + /** for memory managements - ugly */ + virtual eoIntBounds * dup() const + { + return new eoIntNoBounds(*this); + } + +}; + +/** one object for all - see eoIntBounds.cpp + * + * @ingroup Real + * @ingroup Bounds + */ +extern eoIntNoBounds eoDummyIntNoBounds; + +/** + * fully bounded eoIntBound == interval + * + * @ingroup Real + * @ingroup Bounds + */ +class eoIntInterval : public eoIntBounds +{ +public : + virtual ~eoIntInterval(){} + + /** + Simple bounds = minimum and maximum (allowed) + */ + eoIntInterval(long int _min=0, long int _max=1) : + repMinimum(_min), repMaximum(_max), repRange(_max-_min) + { + if (repRange<=0) + throw std::logic_error("Void range in eoIntBounds"); + } + + // accessors + virtual long int minimum() const { return repMinimum; } + virtual long int maximum() const { return repMaximum; } + virtual long int range() const { return repRange; } + + // description + virtual bool isBounded(void) const {return true;} + virtual bool hasNoBoundAtAll(void) const {return false;} + virtual bool isMinBounded(void) const {return true;} + virtual bool isMaxBounded(void) const {return true;} + + virtual double uniform(eoRng & _rng = eo::rng) const + { + return repMinimum + _rng.uniform(repRange); + } + + virtual long int random(eoRng & _rng = eo::rng) const + { + return repMinimum + _rng.random(repRange); + } + + // says if a given double is within the bounds + virtual bool isInBounds(double _r) const + { + if (_r < repMinimum) + return false; + if (_r > repMaximum) + return false; + return true; + } + + // folds a value into bounds + virtual void foldsInBounds(double & _r) const + { + long iloc; + double dlargloc = 2 * range() ; + + if (fabs(_r) > 1.0E9) // iloc too large! + { + _r = uniform(); + return; + } + + if ( (_r > maximum()) ) + { + iloc = (long) ( (_r-minimum()) / dlargloc ) ; + _r -= dlargloc * iloc ; + if ( _r > maximum() ) + _r = 2*maximum() - _r ; + } + + if (_r < minimum()) + { + iloc = (long) ( (maximum()-_r) / dlargloc ) ; + _r += dlargloc * iloc ; + if (_r < minimum()) + _r = 2*minimum() - _r ; + } + } + + // truncates to the bounds + virtual void truncate(double & _r) const + { + if (_r < repMinimum) + _r = repMinimum; + else if (_r > repMaximum) + _r = repMaximum; + return; + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoIntVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoIntInterval::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[" << repMinimum << "," << repMaximum << "]"; + } + + /** for memory managements - ugly */ + virtual eoIntBounds * dup() const + { + return new eoIntInterval(*this); + } + +private : + long int repMinimum; + long int repMaximum; + long int repRange; // to minimize operations ??? +}; + +/** + * an eoIntBound bounded from below only + * + * @ingroup Real + * @ingroup Bounds + */ +class eoIntBelowBound : public eoIntBounds +{ +public : + virtual ~eoIntBelowBound(){} + /** + Simple bounds = minimum + */ + eoIntBelowBound(long int _min=0) : + repMinimum(_min) + {} + + // accessors + virtual long int minimum() const { return repMinimum; } + + virtual long int maximum() const + { + throw std::logic_error("Trying to get maximum of eoIntBelowBound"); + } + virtual long int range() const + { + throw std::logic_error("Trying to get range of eoIntBelowBound"); + } + + virtual double uniform(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in eoIntBelowBound"); + } + + virtual long int random(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in eoIntBelowBound"); + } + + // description + virtual bool isBounded(void) const {return false;} + virtual bool hasNoBoundAtAll(void) const {return false;} + virtual bool isMinBounded(void) const {return true;} + virtual bool isMaxBounded(void) const {return false;} + + // says if a given double is within the bounds + virtual bool isInBounds(double _r) const + { + if (_r < repMinimum) + return false; + return true; + } + + // folds a value into bounds + virtual void foldsInBounds(double & _r) const + { + // easy as a pie: symmetry w.r.t. minimum + if (_r < repMinimum) // nothing to do otherwise + _r = 2*repMinimum - _r; + return ; + } + + // truncates to the bounds + virtual void truncate(double & _r) const + { + if (_r < repMinimum) + _r = repMinimum; + return; + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoIntVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoIntBelowBound::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[" << repMinimum << ",+inf]"; + } + + /** for memory managements - ugly */ + virtual eoIntBounds * dup() const + { + return new eoIntBelowBound(*this); + } + +private : + long int repMinimum; +}; + +/** +An eoIntBound bounded from above only + * + * @ingroup Real + * @ingroup Bounds +*/ +class eoIntAboveBound : public eoIntBounds +{ +public : + virtual ~eoIntAboveBound(){} + + /** + Simple bounds = minimum + */ + eoIntAboveBound(long int _max=0) : + repMaximum(_max) + {} + + // accessors + virtual long int maximum() const { return repMaximum; } + + virtual long int minimum() const + { + throw std::logic_error("Trying to get minimum of eoIntAboveBound"); + } + virtual long int range() const + { + throw std::logic_error("Trying to get range of eoIntAboveBound"); + } + + virtual double uniform(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in eoIntAboveBound"); + } + + virtual long int random(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in eoIntAboveBound"); + } + + // description + virtual bool isBounded(void) const {return false;} + virtual bool hasNoBoundAtAll(void) const {return false;} + virtual bool isMinBounded(void) const {return false;} + virtual bool isMaxBounded(void) const {return true;} + + // says if a given double is within the bounds + virtual bool isInBounds(double _r) const + { + if (_r > repMaximum) + return false; + return true; + } + + // folds a value into bounds + virtual void foldsInBounds(double & _r) const + { + // easy as a pie: symmetry w.r.t. maximum + if (_r > repMaximum) // nothing to do otherwise + _r = 2*repMaximum - _r; + return ; + } + + // truncates to the bounds + virtual void truncate(double & _r) const + { + if (_r > repMaximum) + _r = repMaximum; + return; + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoIntVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoIntAboveBound::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[-inf," << repMaximum << "]"; + } + + /** for memory managements - ugly */ + virtual eoIntBounds * dup() const + { + return new eoIntAboveBound(*this); + } + +private : + long int repMaximum; +}; + +//////////////////////// tentative for a general BOUND class that is constructed from a string + +/** A class that encapsulate all possible eoIntBounds. + * Mandatory in order to read through the parser + * + * @ingroup Real + * @ingroup Bounds + */ +class eoGeneralIntBounds : public eoIntBounds +{ +public: + /** Ctor: from a string, chooses the type of bound */ + eoGeneralIntBounds(std::string _s = "[-infinity,+infinity]") + { + repBound = getBoundsFromString(_s); + } + + /** Need a Cpy Ctor because we are allocating memory */ + eoGeneralIntBounds(const eoGeneralIntBounds & _b) : eoIntBounds(_b) + { + // replicate the embedded bound (I'm pretty sure there is another + // way to do that !!! + + bool minBounded = _b.isMinBounded(); + bool maxBounded = _b.isMaxBounded(); + long int minimum, maximum; + const eoIntBounds & bb = _b.theBounds(); + if (minBounded) minimum = bb.minimum(); + if (maxBounded) maximum = bb.maximum(); + + if (minBounded && maxBounded) + repBound = new eoIntInterval(minimum, maximum); + else if (!minBounded && !maxBounded) // no bound at all + repBound = new eoIntNoBounds; + else if (!minBounded && maxBounded) + repBound = new eoIntAboveBound(maximum); + else if (minBounded && !maxBounded) + repBound = new eoIntBelowBound(minimum); + } + + eoGeneralIntBounds& operator=(const eoGeneralIntBounds& _b) + { + // replicate the embedded bound (I'm pretty sure there is another + // way to do that !!! + + bool minBounded = _b.isMinBounded(); + bool maxBounded = _b.isMaxBounded(); + long int minimum, maximum; + const eoIntBounds & bb = _b.theBounds(); + if (minBounded) minimum = bb.minimum(); + if (maxBounded) maximum = bb.maximum(); + + // first delete the embedded bounds if necessary + if (repBound) + delete repBound; + // now reallocate + if (minBounded && maxBounded) + repBound = new eoIntInterval(minimum, maximum); + else if (!minBounded && !maxBounded) // no bound at all + repBound = new eoIntNoBounds; + else if (!minBounded && maxBounded) + repBound = new eoIntAboveBound(maximum); + else if (minBounded && !maxBounded) + repBound = new eoIntBelowBound(minimum); + return (*this); + } + + + /** Need a Dtor because we allocate an actual bound */ + ~eoGeneralIntBounds() + { + delete repBound; + } + + ///// and now all methods from the embedded bounds + /** Self-Test: true if ***both*** a min and a max + */ + virtual bool isBounded(void) const {return repBound->isBounded();} + + /** Self-Test: true if no min ***and*** no max + * hence no further need to test/truncate/fold anything + */ + virtual bool hasNoBoundAtAll(void) const {return repBound->hasNoBoundAtAll();} + + /** Self-Test: bounded from below??? + */ + virtual bool isMinBounded(void) const {return repBound->isMinBounded();} + + /** Self-Test: bounded from above??? + */ + virtual bool isMaxBounded(void) const {return repBound->isMaxBounded();} + + /** Test on a value: is it in bounds? + */ + virtual bool isInBounds(double _x) const {return repBound->isInBounds(_x);} + + /** Put value back into bounds - by folding back and forth + */ + virtual void foldsInBounds(double & _x) const {return repBound->foldsInBounds(_x);} + + /** Put value back into bounds - by truncating to a boundary value + */ + virtual void truncate(double & _x) const {return repBound->truncate(_x);} + + /** get minimum value + * std::exception if does not exist + */ + virtual long int minimum() const {return repBound->minimum();} + /** get maximum value + * std::exception if does not exist + */ + virtual long int maximum() const {return repBound->maximum();} + /** get range + * std::exception if unbounded + */ + virtual long int range() const {return repBound->range();} + + /** random generator of uniform doubles in bounds + * std::exception if unbounded + */ + virtual double uniform(eoRng & _rng = eo::rng) const {(void)_rng; return repBound->uniform();} + + /** random generator of uniform ints in bounds + * std::exception if unbounded + */ + virtual long int random(eoRng & _rng = eo::rng) const {(void)_rng; return repBound->random();} + + /** for memory managements - ugly */ + virtual eoIntBounds * dup() const {return repBound->dup();} + + /** for efficiency, it's better to use the embedded boud directly */ + const eoIntBounds & theBounds() const { return *repBound;} + + /** don't forget the printOn method - + * again that of the embedded bound + */ + virtual void printOn(std::ostream& _os) const + { + repBound->printOn(_os); + } + + /** no readFrom ??? Have to check that later */ + virtual void readFrom(std::istream& _is) + { + std::string s; + _is >> s; + if (repBound) + delete repBound; + repBound = getBoundsFromString(s); + } + +private: + // reading from a string + eoIntBounds * getBoundsFromString(std::string); + + eoIntBounds * repBound; +}; + + +#endif diff --git a/deprecated/eo/src/utils/eoLogger.cpp b/deprecated/eo/src/utils/eoLogger.cpp new file mode 100644 index 000000000..f052d7955 --- /dev/null +++ b/deprecated/eo/src/utils/eoLogger.cpp @@ -0,0 +1,225 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/* + +(c) Thales group, 2010 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; + version 2 of the license. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: +Johann Dréo +Caner Candan + +*/ + +#ifdef _WIN32 +#include +#else // _WIN32 +#include +#endif // ! _WIN32 + +#include +#include +#include // used to define EOF + +#include + +#include "eoLogger.h" + +void eoLogger::_init() +{ + _standard_io_streams[&std::cout] = 1; + _standard_io_streams[&std::clog] = 2; + _standard_io_streams[&std::cerr] = 2; + + // /!\ If you want to add a level dont forget to add it at the header file in the enumerator Levels + + addLevel("quiet", eo::quiet); + addLevel("errors", eo::errors); + addLevel("warnings", eo::warnings); + addLevel("progress", eo::progress); + addLevel("logging", eo::logging); + addLevel("debug", eo::debug); + addLevel("xdebug", eo::xdebug); +} + +eoLogger::eoLogger() : + std::ostream(&_obuf), + + _verbose("quiet", "verbose", "Set the verbose level", 'v'), + _printVerboseLevels(false, "print-verbose-levels", "Print verbose levels", 'l'), + _output("", "output", "Redirect a standard output to a file", 'o'), + + _selectedLevel(eo::progress), + _contextLevel(eo::quiet), + _fd(2), + _obuf(_fd, _contextLevel, _selectedLevel) +{ + _init(); +} + +eoLogger::eoLogger(eo::file file) : + std::ostream(&_obuf), + + _verbose("quiet", "verbose", "Set the verbose level", 'v'), + _printVerboseLevels(false, "print-verbose-levels", "Print verbose levels", 'l'), + _output("", "output", "Redirect a standard output to a file", 'o'), + + _selectedLevel(eo::progress), + _contextLevel(eo::quiet), + _fd(2), + _obuf(_fd, _contextLevel, _selectedLevel) +{ + _init(); + *this << file; +} + +eoLogger::~eoLogger() +{ + if (_fd > 2) { ::close(_fd); } +} + +void eoLogger::_createParameters( eoParser& parser ) +{ + //------------------------------------------------------------------ + // we are saying to eoParser to create the parameters created above. + //------------------------------------------------------------------ + + std::string section("Logger"); + parser.processParam(_verbose, section); + parser.processParam(_printVerboseLevels, section); + parser.processParam(_output, section); + + //------------------------------------------------------------------ + + + //------------------------------------------------------------------ + // we're gonna redirect the log to the given filename if -o is used. + //------------------------------------------------------------------ + + if ( ! _output.value().empty() ) + { + eo::log << eo::file( _output.value() ); + } + + //------------------------------------------------------------------ + + + //------------------------------------------------------------------ + // we're gonna print the list of levels if -l parameter is used. + //------------------------------------------------------------------ + + if ( _printVerboseLevels.value() ) + { + eo::log.printLevels(); + } + + //------------------------------------------------------------------ +} + +std::string eoLogger::className() const +{ + return ("eoLogger"); +} + +void eoLogger::addLevel(std::string name, eo::Levels level) +{ + _levels[name] = level; + _sortedLevels.push_back(name); +} + +void eoLogger::printLevels() const +{ + std::cout << "Available verbose levels:" << std::endl; + + for (std::vector::const_iterator it = _sortedLevels.begin(), end = _sortedLevels.end(); + it != end; ++it) + { + std::cout << "\t" << *it << std::endl; + } + + ::exit(0); +} + +eoLogger& operator<<(eoLogger& l, const eo::Levels lvl) +{ + l._contextLevel = lvl; + return l; +} + +eoLogger& operator<<(eoLogger& l, eo::file f) +{ + l._fd = ::open(f._f.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0644); + return l; +} + +eoLogger& operator<<(eoLogger& l, eo::setlevel v) +{ + l._selectedLevel = (v._lvl < 0 ? l._levels[v._v] : v._lvl); + return l; +} + +eoLogger& operator<<(eoLogger& l, std::ostream& os) +{ + if (l._standard_io_streams.find(&os) != l._standard_io_streams.end()) + { + l._fd = l._standard_io_streams[&os]; + } + return l; +} + +eoLogger::outbuf::outbuf(const int& fd, + const eo::Levels& contexlvl, + const eo::Levels& selectedlvl) + : _fd(fd), _contextLevel(contexlvl), _selectedLevel(selectedlvl) +{} + +int eoLogger::outbuf::overflow(int_type c) +{ + if (_selectedLevel >= _contextLevel) + { + if (_fd >= 0 && c != EOF) + { + ::write(_fd, &c, 1); + } + } + return c; +} + +namespace eo +{ + file::file(const std::string f) + : _f(f) + {} + + setlevel::setlevel(const std::string v) + : _v(v), _lvl((Levels)-1) + {} + + setlevel::setlevel(const Levels lvl) + : _v(std::string("")), _lvl(lvl) + {} +} + +void make_verbose(eoParser& parser) +{ + eo::log._createParameters( parser ); + + eo::log << eo::setlevel(eo::log._verbose.value()); +} + +eoLogger eo::log; diff --git a/deprecated/eo/src/utils/eoLogger.h b/deprecated/eo/src/utils/eoLogger.h new file mode 100644 index 000000000..e5faf8f34 --- /dev/null +++ b/deprecated/eo/src/utils/eoLogger.h @@ -0,0 +1,288 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/* +(c) Thales group, 2010 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; + version 2 of the License. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: +Johann Dréo +Caner Candan + +*/ + +/** @defgroup Logging Logging + * @ingroup Utilities + + Global logger for EO. + + Here's an example explaning how to use eoLogger: +\code + #include + + int main(int ac, char** av) + { + // We are declaring the usual eoParser class + eoParser parser(ac, av); + + // This call is important to allow -v parameter to change user level. + make_verbose(parser); + + // At this time we are switching to warning message and messages + // which are going to follow it are going to be warnings message too. + // These messages can be displayed only if the user level (sets with + // eo::setlevel function) is set to eo::warnings. + eo::log << eo::warnings; + + // With the following eo::file function we are defining that + // all future logs are going to this new file resource which is + // test.txt + eo::log << eo::file("test.txt") << "In FILE" << std::endl; + + // Now we are changing again the resources destination to cout which + // is the standard output. + eo::log << std::cout << "In COUT" << std::endl; + + // Here are 2 differents examples of how to set the errors user level + // in using either a string or an identifier. + eo::log << eo::setlevel("errors"); + eo::log << eo::setlevel(eo::errors); + + // Now we are writting a message, that will be displayed only if we are above the "quiet" level + eo::log << eo::quiet << "1) Must be in quiet mode to see that" << std::endl; + + // And so on... + eo::log << eo::setlevel(eo::warnings) << eo::warnings << "2) Must be in warnings mode to see that" << std::endl; + + eo::log << eo::setlevel(eo::logging); + + eo::log << eo::errors; + eo::log << "3) Must be in errors mode to see that"; + eo::log << std::endl; + + eo::log << eo::debug << 4 << ')' + << " Must be in debug mode to see that\n"; + + return 0; + } +\endcode + +@{ +*/ + +#ifndef eoLogger_h +#define eoLogger_h + +#include +#include +#include +#include + +#include "eoObject.h" +#include "eoParser.h" + +namespace eo +{ + /** + * Levels contents all the available levels in eoLogger + * + * /!\ If you want to add a level dont forget to add it at the implementation of the class eoLogger in the ctor + */ + enum Levels {quiet = 0, + errors, + warnings, + progress, + logging, + debug, + xdebug}; + + /** + * file + * this structure combined with the friend operator<< below is an easy way to select a file as output. + */ + struct file + { + file(const std::string f); + const std::string _f; + }; + + /** + * setlevel + * this structure combined with the friend operator<< below is an easy way to set a verbose level. + */ + struct setlevel + { + setlevel(const std::string v); + setlevel(const Levels lvl); + const std::string _v; + const Levels _lvl; + }; +} + +/** + * eoLogger + * Class providing a verbose management through EO + * Use of a global variable eo::log to easily use the logger like std::cout + */ +class eoLogger : public eoObject, + public std::ostream +{ +public: + //! default ctor + eoLogger(); + + //! overidded ctor in order to instanciate a logger with a file define in parameter + eoLogger(eo::file file); + + //! dtor + ~eoLogger(); + + //! common function for all eo objects + virtual std::string className() const; + + //! Print the available levels on the standard output + //! enablable with the option -l + void printLevels() const; + + /*! Returns the selected levels, that is the one asked by the user + * + * Use this function if you want to be able to compare selected levels to a given one, like: + * if( eo::log.getLevelSelected() >= eo::progress ) {...} + */ + inline eo::Levels getLevelSelected() const { return _selectedLevel; } + + /*! Returns the current level of the context + * the one given when you output message with the logger + */ + inline eo::Levels getLevelContext() const { return _contextLevel; } + +protected: + //! in order to add a level of verbosity + void addLevel(std::string name, eo::Levels level); + +private: + //! used by the function make_verbose in order to add options to specify the verbose level + void _createParameters( eoParser& ); + + //! used by the set of ctors to initiate some useful variables + void _init(); + +private: + /** + * outbuf + * this class inherits from std::streambuf which is used by eoLogger to write the buffer in an output stream + */ + class outbuf : public std::streambuf + { + public: + outbuf(const int& fd, const eo::Levels& contexlvl, const eo::Levels& selectedlvl); + protected: + virtual int overflow(int_type c); + private: + const int& _fd; + const eo::Levels& _contextLevel; + const eo::Levels& _selectedLevel; + }; + +private: + /** + * MapLevel is the type used by the map member _levels. + */ + typedef std::map MapLevel; + +public: + /** + * operator<< used there to set a verbose mode. + */ + //! in order to use stream style to define the context verbose level where the following logs will be saved + friend eoLogger& operator<<(eoLogger&, const eo::Levels); + + /** + * operator<< used there to set a filename through the class file. + */ + //! in order to use stream style to define a file to dump instead the standart output + friend eoLogger& operator<<(eoLogger&, eo::file); + + /** + * operator<< used there to set a verbose level through the class setlevel. + */ + //! in order to use stream style to define manually the verbose level instead using options + friend eoLogger& operator<<(eoLogger&, eo::setlevel); + + /** + * operator<< used there to be able to use std::cout to say that we wish to redirect back the buffer to a standard output. + */ + //! in order to use stream style to go back to a standart output defined by STL + //! and to get retro-compatibility + friend eoLogger& operator<<(eoLogger&, std::ostream&); + +private: + friend void make_verbose(eoParser&); + + eoValueParam _verbose; + eoValueParam _printVerboseLevels; + eoValueParam _output; + + /** + * _selectedLevel is the member storing verbose level setted by the user thanks to operator() + */ + eo::Levels _selectedLevel; + eo::Levels _contextLevel; + + /** + * _fd in storing the file descriptor at this place we can disable easily the buffer in + * changing the value at -1. It is used by operator <<. + */ + int _fd; + + /** + * _obuf std::ostream mandates to use a buffer. _obuf is a outbuf inheriting of std::streambuf. + */ + outbuf _obuf; + + /** + * _levels contains all the existing level order by position + */ + MapLevel _levels; + + /** + * _levelsOrder is just a list to keep the order of levels + */ + std::vector _sortedLevels; + + /** + * _standard_io_streams + */ + std::map< std::ostream*, int > _standard_io_streams; +}; +/** @example t-eoLogger.cpp + */ + +//! make_verbose gets level of verbose and sets it in eoLogger +void make_verbose(eoParser&); + +namespace eo +{ + /** + * log is an external global variable defined to easily use a same way than std::cout to write a log. + */ + extern eoLogger log; +} + +/** @} */ + +#endif // !eoLogger_h diff --git a/deprecated/eo/src/utils/eoMOFitnessStat.h b/deprecated/eo/src/utils/eoMOFitnessStat.h new file mode 100644 index 000000000..8e1b2d3fd --- /dev/null +++ b/deprecated/eo/src/utils/eoMOFitnessStat.h @@ -0,0 +1,91 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFitnessStat.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFitnessStat_h +#define _eoFitnessStat_h + +#include + +/** + The fitnesses of a whole population, as a vector +*/ +template +class eoFitnessStat : public eoSortedStat > +{ +public : + + using eoSortedStat >::value; + + eoFitnessStat(std::string _description = "AllFitnesses") : + eoSortedStat >(std::vector(0), _description) {} + + virtual void operator()(const std::vector& _popPters) + { + value().resize(_popPters.size()); + for (unsigned i=0; i<_popPters.size(); i++) + value()[i] = _popPters[i]->fitness(); + } +}; + + +/** For multi-objective fitness, we need to translate a stat > + into a vector, so each objective gets a seperate stat +*/ +#ifdef _MSC_VER +// The follownig is needed to avoid some bug in Visual Studio 6.0 +typedef double PartFitDefault; +template +class eoMOFitnessStat : public eoSortedStat > +#else +template +class eoMOFitnessStat : public eoSortedStat > +#endif + +{ +public: + + using eoSortedStat >::value; + + /** Ctor: say what component you want + */ + eoMOFitnessStat(unsigned _objective, std::string _description = "MO-Fitness") : + eoSortedStat >(std::vector(0), _description), + objective(_objective) {} + + virtual void operator()(const std::vector& _popPters) + { + value().resize(_popPters.size()); + + for (unsigned i=0; i<_popPters.size(); i++) + { + value()[i] = _popPters[i]->fitness()[objective]; + } + } +private: + unsigned int objective; // The objective we're storing + +}; +#endif diff --git a/deprecated/eo/src/utils/eoMonitor.h b/deprecated/eo/src/utils/eoMonitor.h new file mode 100644 index 000000000..1c92e9c00 --- /dev/null +++ b/deprecated/eo/src/utils/eoMonitor.h @@ -0,0 +1,80 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ + +#ifndef _eoMonitor_h +#define _eoMonitor_h + + +#include +#include +#include + +/** @defgroup Monitors Monitoring + * + * Monitors take a set of value parameters (eoValueParam) objects and + * output them on a given stream, file, pipe, etc. + * + * They can be called from within an eoCheckPoint, to print different values + * of parameters or of eoStat at each generation. + * + * @see eoCheckPoint + * @see eoStat + * @ingroup Utilities + */ + + +class eoParam; +template class eoCheckPoint; + +/** + The abstract monitor class is a std::vector of parameter pointers. Use + either push_back a pointer or add a reference to a parameter. + Derived classes will then implement the operator()(void) which + will stream or pipe the current values of the parameters to wherever you + want it streamed or piped to. + + @ingroup Monitors +*/ +class eoMonitor : public eoF +{ +public : + + virtual void lastCall() {} + + /** + Adds a parameter to the monitor. It is virtual so you can do some type checking + in derived classes if you must. + */ + virtual void add(const eoParam& _param) { vec.push_back(&_param); } + + virtual std::string className(void) const { return "eoMonitor"; } + + template + eoMonitor& addTo(eoCheckPoint& cp) { cp.add(*this); return *this; } + +protected : + typedef std::vector::iterator iterator; + std::vector vec; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoOStreamMonitor.cpp b/deprecated/eo/src/utils/eoOStreamMonitor.cpp new file mode 100644 index 000000000..3365301e9 --- /dev/null +++ b/deprecated/eo/src/utils/eoOStreamMonitor.cpp @@ -0,0 +1,58 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +//using namespace std; + +eoMonitor& eoOStreamMonitor::operator()(void) +{ + if (!out) { + std::string str = "eoOStreamMonitor: Could not write to the ooutput stream"; + throw std::runtime_error(str); + } + + if (firsttime) { + + eo::log << eo::debug << "First Generation" << std::endl; + + for (iterator it = vec.begin (); it != vec.end (); ++it) { + out << (*it)->longName (); + out << delim << std::left << std::setfill(fill) << std::setw(width); + } + out << std::endl; + + firsttime = false; + } // if firstime + + // ok, now the real saving. write out + //! @todo old verbose formatting, do we still need it? + /* + for (iterator it = vec.begin (); it != vec.end (); ++it) { + // name: value + out << (*it)->longName () << ": " << (*it)->getValue () << std::endl; + } // for it in vec + */ + + for (iterator it = vec.begin (); it != vec.end (); ++it) { + // value only + out << (*it)->getValue (); + out << delim << std::left << std::setfill(fill) << std::setw(width); + } // for it in vec + + out << std::endl; + eo::log << eo::debug << "End of Generation" << std::endl; + + return *this; +} diff --git a/deprecated/eo/src/utils/eoOStreamMonitor.h b/deprecated/eo/src/utils/eoOStreamMonitor.h new file mode 100644 index 000000000..b941b05f2 --- /dev/null +++ b/deprecated/eo/src/utils/eoOStreamMonitor.h @@ -0,0 +1,72 @@ +/* + +(c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +(c) Thales group, 2010 + + This library is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free + Software Foundation; version 2 of the license. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along + with this library; if not, write to the Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: + todos@geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + Johann Dréo +*/ + +#ifndef _eoOStreamMonitor_h_ +#define _eoOStreamMonitor_h_ + +#include +#include + +#include +#include +#include + +/** + Prints statistics to a given ostream. + + You can pass any instance of an ostream to the constructor, like, for example, std::clog. + + @ingroup Monitors +*/ +class eoOStreamMonitor : public eoMonitor +{ +public : + eoOStreamMonitor( std::ostream & _out, bool /*_verbose*/=true, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) + { +#ifndef DEPRECATED_MESSAGES + eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release" << std::endl; +#pragma message "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release" +#endif // !DEPRECATED_MESSAGES + } + + eoOStreamMonitor( std::ostream & _out, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) + {} + + eoMonitor& operator()(void); + + virtual std::string className(void) const { return "eoOStreamMonitor"; } + +private : + std::ostream & out; + std::string delim; + unsigned int width; + char fill; + bool firsttime; +}; + +#endif // _eoOStreamMonitor_h_ diff --git a/deprecated/eo/src/utils/eoParallel.cpp b/deprecated/eo/src/utils/eoParallel.cpp new file mode 100644 index 000000000..d9d09c38b --- /dev/null +++ b/deprecated/eo/src/utils/eoParallel.cpp @@ -0,0 +1,115 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/* + +(c) Thales group, 2010 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; + version 2 of the license. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: +Caner Candan + +*/ + +#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' ), + _doMeasure( false, "parallelize-do-measure", "Do some measures during execution", '\0' ), + _t_start(0) +{ +} + +eoParallel::~eoParallel() +{ +#ifdef _OPENMP + if ( doMeasure() ) + { + double _t_end = omp_get_wtime(); + eoLogger log; + log << eo::file("measure_" + prefix()) << _t_end - _t_start << std::endl; + } +#endif // !_OPENMP +} + +std::string eoParallel::className() const +{ + return "eoParallel"; +} + +std::string eoParallel::prefix() const +{ + std::string value( _prefix.value() ); + + if ( _isEnabled.value() ) + { + if ( _isDynamic.value() ) + { + value += "_dynamic.out"; + } + else + { + value += "_parallel.out"; + } + } + else + { + value += "_sequential.out"; + } + + return value; +} + +void eoParallel::_createParameters( eoParser& parser ) +{ + std::string section("Parallelization"); + parser.processParam( _isEnabled, section ); + parser.processParam( _isDynamic, section ); + parser.processParam( _prefix, section ); + parser.processParam( _nthreads, section ); + parser.processParam( _enableResults, section ); + parser.processParam( _doMeasure, section ); +} + +void make_parallel(eoParser& parser) +{ + eo::parallel._createParameters( parser ); + +#ifdef _OPENMP + if ( eo::parallel.isEnabled() ) + { + if ( eo::parallel.nthreads() > 0 ) + { + omp_set_num_threads( eo::parallel.nthreads() ); + } + } + + if ( eo::parallel.doMeasure() ) + { + eo::parallel._t_start = omp_get_wtime(); + } +#endif // !_OPENMP +} + +eoParallel eo::parallel; diff --git a/deprecated/eo/src/utils/eoParallel.h b/deprecated/eo/src/utils/eoParallel.h new file mode 100644 index 000000000..3f22f6c43 --- /dev/null +++ b/deprecated/eo/src/utils/eoParallel.h @@ -0,0 +1,88 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/* +(c) Thales group, 2010 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; + version 2 of the License. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + +Authors: +Caner Candan + +*/ + +/** @defgroup Parallel Parallel + * @ingroup Utilities + @{ +*/ + +#ifndef eoParallel_h +#define eoParallel_h + +#include "eoObject.h" +#include "eoParser.h" + +/** + * eoParallel + * Class providing parameters for parallelization + * Use of a global variable eo::parallel to easily use the parallelization parameters anywhere + */ +class eoParallel : public eoObject +{ +public: + eoParallel(); + ~eoParallel(); + + virtual std::string className() const; + + inline bool isEnabled() const { return _isEnabled.value(); } + inline bool isDynamic() const { return _isDynamic.value(); } + + std::string prefix() const; + + inline unsigned int nthreads() const { return _nthreads.value(); } + + inline bool enableResults() const { return _enableResults.value(); } + inline bool doMeasure() const { return _doMeasure.value(); } + + friend void make_parallel(eoParser&); + +private: + void _createParameters( eoParser& ); + +private: + eoValueParam _isEnabled; + eoValueParam _isDynamic; + eoValueParam _prefix; + eoValueParam _nthreads; + eoValueParam _enableResults; + eoValueParam _doMeasure; + double _t_start; +}; + +void make_parallel(eoParser&); + +namespace eo +{ + /** + * parallel is an external global variable defined in order to use where ever you want the parallel parameters + */ + extern eoParallel parallel; +} + +/** @} */ + +#endif // !eoParallel_h diff --git a/deprecated/eo/src/utils/eoParam.h b/deprecated/eo/src/utils/eoParam.h new file mode 100644 index 000000000..948092c93 --- /dev/null +++ b/deprecated/eo/src/utils/eoParam.h @@ -0,0 +1,486 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoParam.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk +*/ +//----------------------------------------------------------------------------- + +#ifndef eoParam_h +#define eoParam_h + +#include +#include +#include +#include +#include +#include +#include + +/** @defgroup Parameters Parameters management + * + * A parameter is basically an object that stores a value and that can read/print it from/on streams. + * + * It is mainly used for command-line options (see eoParser) and eoStat. + * + * @ingroup Utilities + * @{ + */ + +/** + eoParam: Base class for monitoring and parsing parameters +*/ +class eoParam +{ +public: + + /** Empty constructor - called from outside any parser */ + eoParam () + : repLongName(""), repDefault(""), repDescription(""), + repShortHand(0), repRequired(false) + {} + + /** Construct a Param. + * + * @param _longName Long name of the argument + * @param _default The default value + * @param _description Description of the parameter. What is useful for. + * @param _shortName Short name of the argument (Optional) + * @param _required If it is a necessary parameter or not + */ + eoParam (std::string _longName, std::string _default, + std::string _description, char _shortName = 0, bool _required = false) + : repLongName(_longName), repDefault(_default), + repDescription(_description ), + repShortHand(_shortName), repRequired( _required) + {} + + /** + * Virtual destructor is needed. + */ + virtual ~eoParam () {} + + /** + * Pure virtual function to get the value out. + */ + virtual std::string getValue () const = 0; + + /** + * Pure virtual function to set the value + */ + virtual void setValue(const std::string& _value) = 0 ; + + /** + * Returns the short name. + */ + char shortName() const { return repShortHand; }; + + /** + * Returns the long name. + */ + const std::string& longName() const { return repLongName; }; + + /** + * Returns the description of the argument + */ + const std::string& description() const { return repDescription; }; + + /** + * Returns the default value of the argument + */ + const std::string& defValue() const { return repDefault; }; + + /** + * Sets the default value of the argument, + */ + void defValue( const std::string& str ) { repDefault = str; }; + + /** + * ALlows to change the name (see the prefix in eoParser.h) + */ + void setLongName(std::string _longName) { repLongName = _longName;} + + /** + * Returns if required or not. + */ + bool required() const { return repRequired; }; + +private: + std::string repLongName; + std::string repDefault; + std::string repDescription; + char repShortHand; + bool repRequired; +}; + + + +/** + eoValueParam: templatized derivation of eoParam. Can be used to contain + any scalar value type. It makes use of std::strstream to get and set values. + + @todo This should be changed to std::stringstream when that class is available in g++. + + Note also that there is a template specialization for std::pair and + for std::vector. These stream their contents delimited with whitespace. +*/ +template +class eoValueParam : public eoParam +{ +public : + + /** Construct a Param. */ + eoValueParam(void) : eoParam() {} + + /** Construct a Param. + * + * @param _defaultValue The default value + * @param _longName Long name of the argument + * @param _description Description of the parameter. What is useful for. + * @param _shortHand Short name of the argument (Optional) + * @param _required If it is a necessary parameter or not + */ + eoValueParam(ValueType _defaultValue, + std::string _longName, + std::string _description = "No description", + char _shortHand = 0, + bool _required = false) + : eoParam(_longName, "", _description, _shortHand, _required), + repValue(_defaultValue) + { + eoParam::defValue(getValue()); + } + + /** Get a reference on the parameter value + + @return parameter value + */ + ValueType& value() { return repValue; } + + /** Get a const reference on the parameter value + + @overload + + @return parameter value + */ + const ValueType& value() const { return repValue; } + + + /** Change the parameter value + */ + void value( ValueType val ) + { + // convert to string + std::ostringstream os; + os << val; + + // convert to ValueType + std::istringstream is( os.str() ); + is >> repValue; + } + + + /** Get the string representation of the value + */ + std::string getValue(void) const + { + std::ostringstream os; + os << repValue; + return os.str(); + } + + + /** @brief Set the value according to the speciied string + + For scalar types the textual represenation is typically quite + straigtforward. + + For vector we expect a list of numbers, where the first is + an unsigned integer taken as the length ot the vector and then + successively the vector elements. Vector elements can be separated + by ',', ';', or ' '. Note, however, that eoParser does not deal + correctly with parameter values contianing spaces (' '). + + @param _value Textual representation of the new value + */ + void setValue(const std::string& _value) + { + std::istringstream is(_value); + is >> repValue; + } + +protected: + + ValueType repValue; +}; + +/* + Specialization for std::string +*/ +template <> +inline std::string eoValueParam::getValue() const +{ + return repValue; +} + + +template <> +inline void eoValueParam::setValue(const std::string& _value) +{ + if (_value.empty()) + { + repValue = true; + return; + } + std::istringstream is(_value); + is >> repValue; +} + + +/// Because MSVC does not support partial specialization, the std::pair is a double, not a T +template <> +inline std::string eoValueParam >::getValue(void) const +{ + // use own buffer as MSVC's buffer leaks! + std::ostringstream os; + os << repValue.first << ' ' << repValue.second; + return os.str(); +} + +/// Because MSVC does not support partial specialization, the std::pair is a double, not a T +template <> +inline void eoValueParam >::setValue(const std::string& _value) +{ + std::istringstream is(_value); + is >> repValue.first; + is >> repValue.second; +} + +// The std::vector > +////////////////////////////////// +/// Because MSVC does not support partial specialization, the std::vector is a std::vector of doubles, not a T +template <> +inline std::string eoValueParam > >::getValue(void) const +{ + std::ostringstream os; + os << repValue.size() << ' '; + for (unsigned i = 0; i < repValue.size(); ++i) + { + os << repValue[i].size() << ' '; + std::copy(repValue[i].begin(), repValue[i].end(), std::ostream_iterator(os, " ")); + } + return os.str(); +} + +/// Because MSVC does not support partial specialization, the std::vector is a std::vector of doubles, not a T +template <> +inline void eoValueParam > >::setValue(const std::string& _value) +{ + std::istringstream is(_value); + unsigned i,j,sz; + is >> sz; + repValue.resize(sz); + + for (i = 0; i < repValue.size(); ++i) + { + unsigned sz2; + is >> sz2; + repValue[i].resize(sz2); + for (j = 0; j < sz2; ++j) + { + is >> repValue[i][j]; + } + } +} + +// The std::vector +////////////////////////////////// +/// Because MSVC does not support partial specialization, the std::vector is a double, not a T +template <> +inline std::string eoValueParam >::getValue(void) const +{ + std::ostringstream os; + os << repValue.size() << ' '; + std::copy(repValue.begin(), repValue.end(), std::ostream_iterator(os, " ")); + return os.str(); +} + +/// Because MSVC does not support partial specialization, the std::vector is a double, not a T +template <> +inline void eoValueParam >::setValue(const std::string& _value) +{ + static const std::string delimiter(",;"); + std::istringstream is(_value); + unsigned sz; + is >> sz; + repValue.resize(sz); + for(unsigned i=0; i> c; + } while((std::string::npos != delimiter.find(c)) && (! is.eof())); + is >> repValue[i]; + } +} + +// The std::vector +////////////////////////////////// +/// Because MSVC does not support partial specialization, the std::vector is a eoMinimizingFitness, not a T +template <> +inline std::string eoValueParam >::getValue(void) const +{ + std::ostringstream os; + os << repValue.size() << ' '; + std::copy(repValue.begin(), repValue.end(), std::ostream_iterator(os, " ")); + return os.str(); +} + +/// Because MSVC does not support partial specialization, the std::vector is a eoMinimizingFitness, not a T +// NOTE: g++ doesn support it either!!! +template <> +inline void eoValueParam >::setValue(const std::string& _value) +{ + std::istringstream is(_value); + unsigned sz; + is >> sz; + repValue.resize(sz); + std::copy(std::istream_iterator(is), std::istream_iterator(), repValue.begin()); +} + +// The std::vector +////////////////////////////////// +template <> +inline std::string eoValueParam >::getValue(void) const +{ + throw std::runtime_error("I cannot getValue for a std::vector"); + return std::string(""); +} + +template <> +inline void eoValueParam >::setValue(const std::string&) +{ + throw std::runtime_error("I cannot setValue for a std::vector"); + return; +} + +/*template + class eoContainerParam : public eoParam + { + public : + eoContainerParam (ContainerType& value, std::string _shortName, std::string _longName, + std::string _default, + std::string _description, + bool _required, + bool _change ) + : value(_value), eoParam(_shortName, _longName, _description, _default, _required, _change) + {} + + + // void setValue(const std::string & _value) + // { + // std::istd::stringstream is(_value); + // copy(std::istream_iterator(is), std::istream_iterator(), back_inserter(value)); + // } + + private : + ContainerType& value; + };*/ + +/** + * Another helper class for parsing parameters like + * Keyword(arg1, arg2, ...) + * + * It is basically a std::pair > + * first std::string is keyword + * the std::vector contains all arguments (as std::strings) + * See make_algo.h + */ + +class eoParamParamType : public std::pair > +{ +public: + eoParamParamType(std::string _value) + { + readFrom(_value); + } + + std::ostream & printOn(std::ostream & _os) const + { + _os << first; + unsigned narg = second.size(); + if (!narg) + return _os; + + // Here, we do have args + _os << "("; + if (narg == 1) // 1 arg only + { + _os << second[0] << ")" ; + return _os; + } + // and here more than 1 arg + for (unsigned i=0; i> value; + readFrom(value); + return _is; + } + + void readFrom(std::string & _value) + { + second.resize(0); // just in case + size_t pos = _value.find('('); + if (pos >= _value.size()) // no arguments + { + first = _value; + return; + } + // so here we do have arguments + std::string t = _value.substr(pos+1);// the arguments + _value.resize(pos); + first = _value; // done for the keyword (NOTE: may be empty std::string!) + + // now all arguments + std::string delim(" (),"); + while ( (pos=t.find_first_not_of(delim)) < t.size()) + { + size_t posEnd = t.find_first_of(delim, pos); + std::string u = t.substr(pos,posEnd);//(t, pos); + /*u.resize(posEnd - pos);*/ + second.push_back(u); + t = t.substr(posEnd+1); + } + } +}; + +// at the moment, the following are defined in eoParser.cpp +std::ostream & operator<<(std::ostream & _os, const eoParamParamType & _rate); +std::istream & operator>>(std::istream & _is, eoParamParamType & _rate); + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/eoParser.cpp b/deprecated/eo/src/utils/eoParser.cpp new file mode 100644 index 000000000..cc306bf73 --- /dev/null +++ b/deprecated/eo/src/utils/eoParser.cpp @@ -0,0 +1,451 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoParser.cpp +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net +Authors: + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + Johann Dréo + */ +//----------------------------------------------------------------------------- + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include + + +using namespace std; + +std::ostream& printSectionHeader(std::ostream& os, std::string section) +{ + if (section == "") + section = "General"; + + // convert each character to upper case + std::transform( section.begin(), section.end(), section.begin(), ::toupper); + + // the formating with setfill would not permits to add this extra space as + // one more call to stream operator, thus it is inserted here + section += ' '; + + // pretty print so as to print the section, followed by as many # as + // necessary to fill the line until 80 characters + os << std::endl + << "### " + << std::left + << std::setfill('#') + << std::setw(80) // TODO do not hard code the width of the line + << section + << std::endl; + return os; +} + +eoParameterLoader::~eoParameterLoader() +{ + for (unsigned i = 0; i < ownedParams.size(); ++i) + { + delete ownedParams[i]; + } +} + +eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, + string _lFileParamName, char _shortHand) : + programName(_argv[0]), + programDescription( _programDescription), + needHelpMessage( false ), + needHelp(false, "help", "Prints this message", 'h'), + stopOnUnknownParam(true, "stopOnUnknownParam", "Stop if unkown param entered", '\0') +{ + // need to process the param file first + // if we want command-line to have highest priority + unsigned i; + for (i = 1; i < _argc; ++i) + { + if(_argv[i][0] == '@') + { // read response file + char *pts = _argv[i]+1; // yes a char*, sorry :-) + ifstream ifs (pts); + ifs.peek(); // check if it exists + if (!ifs) + { + string msg = string("Could not open response file: ") + pts; + throw runtime_error(msg); + } + // read - will be overwritten by command-line + readFrom(ifs); + break; // stop reading command line args for '@' + } + } + // now read arguments on command-line + stringstream stream; + for (i = 1; i < _argc; ++i) + { + stream << _argv[i] << '\n'; + } + readFrom(stream); + processParam(needHelp); + processParam(stopOnUnknownParam); +} + + +std::string eoParser::get( const std::string & name) const +{ + return getParamWithLongName( name )->getValue(); +} + + +eoParam * eoParser::getParamWithLongName(const std::string& _name) const +{ + typedef std::multimap MultiMapType; + typedef MultiMapType::const_iterator iter; + std::string search(prefix+_name); + for(iter p = params.begin(); p != params.end(); ++p) + if(p->second->longName() == search) + return p->second; + return 0; +} + +eoParam * eoParser::getParam(const std::string& _name) const +{ + eoParam * p = getParamWithLongName( _name ); + if( p == NULL ) { + throw eoMissingParamException(_name ); + } else { + return p; + } +} + +void eoParser::processParam(eoParam& param, std::string section) +{ + // this param enters the parser: add the prefix to the long name + if (prefix != "") + { + param.setLongName(prefix+param.longName()); + section = prefix + section; // and to section + } + doRegisterParam(param); // plainly register it + params.insert(make_pair(section, ¶m)); +} + +void eoParser::doRegisterParam(eoParam& param) +{ + if (param.required() && !isItThere(param)) + { + string msg = "Required parameter: " + param.longName() + " missing"; + needHelpMessage = true; + messages.push_back(msg); + } + pair value = getValue(param); + if (value.first) + { + param.setValue(value.second); + } +} + +pair eoParser::getValue(eoParam& _param) const +{ + pair result(false, ""); + + if (_param.shortName() != 0) + { + map::const_iterator it = shortNameMap.find(_param.shortName()); + if (it != shortNameMap.end()) + { + result.second = it->second; + result.first = true; + return result; + } + } + map::const_iterator it = longNameMap.find(_param.longName()); + if (it != longNameMap.end()) + { + result.second = it->second; + result.first = true; + return result; + } + //! @todo check environment, just long names + return result; +} + +void eoParser::updateParameters() +{ + typedef MultiMapType::const_iterator It; + + for (It p = params.begin(); p != params.end(); ++p) + { + doRegisterParam(*p->second); + } +} + +void eoParser::readFrom(istream& is) +{ + string str; + // we must avoid processing \section{xxx} if xxx is NOT "Parser" + bool processing = true; + while (is >> str) + { + if (str.find(string("\\section{"))==0) // found section begin + processing = (str.find(string("Parser"))= 3) + value = string(str.begin() + 3, str.end()); + } + else + { + value = string(str.begin() + 2, str.end()); + } + } + + shortNameMap[str[1]] = value; + } + } + } + } + + updateParameters(); +} + +void eoParser::printOn(ostream& os) const +{ + typedef MultiMapType::const_iterator It; + + It p = params.begin(); + + std::string section = p->first; + + printSectionHeader(os, section); + //print every param with its value + for (; p != params.end(); ++p) + { + std::string newSection = p->first; + + if (newSection != section) + { + section = newSection; + printSectionHeader(os, section); + } + + eoParam* param = p->second; + + if (!isItThere(*param)) // comment out the ones not set by the user + os << "# "; + + string str = "--" + param->longName() + "=" + param->getValue(); + + os.setf(ios_base::left, ios_base::adjustfield); + os << setfill(' ') << setw(40) << str; + + os << setw(0) << " # "; + if (param->shortName()) + os << '-' << param->shortName() << " : "; + os << param->description(); + + if (param->required()) + { + os << " REQUIRED "; + } + + os << '\n'; + } +} + +void eoParser::printHelp(ostream& os) +{ + if (needHelp.value() == false && !messages.empty()) + { + std::copy(messages.begin(), messages.end(), ostream_iterator(os, "\n")); + messages.clear(); + return; + } + + // print program name and description + os << this->programName <<": "<< programDescription << "\n\n"; + + // print the usage when calling the program from the command line + os << "Usage: "<< programName<<" [Options]\n"; + // only short usage! + os << "Options of the form \"-f[=Value]\" or \"--Name[=value]\"" << endl; + + os << "Where:"<first; + + printSectionHeader(os, section); + + //print every param with its value + for (; p != params.end(); ++p) + { + std::string newSection = p->first; + + if (newSection != section) + { + section = newSection; + printSectionHeader(os, section); + } + + if (p->second->shortName()) + os << "-" << p->second->shortName() << ", "; + + os << "--" <second->longName() <<" :\t" + << p->second->description() ; + + os << " (" << ( (p->second->required())?"required":"optional" ); + os <<", default: "<< p->second->defValue() << ')' << std::endl; + } // for p + + os << "\n@param_file \t defines a file where the parameters are stored\n"; + os << '\n'; + +} + +bool eoParser::userNeedsHelp(void) +{ + /* + check whether there are long or short names entered + without a corresponding parameter + */ + // first, check if we want to check that ! + if (stopOnUnknownParam.value()) + { + // search for unknown long names + for (LongNameMapType::const_iterator lIt = longNameMap.begin(); lIt != longNameMap.end(); ++lIt) + { + string entry = lIt->first; + + MultiMapType::const_iterator it; + + for (it = params.begin(); it != params.end(); ++it) + { + if (entry == it->second->longName()) + { + break; + } + } + + if (it == params.end()) + { + string msg = "Unknown parameter: --" + entry + " entered"; + needHelpMessage = true; + messages.push_back(msg); + } + } // for lIt + + // search for unknown short names + for (ShortNameMapType::const_iterator sIt = shortNameMap.begin(); sIt != shortNameMap.end(); ++sIt) + { + char entry = sIt->first; + + MultiMapType::const_iterator it; + + for (it = params.begin(); it != params.end(); ++it) + { + if (entry == it->second->shortName()) + { + break; + } + } + + if (it == params.end()) + { + string entryString(1, entry); + string msg = "Unknown parameter: -" + entryString + " entered"; + needHelpMessage = true; + messages.push_back(msg); + } + } // for sIt + + if( needHelpMessage ) { + string msg = "Use -h or --help to get help about available parameters"; + messages.push_back( msg ); + } + + } // if stopOnUnknownParam + + return needHelp.value() || !messages.empty(); +} + +///////////////// I put these here at the moment +ostream & operator<<(ostream & _os, const eoParamParamType & _rate) +{ + _rate.printOn(_os); + return _os; +} + +istream & operator>>(istream & _is, eoParamParamType & _rate) +{ + _rate.readFrom(_is); + return _is; +} diff --git a/deprecated/eo/src/utils/eoParser.h b/deprecated/eo/src/utils/eoParser.h new file mode 100644 index 000000000..be680ab0c --- /dev/null +++ b/deprecated/eo/src/utils/eoParser.h @@ -0,0 +1,343 @@ +/* (c) Marc Schoenauer, Maarten Keijzer, GeNeura Team, Thales group + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) any +later version. + +This library is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 59 +Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net +Authors: + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + Johann Dréo +*/ + + +#ifndef EO_PARSER_H +#define EO_PARSER_H + +#include +#include +#include + +#include "eoParam.h" +#include "eoObject.h" +#include "eoPersistent.h" +#include "eoExceptions.h" + +/** Parameter saving and loading + +eoParameterLoader is an abstract class that can be used as a base for your own +parameter loading and saving. The command line parser eoParser is derived from +this class. + +@ingroup Parameters +*/ +class eoParameterLoader +{ +public : + + /** Need a virtual destructor */ + virtual ~eoParameterLoader(); + + /** Register a parameter and set its value if it is known + + @param param the parameter to process + @param section the section where this parameter belongs + */ + virtual void processParam(eoParam& param, std::string section = "") = 0; + + /** + * checks if _param has been actually entered + */ + virtual bool isItThere(eoParam& _param) const = 0; + + /** + * Construct a Param and sets its value. The loader will own the memory thus created + * + * @param _defaultValue The default value + * @param _longName Long name of the argument + * @param _description Description of the parameter. What is useful for. + * @param _shortHand Short name of the argument (Optional) + * @param _section Name of the section where the parameter belongs + * @param _required If it is a necessary parameter or not + */ + template + eoValueParam& createParam(ValueType _defaultValue, + std::string _longName, + std::string _description, + char _shortHand = 0, + std::string _section = "", + bool _required = false) + { + eoValueParam* p = new eoValueParam(_defaultValue, + _longName, + _description, + _shortHand, + _required); + ownedParams.push_back(p); + processParam(*p, _section); + return *p; + } + + +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 + parameter settings. + + Parameters can be read from argv, strings or streams, and must be specified + using the following convention: --name=value or -n=value + + You should not use space as a separator between the parameter and its value. + + @ingroup Parameters +*/ +class eoParser : public eoParameterLoader, public eoObject, public eoPersistent +{ + +public: + + /** + * Constructor + * a complete constructor that reads the command line an optionally reads + * a configuration file. + + * + * myEo --param-file=param.rc will then load using the parameter file param.rc + * + * @param _argc command line arguments count + * @param _argv command line parameters + * @param _programDescription Description of the work the program does + * @param _lFileParamName Name of the parameter specifying the configuration file (--param-file) + * @param _shortHand Single charachter shorthand for specifying the configuration file + */ + eoParser ( unsigned _argc, char **_argv , std::string _programDescription = "", + std::string _lFileParamName = "param-file", char _shortHand = 'p'); + + /** + Processes the parameter and puts it in the appropriate section for readability + */ + void processParam(eoParam& param, std::string section = ""); + + /** Read from a stream + * @param is the input stream + */ + void readFrom(std::istream& is); + + /** Pint on a stream + * @param os the output stream + */ + void printOn(std::ostream& os) const; + + /// className for readibility + std::string className(void) const { return "Parser"; } + + /// true if the user made an error or asked for help + bool userNeedsHelp(void); + /** + * Prints an automatic help in the specified output using the information + * provided by parameters + */ + void printHelp(std::ostream& os); + + std::string ProgramName() { return programName; } + + /** Has param been entered by user? + + Checks if _param has been actually entered by the user + */ + virtual bool isItThere(eoParam& _param) const + { return getValue(_param).first; } + + + std::string get( const std::string & name) const; + + + /** + * get a handle on a param from its longName + * + * if not found, returns 0 (null pointer :-) + * + * Not very clean (requires hard-coding of the long name twice!) + * but very useful in many occasions... + */ + eoParam * getParamWithLongName(const std::string& _name) const; + + + /** + * Get a handle on a param from its long name + * If not found, raise an eoMissingParamException + */ + eoParam * getParam(const std::string& _name) const; + + + /** + * Get the value of a param from its long name + * If not found, raise an eoMissingParamException + * + * Remember to specify the expected return type with a templated call: + * unsigned int popSize = eoparser.value("popSize"); + * + * If the template type is not the good one, an eoWrongParamTypeException is raised. + */ + template + ValueType valueOf(const std::string& _name) const + { + eoParam* param = getParam(_name); + + // Note: eoParam is the polymorphic base class of eoValueParam, thus we can do a dynamix cast + eoValueParam* vparam = dynamic_cast< eoValueParam* >(param); + + if( vparam == NULL ) { + // if the dynamic cast has failed, chances are that ValueType + // is not the same than the one used at declaration. + throw eoWrongParamTypeException( _name ); + } else { + return vparam->value(); + } + } + + + + /** Get or create parameter + + It seems finally that the easiest use of the above method is + through the following, whose interface is similar to that of the + widely-used createParam. + */ + template + eoValueParam& getORcreateParam(ValueType _defaultValue, + std::string _longName, + std::string _description, + char _shortHand = 0, + std::string _section = "", + bool _required = false) + { + eoParam* ptParam = getParamWithLongName(_longName); + if (ptParam) { + // found + eoValueParam* ptTypedParam( + dynamic_cast*>(ptParam)); + return *ptTypedParam; + } else { + // not found -> create it + return createParam(_defaultValue, _longName, _description, + _shortHand, _section, _required); + } + } + + + + /** Set parameter value or create parameter + + This makes sure that the specified parameter has the given value. + If the parameter does not exist yet, it is created. + + This requires that operator<< is defined for ValueType. + + + @param _defaultValue Default value. + @param _longName Long name of the argument. + @param _description Description of the parameter. + @param _shortHand Short name of the argument (Optional) + @param _section Name of the section where the parameter belongs. + @param _required Is the parameter mandatory? + @return Corresponding parameter. + */ + template + eoValueParam& setORcreateParam(ValueType _defaultValue, + std::string _longName, + std::string _description, + char _shortHand = 0, + std::string _section = "", + bool _required = false) + { + eoValueParam& param = createParam(_defaultValue, _longName, _description, + _shortHand, _section, _required); + std::ostringstream os; + os << _defaultValue; + if(isItThere(param)) { + param.setValue(os.str()); + } else { + longNameMap[_longName] = os.str(); + shortNameMap[_shortHand] = os.str(); + } + return param; + } + + + + /** accessors to the stopOnUnknownParam value */ + void setStopOnUnknownParam(bool _b) {stopOnUnknownParam.value()=_b;} + bool getStopOnUnknownParam() {return stopOnUnknownParam.value();} + + /** Prefix handling */ + void setPrefix(const std:: string & _prefix) {prefix = _prefix;} + + void resetPrefix() {prefix = "";} + + std::string getPrefix() {return prefix;} + +private: + + void doRegisterParam(eoParam& param); + + std::pair getValue(eoParam& _param) const; + + void updateParameters(); + + typedef std::multimap MultiMapType; + + // used to store all parameters that are processed + MultiMapType params; + + std::string programName; + std::string programDescription; + + typedef std::map ShortNameMapType; + ShortNameMapType shortNameMap; + + typedef std::map LongNameMapType; + LongNameMapType longNameMap; + + // flag that marks if the user need to know that there was a problem + // used to display the message about "-h" only once + bool needHelpMessage; + + eoValueParam needHelp; + eoValueParam stopOnUnknownParam; + + mutable std::vector messages; + + std::string prefix; // used for all created params - in processParam + +}; + + + +#endif // EO_PARSER_H + + + +// Local Variables: +// coding: iso-8859-1 +// mode:C++ +// c-file-style: "Stroustrup" +// comment-column: 35 +// fill-column: 80 +// End: diff --git a/eo/src/utils/eoParserLogger.h b/deprecated/eo/src/utils/eoParserLogger.h similarity index 100% rename from eo/src/utils/eoParserLogger.h rename to deprecated/eo/src/utils/eoParserLogger.h diff --git a/deprecated/eo/src/utils/eoPopStat.h b/deprecated/eo/src/utils/eoPopStat.h new file mode 100644 index 000000000..f3f091a6e --- /dev/null +++ b/deprecated/eo/src/utils/eoPopStat.h @@ -0,0 +1,137 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPopStat.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +/** WARNING: this file contains 2 classes: + +eoPopString and eoSortedPopString + +that transform the population into a std::string +that can be used to dump to the screen +*/ + +#ifndef _eoPopStat_h +#define _eoPopStat_h + +#include + + +/** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats. +This snippet is a workaround: +This class will "print" a whole population into a std::string - that you can later +send to any stream +This is the plain version - see eoPopString for the Sorted version + +Note: this Stat should probably be used only within eoStdOutMonitor, and not +inside an eoFileMonitor, as the eoState construct will work much better there. + +@ingroup Stats +*/ +template +class eoPopStat : public eoStat +{ +public: + + using eoStat::value; + + /** default Ctor, void std::string by default, as it appears + on the description line once at beginning of evolution. and + is meaningless there. _howMany defaults to 0, that is, the whole + population*/ + eoPopStat(unsigned _howMany = 0, std::string _desc ="") + : eoStat("", _desc), combien( _howMany) {} + +/** Fills the value() of the eoParam with the dump of the population. +Adds a \n before so it does not get mixed up with the rest of the stats +that are written by the monitor it is probably used from. +*/ +void operator()(const eoPop& _pop) +{ + value() = "\n# ====== pop dump =====\n"; + unsigned howmany=combien?combien:_pop.size(); + for (unsigned i = 0; i < howmany; ++i) + { + std::ostringstream os; + os << _pop[i] << std::endl; + + // paranoid: + value() += os.str(); + } +} + +private: + unsigned combien; +}; + +/** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats. +This snippet is a workaround: +This class will "print" a whole population into a std::string - that you can later +send to any stream +This is the Sorted version - see eoPopString for the plain version + +Note: this Stat should probably be used only within eoStdOutMonitor, and not +inside an eoFileMonitor, as the eoState construct will work much better there. + +@ingroup Stats +*/ +template +class eoSortedPopStat : public eoSortedStat +{ +public: + + using eoSortedStat::value; + + /** default Ctor, void std::string by default, as it appears on + the description line once at beginning of evolution. and is + meaningless there _howMany defaults to 0, that is, the whole + population + */ + eoSortedPopStat(unsigned _howMany = 0, std::string _desc ="") + : eoSortedStat("", _desc) , combien( _howMany) + {} + + /** Fills the value() of the eoParam with the dump of the + population. Adds a \n before so it does not get mixed up with + the rest of the stats that are written by the monitor it is + probably used from. + */ + void operator()(const std::vector& _pop) + { + value() = ""; // empty + unsigned howMany=combien?combien:_pop.size(); + for (unsigned i = 0; i < howMany; ++i) + { + std::ostringstream os; + os << *_pop[i] << std::endl; + + // paranoid: + value() += os.str(); + } + } +private: + unsigned combien; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoRNG.cpp b/deprecated/eo/src/utils/eoRNG.cpp new file mode 100644 index 000000000..b538499f1 --- /dev/null +++ b/deprecated/eo/src/utils/eoRNG.cpp @@ -0,0 +1,18 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include +#include "eoRNG.h" + +// initialize static constants +const uint32_t eoRng::K(0x9908B0DFU); +const int eoRng::M(397); +const int eoRng::N(624); + +namespace eo +{ + // global random number generator object + eoRng rng(static_cast(time(0))); +} diff --git a/deprecated/eo/src/utils/eoRNG.h b/deprecated/eo/src/utils/eoRNG.h new file mode 100644 index 000000000..984e76271 --- /dev/null +++ b/deprecated/eo/src/utils/eoRNG.h @@ -0,0 +1,598 @@ +/** Random number generator adapted from (see comments below) + +The random number generator is modified into a class +by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller +transformation to generate normal deviates. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: eodev-main@lists.sourceforge.net +Old contact information: todos@geneura.ugr.es, http://geneura.ugr.es +*/ + +#ifndef EO_RANDOM_NUMBER_GENERATOR +#define EO_RANDOM_NUMBER_GENERATOR + +/** @addtogroup Random + * @{ + * */ + +# if (defined _MSC_VER) +/** uint32_t is an unsigned integer type capable of holding 32 bits. + + In the applicatione here exactly 32 are used. + 64 bits might be better on an Alpha or other 64 bit systems with GCC at high + optimization levels so feel free to try your options and see what's best for + you. +*/ +typedef unsigned long uint32_t; +#else +#if (! defined __sun) +// The C99-standard defines uint32_t to be declared in stdint.h, but some +// systems don't have that and implement it in inttypes.h. +#include +#else +#include +#endif +#endif + +#include +#include +#include "eoPersistent.h" +#include "eoObject.h" + + +/** Random Number Generator + +@class eoRng eoRNG.h utils/eoRNG.h + +eoRng is a persistent class that uses the ``Mersenne Twister'' random +number generator MT19937 for generating random numbers. The various +member functions implement useful functions for evolutionary +algorithms. Included are: rand(), random(), flip() and normal(). + +EO provides a global random number generator rng that is seeded by the +current UNIX time at program start. Moreover some global convenience functions +are provided that use the global random number generator: random, +normal. + +@warning If you want to repeatedly generated the same sequence of pseudo-random +numbers, you should always reseed the generator at the beginning of your code. + + + +

Documentation in original file

+ +This is the ``Mersenne Twister'' random number generator MT19937, which +generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) starting +from any odd seed in 0..(2^32 - 1). This version is a recode by Shawn Cokus +(Cokus@math.washington.edu) on March 8, 1998 of a version by Takuji Nishimura +(who had suggestions from Topher Cooper and Marc Rieffel in July-August 1997). + +Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha +running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to +generate 300 million random numbers; after recoding: 24.0 sec. for the same +(i.e., 46.5% of original time), so speed is now about 12.5 million random number +generations per second on this machine. + +According to the URL (and +paraphrasing a bit in places), the Mersenne Twister is ``designed with +consideration of the flaws of various existing generators,'' has a period of +2^19937 - 1, gives a sequence that is 623-dimensionally equidistributed, and +``has passed many std::stringent tests, including the die-hard test of G. +Marsaglia and the load test of P. Hellekalek and S. Wegenkittl.'' It is +efficient in memory usage (typically using 2506 to 5012 bytes of static data, +depending on data type sizes, and the code is quite short as well). It generates +random numbers in batches of 624 at a time, so the caching and pipelining of +modern systems is exploited. It is also divide- and mod-free. + +The code as Shawn received it included the following notice: Copyright (C) +1997 Makoto Matsumoto and Takuji Nishimura. When you use this, send an e-mail to + with an appropriate reference to your work. It +would be nice to Cc: and + when you write. + + +

Portability

+ +Note for people porting EO to other platforms: please make sure that the type +uint32_t in the file eoRNG.h is exactly 32 bits long. It may in principle be +longer, but not shorter. If it is longer, file compatibility between EO on +different platforms may be broken. +*/ +class eoRng : public eoObject, public eoPersistent +{ +public : + + /** Constructor + + @param s Random seed; if you want another seed, use reseed. + + @see reseed for details on usage of the seeding value. + */ + eoRng(uint32_t s) + : state(0), next(0), left(-1), cached(false) + { + state = new uint32_t[N+1]; + initialize(2*s); + } + + /** Destructor */ + ~eoRng() + { + delete [] state; + } + + /** Re-initializes the Random Number Generator. + + WARNING: Jeroen Eggermont noticed that initialize does + not differentiate between odd and even numbers, therefore the argument to + reseed is now doubled before being passed on. + + Manually divide the seed by 2 if you want to re-run old runs + + @version MS. 5 Oct. 2001 + */ + void reseed(uint32_t s) + { + initialize(2*s); + } + + /** Re-initializes the Random Number Generator + + This is the traditional seeding procedure. This version is deprecated and + only provided for compatibility with old code. In new projects you should + use reseed. + + @see reseed for details on usage of the seeding value. + + @version old version (deprecated) + */ + void oldReseed(uint32_t s) + { + initialize(s); + } + + /** Random number from unifom distribution + + @param m Define interval for random number to [0, m) + @return random number in the range [0, m) + */ + double uniform(double m = 1.0) + { // random number between [0, m] + return m * double(rand()) / double(1.0 + rand_max()); + } + + /** Random number from unifom distribution + + @param min Define minimum for interval in the range [min, max) + @param max Define maximum for interval in the range [min, max) + @return random number in the range [min, max) + */ + double uniform(double min, double max) + { // random number between [min, max] + return min + uniform(max - min); + } + + /** Random integer number from unifom distribution + + @param m Define interval for random number to [0, m) + @return random integer in the range [0, m) + */ + uint32_t random(uint32_t m) + { + // C++ Standard (4.9 Floatingintegral conversions [conv.fpint]) + // defines floating point to integer conversion as truncation + // ("rounding towards zero"): "An rvalue of a floating point type + // can be converted to an rvalue of an integer type. The conversion + // truncates; that is, the fractional part is discarded" + return uint32_t(uniform() * double(m)); + } + + /** Biased coin toss + + This tosses a biased coin such that flip(x/100.0) will true x% of the time + + @param bias The coins' bias (the \e x above) + @return The result of the biased coin toss + */ + bool flip(double bias=0.5) + { + return uniform() < bias; + } + + /** Gaussian deviate + + Zero mean Gaussian deviate with standard deviation 1. + Note: Use the Marsaglia polar method. + + @return Random Gaussian deviate + */ + double normal(); + + /** Gaussian deviate + + Gaussian deviate with zero mean and specified standard deviation. + + @param stdev Standard deviation for Gaussian distribution + @return Random Gaussian deviate + */ + double normal(double stdev) + { return stdev * normal(); } + + /** Gaussian deviate + + Gaussian deviate with specified mean and standard deviation. + + @param mean Mean for Gaussian distribution + @param stdev Standard deviation for Gaussian distribution + @return Random Gaussian deviate + */ + double normal(double mean, double stdev) + { return mean + normal(stdev); } + + /** Random numbers using a negative exponential distribution + + @param mean Mean value of distribution + @return Random number from a negative exponential distribution + */ + double negexp(double mean) + { + return -mean*log(double(rand()) / rand_max()); + } + + /** + rand() returns a random number in the range [0, rand_max) + */ + uint32_t rand(); + + /** + rand_max() the maximum returned by rand() + */ + uint32_t rand_max() const { return uint32_t(0xffffffff); } + + /** Roulette wheel selection + + roulette_wheel(vec, total = 0) does a roulette wheel selection + on the input std::vector vec. If the total is not supplied, it is + calculated. It returns an integer denoting the selected argument. + */ + template + int roulette_wheel(const std::vector& vec, TYPE total = 0) + { + if (total == 0) + { // count + for (unsigned i = 0; i < vec.size(); ++i) + total += vec[i]; + } + double fortune = uniform() * total; + int i = 0; + while (fortune >= 0) + { + fortune -= vec[i++]; + } + return --i; + } + + + /** Randomly select element from vector. + + @return Uniformly chosen element from the vector. + */ + template + const TYPE& choice(const std::vector& vec) + { return vec[random(vec.size())]; } + + + /** Randomly select element from vector. + + @overload + + Provide a version returning a non-const element reference. + + @return Uniformly chosen element from the vector. + + @warning Changing the return value does alter the vector. + */ + template + TYPE& choice(std::vector& vec) + { return vec[random(vec.size())]; } + + /** @brief Print RNG + + @param _os Stream to print RNG on + */ + void printOn(std::ostream& _os) const + { + for (int i = 0; i < N; ++i) + { + _os << state[i] << ' '; + } + _os << int(next - state) << ' '; + _os << left << ' ' << cached << ' ' << cacheValue; + } + + /** @brief Read RNG + + @param _is Stream to read RNG from + */ + void readFrom(std::istream& _is) + { + for (int i = 0; i < N; ++i) + { + _is >> state[i]; + } + + int n; + _is >> n; + next = state + n; + + _is >> left; + _is >> cached; + _is >> cacheValue; + } + + std::string className() const { return "Mersenne-Twister"; } + +private: + + uint32_t restart(); + + /* @brief Initialize state + + We initialize state[0..(N-1)] via the generator + + x_new = (69069 * x_old) mod 2^32 + + from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's _The Art of Computer + Programming_, Volume 2, 3rd ed. + + Notes (SJC): I do not know what the initial state requirements of the + Mersenne Twister are, but it seems this seeding generator could be better. + It achieves the maximum period for its modulus (2^30) iff x_initial is odd + (p. 20-21, Sec. 3.2.1.2, Knuth); if x_initial can be even, you have + sequences like 0, 0, 0, ...; 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; + 2^29, 2^29 + 2^31, 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd + below. + + Even if x_initial is odd, if x_initial is 1 mod 4 then + + the lowest bit of x is always 1, + the next-to-lowest bit of x is always 0, + the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , + the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , + the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , + ... + + and if x_initial is 3 mod 4 then + + the lowest bit of x is always 1, + the next-to-lowest bit of x is always 1, + the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , + the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , + the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , + ... + + The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is 16, + which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It also does well + in the dimension 2..5 spectral tests, but it could be better in dimension 6 + (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). + + Note that the random number user does not see the values generated here + directly since restart() will always munge them first, so maybe none of all + of this matters. In fact, the seed values made here could even be + extra-special desirable if the Mersenne Twister theory says so-- that's why + the only change I made is to restrict to odd seeds. + */ + void initialize(uint32_t seed); + + /** @brief Array for the state */ + uint32_t *state; + + /** Pointer to next available random number */ + uint32_t *next; + + /** Number of random numbers currently left */ + int left; + + /** @brief Is there a valid cached value for the normal distribution? */ + bool cached; + + /** @brief Cached value for normal distribution? */ + double cacheValue; + + /** @brief Size of the state-vector */ + static const int N; + + /** Internal constant */ + static const int M; + + /** @brief Magic constant */ + static const uint32_t K; + + + /** @brief Copy constructor + + Private copy ctor and assignment operator to make sure that nobody + accidentally copies the random number generator. If you want similar RNG's, + make two RNG's and initialize them with the same seed. + + As it cannot be called, we do not provide an implementation. + */ + eoRng(const eoRng&); + + /** @brief Assignment operator + + @see Copy constructor eoRng(const eoRng&). + */ + eoRng& operator=(const eoRng&); +}; +/** @example t-eoRNG.cpp + */ + + + +namespace eo +{ + /** The one and only global eoRng object */ + extern eoRng rng; +} +using eo::rng; + +/** @} */ + + + + +// Implementation of some eoRng members.... Don't mind the mess, it does work. + +#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u +#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u +#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u +#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v + + +inline void eoRng::initialize(uint32_t seed) +{ + left = -1; + + register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state; + register int j; + + for(left=0, *s++=x, j=N; --j; + *s++ = (x*=69069U) & 0xFFFFFFFFU) ; +} + + + +inline uint32_t eoRng::restart() +{ + register uint32_t *p0=state, *p2=state+2, *pM=state+M, s0, s1; + register int j; + + left=N-1, next=state+1; + + for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++) + *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); + + for(pM=state, j=M; --j; s0=s1, s1=*p2++) + *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); + + s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); + s1 ^= (s1 >> 11); + s1 ^= (s1 << 7) & 0x9D2C5680U; + s1 ^= (s1 << 15) & 0xEFC60000U; + return(s1 ^ (s1 >> 18)); +} + + + +inline uint32_t eoRng::rand() +{ + if(--left < 0) + return(restart()); + uint32_t y = *next++; + y ^= (y >> 11); + y ^= (y << 7) & 0x9D2C5680U; + y ^= (y << 15) & 0xEFC60000U; + return(y ^ (y >> 18)); +} + + + +inline double eoRng::normal() +{ + if (cached) { + cached = false; + return cacheValue; + } + double rSquare, var1, var2; + do { + var1 = 2.0 * uniform() - 1.0; + var2 = 2.0 * uniform() - 1.0; + rSquare = var1 * var1 + var2 * var2; + } while (rSquare >= 1.0 || rSquare == 0.0); + double factor = sqrt(-2.0 * log(rSquare) / rSquare); + cacheValue = var1 * factor; + cached = true; + return (var2 * factor); +} + + + +namespace eo +{ + /** @brief Random function + + This is a convenience function for generating random numbers using the + global eo::rng object. + + Templatized random function, returns a random double in the range [min, max). + It works with most basic types such as: + - char + - int (short, long, signed and unsigned) + - float, double + + @param min Minimum for distribution + @param max Maximum for distribution + + @see random(const T& max) + */ + template + inline T random(const T& min, const T& max) { + return static_cast(rng.uniform() * (max-min)) + min; } + + /** @brief Random function + + @overload + + This is a convenience function for generating random numbers using the + global eo::rng object. + + Templatized random function, returns a random double in the range [0, max). + It works with most basic types such as: + - char + - int (short, long, signed and unsigned) + - float, double + + @param max Maximum for distribution + + @see random(const T& min, const T& max) + */ + template + inline T random(const T& max) { + return static_cast(rng.uniform() * max); } + + /** Normal distribution + + This is a convenience function for generating random numbers using the + global eo::rng object. + + @return ormally distributed random number + */ + inline double normal() { return rng.normal(); } +} + + +#endif + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/eoRealBounds.cpp b/deprecated/eo/src/utils/eoRealBounds.cpp new file mode 100644 index 000000000..89dcb3584 --- /dev/null +++ b/deprecated/eo/src/utils/eoRealBounds.cpp @@ -0,0 +1,259 @@ +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include "eoRealBounds.h" +#include "eoRealVectorBounds.h" + + +// the global dummy bounds +// (used for unbounded variables when bounds are required) +eoRealNoBounds eoDummyRealNoBounds; +eoRealVectorNoBounds eoDummyVectorNoBounds(0); + +///////////// helper read functions - could be somewhere else + +// removes leading delimiters - return false if nothing else left +bool remove_leading(std::string & _s, const std::string _delim) +{ + size_t posDebToken = _s.find_first_not_of(_delim); + if (posDebToken >= _s.size()) + return false; + _s = _s.substr(posDebToken); + return true; +} + +double read_double(std::string _s) +{ + std::istringstream is(_s); + double r; + is >> r; + return r; +} + +long int read_int(std::string _s) +{ + std::istringstream is(_s); + long int i; + is >> i; + return i; +} + +// need to rewrite copy ctor and assignement operator because of ownedBounds +eoRealVectorBounds::eoRealVectorBounds(const eoRealVectorBounds & _b): + eoRealBaseVectorBounds(_b), eoPersistent() +{ + factor = _b.factor; + ownedBounds = _b.ownedBounds; + // duplicate all pointers! + if (ownedBounds.size()>0) + for (unsigned i=0; idup(); +} + + +// the readFrom method of eoRealVectorNoBounds: +// only calls the readFrom(string) - for param reading +void eoRealVectorBounds::readFrom(std::istream& _is) +{ + std::string value; + _is >> value; + readFrom(value); + return; +} + +void eoRealVectorBounds::readFrom(std::string _value) +{ + // keep track of old size - to adjust in the end + unsigned oldSize = size(); + // clean-up before filling in + if (ownedBounds.size()>0) + for (unsigned i = 0; i < ownedBounds.size(); ++i) + { + delete ownedBounds[i]; + } + ownedBounds.resize(0); + factor.resize(0); + resize(0); + + // now read + std::string delim(",; "); + while (_value.size()>0) + { + if (!remove_leading(_value, delim)) // only delimiters were left + break; + // look for opening char + size_t posDeb = _value.find_first_of("[("); + if (posDeb >= _value.size()) // nothing left to read (though probably a syntax error there) + { + break; + } + // ending char + std::string closeChar = (_value[posDeb] == '(' ? std::string(")") : std::string("]") ); + + size_t posFin = _value.find_first_of(std::string(closeChar)); + if (posFin >= _value.size()) + throw std::runtime_error("Syntax error when reading bounds"); + + // y a-t-il un nbre devant + unsigned count = 1; + if (posDeb > 0) // something before opening + { + std::string sCount = _value.substr(0, posDeb); + count = read_int(sCount); + if (count <= 0) + throw std::runtime_error("Syntax error when reading bounds"); + } + + // the bounds + std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1); + // and remove from original string + _value = _value.substr(posFin+1); + + remove_leading(sBounds, delim); + size_t posDelim = sBounds.find_first_of(delim); + if (posDelim >= sBounds.size()) + throw std::runtime_error("Syntax error when reading bounds"); + + bool minBounded=false, maxBounded=false; + double minBound=0, maxBound=0; + + // min bound + std::string sMinBounds = sBounds.substr(0,posDelim); + if (sMinBounds != std::string("-inf")) + { + minBounded = true; + minBound = read_double(sMinBounds); + } + + // max bound + size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); + + std::string sMaxBounds = sBounds.substr(posEndDelim); + if (sMaxBounds != std::string("+inf")) + { + maxBounded = true; + maxBound = read_double(sMaxBounds); + } + + // now create the eoRealBounds objects + eoRealBounds *ptBounds; + if (minBounded && maxBounded) + ptBounds = new eoRealInterval(minBound, maxBound); + else if (!minBounded && !maxBounded) // no bound at all + ptBounds = new eoRealNoBounds; + else if (!minBounded && maxBounded) + ptBounds = new eoRealAboveBound(maxBound); + else if (minBounded && !maxBounded) + ptBounds = new eoRealBelowBound(minBound); + // store it for memory management + ownedBounds.push_back(ptBounds); + // push the count + factor.push_back(count); + // and add count of it to the actual bounds + for (unsigned i=0; i 1 already!) + factor[factor.size()-1] += missing; + } +} + +/** the constructor for eoGeneralRealBound - from a string + * very similar to the eoRealVectorBounds::readFrom above + * but was written much later so the readFrom does not call this one + * as it should do + */ +eoRealBounds* eoGeneralRealBounds::getBoundsFromString(std::string _value) +{ + // now read + std::string delim(",; "); + std::string beginOrClose("[(])"); + if (!remove_leading(_value, delim)) // only delimiters were left + throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); + + // look for opening char + size_t posDeb = _value.find_first_of(beginOrClose); // allow ]a,b] + if (posDeb >= _value.size()) // nothing left to read + throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); + + // ending char: next {}() after posDeb + size_t posFin = _value.find_first_of(beginOrClose,posDeb+1); + if (posFin >= _value.size()) // not found + throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); + + // the bounds + std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1); + // and remove from original string + _value = _value.substr(posFin+1); + + remove_leading(sBounds, delim); + size_t posDelim = sBounds.find_first_of(delim); + if (posDelim >= sBounds.size()) + throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); + + bool minBounded=false, maxBounded=false; + double minBound=0, maxBound=0; + + // min bound + std::string sMinBounds = sBounds.substr(0,posDelim); + + if ( (sMinBounds != std::string("-inf")) && + (sMinBounds != std::string("-infinity")) + ) + { + minBounded = true; + minBound = read_double(sMinBounds); + } + + // max bound + size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); + + std::string sMaxBounds = sBounds.substr(posEndDelim); + + if ( (sMaxBounds != std::string("+inf")) && + (sMaxBounds != std::string("+infinity")) + ) + { + maxBounded = true; + maxBound = read_double(sMaxBounds); + } + + // now create the embedded eoRealBounds object + eoRealBounds * locBound; + if (minBounded && maxBounded) + { + if (maxBound <= minBound) + throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); + locBound = new eoRealInterval(minBound, maxBound); + } + else if (!minBounded && !maxBounded) // no bound at all + locBound = new eoRealNoBounds; + else if (!minBounded && maxBounded) + locBound = new eoRealAboveBound(maxBound); + else if (minBounded && !maxBounded) + locBound = new eoRealBelowBound(minBound); + return locBound; +} diff --git a/deprecated/eo/src/utils/eoRealBounds.h b/deprecated/eo/src/utils/eoRealBounds.h new file mode 100644 index 000000000..47c061005 --- /dev/null +++ b/deprecated/eo/src/utils/eoRealBounds.h @@ -0,0 +1,686 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRealBounds.h +// (c) Marc Schoenauer 2001, Maarten Keijzer 2000, GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoRealBounds_h +#define _eoRealBounds_h + +#include // std::exceptions! +#include + +/** +\defgroup Real Vector of reals + +Set of classes related to continuous black-box optimization problems. + +Here are several examples of test programs using eoReal, eoEsSimple, eoEsStdev or eoEsFull to build an Evoution Strategies algorithm: +@include t-eoESAll.cpp +@include t-eoESFull.cpp + +@ingroup Representations + +*/ + + +/** +\class eoRealBounds eoRealBounds.h es/eoRealBounds.h +\ingroup Real + + Defines bound classes for real numbers. + +Scalar type: +------------ +Basic class is eoRealBounds, a pure virtual. + +The following pure virtual methods are to be used in mutations: +- void foldsInBounds(double &) that folds any value that falls out of + the bounds back into the bounds, by bouncing on the limit (if any) +- bool isInBounds(double) that simply says whether or not the argument + is in the bounds +- void truncate(double &) that set the argument to the bound value it +it exceeds it + +So mutation can choose +- iterate trying until they fall in bounds, +- only try once and "restd::pair" by using the foldsInBounds method +- only try once and restd::pair using the truncate method (will create a + huge bias toward the bound if the soluiton is not far from the bounds) + +There is also a uniform() method that generates a uniform value +(if possible, i.e. if bounded) in the interval. + +Derived class are +eoRealInterval that holds a minimum and maximum value, +eoRealNoBounds the "unbounded bounds" (-infinity, +infinity) +eoRealBelowBound the half-bounded interval [min, +infinity) +eoRealAboveBound the half-bounded interval (-infinity, max] + +THis file also contains the declaration of *the* global object that +is the unbounded bound + +@ingroup Bounds +*/ +class eoRealBounds : public eoPersistent +{ +public: + virtual ~eoRealBounds(){} + + /** Self-Test: true if ***both*** a min and a max + */ + virtual bool isBounded(void) const = 0; + + /** Self-Test: true if no min ***and*** no max + * hence no further need to test/truncate/fold anything + */ + virtual bool hasNoBoundAtAll(void) const = 0; + + /** Self-Test: bounded from below??? + */ + virtual bool isMinBounded(void) const = 0; + + /** Self-Test: bounded from above??? + */ + virtual bool isMaxBounded(void) const = 0; + + /** Test on a value: is it in bounds? + */ + virtual bool isInBounds(double) const = 0; + + /** Put value back into bounds - by folding back and forth + */ + virtual void foldsInBounds(double &) const = 0; + + /** Put value back into bounds - by truncating to a boundary value + */ + virtual void truncate(double &) const = 0; + + /** get minimum value + * std::exception if does not exist + */ + virtual double minimum() const = 0 ; + /** get maximum value + * std::exception if does not exist + */ + virtual double maximum() const = 0 ; + /** get range + * std::exception if unbounded + */ + virtual double range() const = 0; + + /** random generator of uniform numbers in bounds + * std::exception if unbounded + */ + virtual double uniform(eoRng & _rng = eo::rng) const = 0; + + /** for memory managements - ugly */ + virtual eoRealBounds * dup() const = 0; +}; + +/** A default class for unbounded variables + +@ingroup Bounds + */ +class eoRealNoBounds : public eoRealBounds +{ +public: + virtual ~eoRealNoBounds(){} + + virtual bool isBounded(void) const {return false;} + virtual bool hasNoBoundAtAll(void) const {return true;} + virtual bool isMinBounded(void) const {return false;} + virtual bool isMaxBounded(void) const {return false;} + virtual void foldsInBounds(double &) const {return;} + virtual void truncate(double &) const {return;} + virtual bool isInBounds(double) const {return true;} + + virtual double minimum() const + { + throw std::logic_error("Trying to get minimum of unbounded eoRealBounds"); + } + virtual double maximum() const + { + throw std::logic_error("Trying to get maximum of unbounded eoRealBounds"); + } + virtual double range() const + { + throw std::logic_error("Trying to get range of unbounded eoRealBounds"); + } + + virtual double uniform(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in unbounded eoRealBounds"); + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoRealVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoRealBounds::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[-inf,+inf]"; + } + + /** for memory managements - ugly */ + virtual eoRealBounds * dup() const + { + return new eoRealNoBounds(*this); + } + +}; + +/** one object for all - see eoRealBounds.cpp +@ingroup Bounds +*/ +extern eoRealNoBounds eoDummyRealNoBounds; + +/** + * fully bounded eoRealBound == interval + +@ingroup Bounds + */ +class eoRealInterval : public eoRealBounds +{ +public : + virtual ~eoRealInterval(){} + + /** + Simple bounds = minimum and maximum (allowed) + */ + eoRealInterval(double _min=0, double _max=1) : + repMinimum(_min), repMaximum(_max), repRange(_max-_min) + { + if (repRange<=0) + throw std::logic_error("Void range in eoRealBounds"); + } + + // accessors + virtual double minimum() const { return repMinimum; } + virtual double maximum() const { return repMaximum; } + virtual double range() const { return repRange; } + + // description + virtual bool isBounded(void) const {return true;} + virtual bool hasNoBoundAtAll(void) const {return false;} + virtual bool isMinBounded(void) const {return true;} + virtual bool isMaxBounded(void) const {return true;} + + virtual double uniform(eoRng & _rng = eo::rng) const + { + return repMinimum + _rng.uniform(repRange); + } + + // says if a given double is within the bounds + virtual bool isInBounds(double _r) const + { + if (_r < repMinimum) + return false; + if (_r > repMaximum) + return false; + return true; + } + + // folds a value into bounds + virtual void foldsInBounds(double & _r) const + { + long iloc; + double dlargloc = 2 * range() ; + + if (fabs(_r) > 1.0E9) // iloc too large! + { + _r = uniform(); + return; + } + + if ( (_r > maximum()) ) + { + iloc = (long) ( (_r-minimum()) / dlargloc ) ; + _r -= dlargloc * iloc ; + if ( _r > maximum() ) + _r = 2*maximum() - _r ; + } + + if (_r < minimum()) + { + iloc = (long) ( (maximum()-_r) / dlargloc ) ; + _r += dlargloc * iloc ; + if (_r < minimum()) + _r = 2*minimum() - _r ; + } + } + + // truncates to the bounds + virtual void truncate(double & _r) const + { + if (_r < repMinimum) + _r = repMinimum; + else if (_r > repMaximum) + _r = repMaximum; + return; + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoRealVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoRealInterval::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[" << repMinimum << "," << repMaximum << "]"; + } + + /** for memory managements - ugly */ + virtual eoRealBounds * dup() const + { + return new eoRealInterval(*this); + } + +private : + double repMinimum; + double repMaximum; + double repRange; // to minimize operations ??? +}; + +/** + * an eoRealBound bounded from below only + +@ingroup Bounds + */ +class eoRealBelowBound : public eoRealBounds +{ +public : + virtual ~eoRealBelowBound(){} + /** + Simple bounds = minimum + */ + eoRealBelowBound(double _min=0) : + repMinimum(_min) + {} + + // accessors + virtual double minimum() const { return repMinimum; } + + virtual double maximum() const + { + throw std::logic_error("Trying to get maximum of eoRealBelowBound"); + } + virtual double range() const + { + throw std::logic_error("Trying to get range of eoRealBelowBound"); + } + + // random generators + virtual double uniform(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in eoRealBelowBound"); + } + + // description + virtual bool isBounded(void) const {return false;} + virtual bool hasNoBoundAtAll(void) const {return false;} + virtual bool isMinBounded(void) const {return true;} + virtual bool isMaxBounded(void) const {return false;} + + // says if a given double is within the bounds + virtual bool isInBounds(double _r) const + { + if (_r < repMinimum) + return false; + return true; + } + + // folds a value into bounds + virtual void foldsInBounds(double & _r) const + { + // easy as a pie: symmetry w.r.t. minimum + if (_r < repMinimum) // nothing to do otherwise + _r = 2*repMinimum - _r; + return ; + } + + // truncates to the bounds + virtual void truncate(double & _r) const + { + if (_r < repMinimum) + _r = repMinimum; + return; + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoRealVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoRealBelowBound::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[" << repMinimum << ",+inf]"; + } + + /** for memory managements - ugly */ + virtual eoRealBounds * dup() const + { + return new eoRealBelowBound(*this); + } + +private : + double repMinimum; +}; + +/** +An eoRealBound bounded from above only +*/ +class eoRealAboveBound : public eoRealBounds +{ +public : + virtual ~eoRealAboveBound(){} + + /** + Simple bounds = minimum + */ + eoRealAboveBound(double _max=0) : + repMaximum(_max) + {} + + // accessors + virtual double maximum() const { return repMaximum; } + + virtual double minimum() const + { + throw std::logic_error("Trying to get minimum of eoRealAboveBound"); + } + virtual double range() const + { + throw std::logic_error("Trying to get range of eoRealAboveBound"); + } + + // random generators + virtual double uniform(eoRng & _rng = eo::rng) const + { + (void)_rng; + + throw std::logic_error("Trying to generate uniform values in eoRealAboveBound"); + } + + // description + virtual bool isBounded(void) const {return false;} + virtual bool hasNoBoundAtAll(void) const {return false;} + virtual bool isMinBounded(void) const {return false;} + virtual bool isMaxBounded(void) const {return true;} + + // says if a given double is within the bounds + virtual bool isInBounds(double _r) const + { + if (_r > repMaximum) + return false; + return true; + } + + // folds a value into bounds + virtual void foldsInBounds(double & _r) const + { + // easy as a pie: symmetry w.r.t. maximum + if (_r > repMaximum) // nothing to do otherwise + _r = 2*repMaximum - _r; + return ; + } + + // truncates to the bounds + virtual void truncate(double & _r) const + { + if (_r > repMaximum) + _r = repMaximum; + return; + } + + // methods from eoPersistent + /** + * Read object. + * @param _is A std::istream. + * but reading should not be done here, because of bound problems + * see eoRealVectorBounds + */ + virtual void readFrom(std::istream& _is) + { + (void)_is; + + throw std::runtime_error("Should not use eoRealAboveBound::readFrom"); + } + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << "[-inf," << repMaximum << "]"; + } + + /** for memory managements - ugly */ + virtual eoRealBounds * dup() const + { + return new eoRealAboveBound(*this); + } + +private : + double repMaximum; +}; + +//////////////////////// tentative for a general BOUND class that is constructed from a string + +/** A class that encapsulate all possible eoIntBounds. + * Mandatory in order to read through the parser + +@ingroup Bounds + */ +class eoGeneralRealBounds : public eoRealBounds +{ +public: + /** Ctor: from a string, chooses the type of bound */ + eoGeneralRealBounds(std::string _s = "[-infinity,+infinity]") + { + repBound = getBoundsFromString(_s); + } + + /** Need a Cpy Ctor because we are allocating memory */ + eoGeneralRealBounds(const eoGeneralRealBounds & _b):eoRealBounds(_b) + { + // replicate the embedded bound (I'm pretty sure there is another + // way to do that !!! + + bool minBounded = _b.isMinBounded(); + bool maxBounded = _b.isMaxBounded(); + double minimum, maximum; + const eoRealBounds & bb = _b.theBounds(); + if (minBounded) minimum = bb.minimum(); + if (maxBounded) maximum = bb.maximum(); + + if (minBounded && maxBounded) + repBound = new eoRealInterval(minimum, maximum); + else if (!minBounded && !maxBounded) // no bound at all + repBound = new eoRealNoBounds; + else if (!minBounded && maxBounded) + repBound = new eoRealAboveBound(maximum); + else if (minBounded && !maxBounded) + repBound = new eoRealBelowBound(minimum); + } + + eoGeneralRealBounds& operator=(const eoGeneralRealBounds& _b) + { + // replicate the embedded bound (I'm pretty sure there is another + // way to do that !!! + + bool minBounded = _b.isMinBounded(); + bool maxBounded = _b.isMaxBounded(); + double minimum, maximum; + const eoRealBounds & bb = _b.theBounds(); + if (minBounded) minimum = bb.minimum(); + if (maxBounded) maximum = bb.maximum(); + + // first delete the embedded bounds if necessary + if (repBound) + delete repBound; + // now reallocate + if (minBounded && maxBounded) + repBound = new eoRealInterval(minimum, maximum); + else if (!minBounded && !maxBounded) // no bound at all + repBound = new eoRealNoBounds; + else if (!minBounded && maxBounded) + repBound = new eoRealAboveBound(maximum); + else if (minBounded && !maxBounded) + repBound = new eoRealBelowBound(minimum); + return (*this); + } + + + /** Need a Dtor because we allocate an actual bound */ + ~eoGeneralRealBounds() + { + delete repBound; + } + + ///// and now all methods from the embedded bounds + /** Self-Test: true if ***both*** a min and a max + */ + virtual bool isBounded(void) const {return repBound->isBounded();} + + /** Self-Test: true if no min ***and*** no max + * hence no further need to test/truncate/fold anything + */ + virtual bool hasNoBoundAtAll(void) const {return repBound->hasNoBoundAtAll();} + + /** Self-Test: bounded from below??? + */ + virtual bool isMinBounded(void) const {return repBound->isMinBounded();} + + /** Self-Test: bounded from above??? + */ + virtual bool isMaxBounded(void) const {return repBound->isMaxBounded();} + + /** Test on a value: is it in bounds? + */ + virtual bool isInBounds(double _x) const {return repBound->isInBounds(_x);} + + /** Put value back into bounds - by folding back and forth + */ + virtual void foldsInBounds(double & _x) const {return repBound->foldsInBounds(_x);} + + /** Put value back into bounds - by truncating to a boundary value + */ + virtual void truncate(double & _x) const {return repBound->truncate(_x);} + + /** get minimum value + * std::exception if does not exist + */ + virtual double minimum() const {return repBound->minimum();} + /** get maximum value + * std::exception if does not exist + */ + virtual double maximum() const {return repBound->maximum();} + /** get range + * std::exception if unbounded + */ + virtual double range() const {return repBound->range();} + + /** random generator of uniform numbers in bounds + * std::exception if unbounded + */ + virtual double uniform(eoRng & _rng = eo::rng) const {(void)_rng; return repBound->uniform();} + + /** for memory managements - ugly */ + virtual eoRealBounds * dup() const {return repBound->dup();} + + /** for efficiency, it's better to use the embedded boud directly */ + const eoRealBounds & theBounds() const { return *repBound;} + + /** don't forget the printOn method - + * again that of the embedded bound + */ + virtual void printOn(std::ostream& _os) const + { + repBound->printOn(_os); + } + + /** no readFrom ??? Have to check that later */ + virtual void readFrom(std::istream& _is) + { + std::string s; + _is >> s; + if (repBound) + delete repBound; + repBound = getBoundsFromString(s); + } + +private: + // reading from a string + eoRealBounds * getBoundsFromString(std::string); + + eoRealBounds * repBound; +}; + + +#endif diff --git a/deprecated/eo/src/utils/eoRealVectorBounds.h b/deprecated/eo/src/utils/eoRealVectorBounds.h new file mode 100644 index 000000000..56feff345 --- /dev/null +++ b/deprecated/eo/src/utils/eoRealVectorBounds.h @@ -0,0 +1,429 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRealVectorBounds.h +// (c) Marc Schoenauer 2001, Maarten Keijzer 2000, GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoRealVectorBounds_h +#define _eoRealVectorBounds_h + +#include // std::exceptions! +#include +#include + +/** +Vector type for bounds (see eoRealBounds.h for scalar types) +------------ +Class eoRealVectorBounds implements the std::vectorized version: +it is basically a std::vector of eoRealBounds * and forwards all request +to the elements of the std::vector. + +This file also contains the global variables and eoDummyVectorNoBounds +that are used as defaults in ctors (i.e. when no +bounds are given, it is assumed unbounded values) + +THe 2 main classes defined here are + +eoRealBaseVectorBounds, base class that handles all useful functions +eoRealVectorBounds which derives from the preceding *and* eoPersistent + and also has a mechanism for memory handling of the pointers + it has to allocate + +@ingroup Bounds +*/ +class eoRealBaseVectorBounds : public std::vector +{ +public: + // virtual desctructor (to avoid warning?) + virtual ~eoRealBaseVectorBounds(){} + + /** Default Ctor. + */ + eoRealBaseVectorBounds() : std::vector(0) {} + + /** Ctor: same bounds for everybody, given as an eoRealBounds + */ + eoRealBaseVectorBounds(unsigned _dim, eoRealBounds & _bounds) : + std::vector(_dim, &_bounds) + {} + + /** Ctor, particular case of dim-2 + */ + eoRealBaseVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : + std::vector(0) + { + push_back( &_xbounds); + push_back( &_ybounds); + } + + /** test: is i_th component bounded + */ + virtual bool isBounded(unsigned _i) + { + return (*this)[_i]->isBounded(); + } + + /** test: bounded iff all are bounded + */ + virtual bool isBounded(void) + { + for (unsigned i=0; iisBounded()) + return false; + return true; + } + + /** Self-test: true iff i_th component has no bounds at all + */ + virtual bool hasNoBoundAtAll(unsigned _i) + { + return (*this)[_i]->hasNoBoundAtAll(); + } + + /** Self-test: true iff all components have no bound at all + */ + virtual bool hasNoBoundAtAll(void) + { + for (unsigned i=0; ihasNoBoundAtAll()) + return false; + return true; + } + + virtual bool isMinBounded(unsigned _i) + { return (*this)[_i]->isMinBounded();} ; + + virtual bool isMaxBounded(unsigned _i) + { return (*this)[_i]->isMaxBounded();} ; + + /** Folds a real value back into the bounds - i_th component + */ + virtual void foldsInBounds(unsigned _i, double & _r) + { + (*this)[_i]->foldsInBounds(_r); + } + + /** Folds all variables of a std::vector of real values into the bounds + */ + virtual void foldsInBounds(std::vector & _v) + { + for (unsigned i=0; ifoldsInBounds(_v[i]); + } + } + + /** Truncates a real value to the bounds - i_th component + */ + virtual void truncate(unsigned _i, double & _r) + { + (*this)[_i]->truncate(_r); + } + + /** truncates all variables of a std::vector of real values to the bounds + */ + virtual void truncate(std::vector & _v) + { + for (unsigned i=0; itruncate(_v[i]); + } + } + + /** test: is i_th component within the bounds? + */ + virtual bool isInBounds(unsigned _i, double _r) + { return (*this)[_i]->isInBounds(_r); } + + /** test: are ALL components within the bounds? + */ + virtual bool isInBounds(std::vector _v) + { + for (unsigned i=0; iminimum();} + virtual double maximum(unsigned _i) {return (*this)[_i]->maximum();} + virtual double range(unsigned _i) {return (*this)[_i]->range();} + + /** Computes the average range + * An std::exception will be raised if one of the component is unbounded + */ + virtual double averageRange() + { + double r=0.0; + for (unsigned i=0; iuniform(); + return r; + } + + /** fills a std::vector with uniformly chosen variables in bounds + * An std::exception will be raised if one of the component is unbounded + */ + void uniform(std::vector & _v, eoRng & _rng = eo::rng) + { + _v.resize(size()); + for (unsigned i=0; iprintOn(_os); + _os << ";"; + } + } +}; + +//////////////////////////////////////////////////////////////////// +/** Now a derived class, for parser reading + * It holds some of the bounds (and destroy them when dying) + +@ingroup Bounds + */ +class eoRealVectorBounds : public eoRealBaseVectorBounds, public eoPersistent +{ +public: + /** Default Ctor will call base class default ctor + */ + eoRealVectorBounds():eoRealBaseVectorBounds() {} + + /** Ctor: same bounds for everybody, given as an eoRealBounds + */ + eoRealVectorBounds(unsigned _dim, eoRealBounds & _bounds) : + eoRealBaseVectorBounds(_dim, _bounds), factor(1,_dim), ownedBounds(0) + {} + + /** Ctor, particular case of dim-2 + */ + eoRealVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : + eoRealBaseVectorBounds(_xbounds, _ybounds), factor(2,1), ownedBounds(0) + {} + + /** Simple bounds = minimum and maximum (allowed) + */ + eoRealVectorBounds(unsigned _dim, double _min, double _max) : + eoRealBaseVectorBounds(), factor(1, _dim), ownedBounds(0) + { + if (_max-_min<=0) + throw std::logic_error("Void range in eoRealVectorBounds"); + eoRealBounds *ptBounds = new eoRealInterval(_min, _max); + // handle memory once + ownedBounds.push_back(ptBounds); + // same bound for everyone + for (unsigned int i=0; i<_dim; i++) + push_back(ptBounds); + } + + /** Ctor: different bounds for different variables, std::vectors of double + */ + eoRealVectorBounds(std::vector _min, std::vector _max) : + factor(_min.size(), 1), ownedBounds(0) + { + if (_max.size() != _min.size()) + throw std::logic_error("Dimensions don't match in eoRealVectorBounds"); + // the bounds + eoRealBounds *ptBounds; + for (unsigned i=0; i<_min.size(); i++) + { + ptBounds = new eoRealInterval(_min[i], _max[i]); + ownedBounds.push_back(ptBounds); + push_back(ptBounds); + } + } + + /** Ctor from a std::string + * and don't worry, the readFrom(std::string) starts by setting everything to 0! + */ + eoRealVectorBounds(std::string _s) : eoRealBaseVectorBounds() + { + readFrom(_s); + } + + /** Dtor: destroy all ownedBounds - BUG ???*/ + virtual ~eoRealVectorBounds() + { +// std::cout << "Dtor, avec size = " << ownedBounds.size() << std::endl; +// for (unsigned i = 0; i < ownedBounds.size(); ++i) +// { +// delete ownedBounds[i]; +// } +} + + + // methods from eoPersistent + /** + * Read object from a stream + * only calls the readFrom(std::string) - for param reading + * @param _is A std::istream. + */ + virtual void readFrom(std::istream& _is) ; + + /** + * Read object from a std::string + * @param _s A std::istream. + */ + virtual void readFrom(std::string _s) ; + + /** overload printOn method to save space */ + virtual void printOn(std::ostream& _os) const + { + if (factor[0]>1) + _os << factor[0] ; + operator[](0)->printOn(_os); + + // other bounds + unsigned int index=factor[0]; + if (factor.size()>1) + for (unsigned i=1; i 1) + _os << factor[i]; + operator[](index)->printOn(_os); + index += factor[i]; + } + } + + /** Eventually increases the size by duplicating last bound */ + void adjust_size(unsigned _dim); + + /** need to rewrite copy ctor and assignement operator + * because of ownedBounds */ + eoRealVectorBounds(const eoRealVectorBounds &); + +private:// WARNING: there is no reason for both std::vector below + //to be synchronized in any manner + std::vector factor; // std::list of nb of "grouped" bounds + std::vector ownedBounds; +// keep this one private + eoRealVectorBounds& operator=(const eoRealVectorBounds&); + }; + +////////////////////////////////////////////////////////////// +/** the dummy unbounded eoRealVectorBounds: usefull if you don't need bounds! + * everything is inlined. + * Warning: we do need this class, and not only a std::vector + +@ingroup Bounds + */ +class eoRealVectorNoBounds: public eoRealVectorBounds +{ +public: + // virtual desctructor (to avoid warning?) + virtual ~eoRealVectorNoBounds(){} + + /** + * Ctor: nothing to do, but beware of dimension: call base class ctor + */ + eoRealVectorNoBounds(unsigned _dim) : + eoRealVectorBounds( (_dim?_dim:1), eoDummyRealNoBounds) + {} + + + virtual bool isBounded(unsigned) {return false;} + virtual bool isBounded(void) {return false;} + + virtual bool hasNoBoundAtAll(unsigned) {return true;} + virtual bool hasNoBoundAtAll(void) {return true;} + + virtual bool isMinBounded(unsigned) {return false;} + virtual bool isMaxBounded(unsigned) {return false;} + + virtual void foldsInBounds(unsigned, double &) {return;} + virtual void foldsInBounds(std::vector &) {return;} + + virtual void truncate(unsigned, double &) {return;} + virtual void truncate(std::vector &) {return;} + + virtual bool isInBounds(unsigned, double) {return true;} + virtual bool isInBounds(std::vector) {return true;} + + // accessors + virtual double minimum(unsigned) + { + throw std::logic_error("Trying to get minimum of eoRealVectorNoBounds"); + } + virtual double maximum(unsigned) + { + throw std::logic_error("Trying to get maximum of eoRealVectorNoBounds"); + } + virtual double range(unsigned) + { + throw std::logic_error("Trying to get range of eoRealVectorNoBounds"); + } + + virtual double averageRange() + { + throw std::logic_error("Trying to get average range of eoRealVectorNoBounds"); + } + + // random generators + virtual double uniform(unsigned, eoRng & _rng = eo::rng) + { + (void)_rng; + + throw std::logic_error("No uniform distribution on eoRealVectorNoBounds"); + } + + // fills a std::vector with uniformly chosen variables in bounds + void uniform(std::vector &, eoRng & _rng = eo::rng) + { + (void)_rng; + + throw std::logic_error("No uniform distribution on eoRealVectorNoBounds"); + } + +}; + + + +/** one object for all - see eoRealBounds.cpp +@ingroup Bounds +*/ +extern eoRealVectorNoBounds eoDummyVectorNoBounds; +#endif diff --git a/deprecated/eo/src/utils/eoRndGenerators.h b/deprecated/eo/src/utils/eoRndGenerators.h new file mode 100644 index 000000000..62e62ccff --- /dev/null +++ b/deprecated/eo/src/utils/eoRndGenerators.h @@ -0,0 +1,161 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoRndGenerators.h + + mimics the rnd_generator.h by putting the generators in the EO-hierarchy + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +//----------------------------------------------------------------------------- + +#ifndef eoRndGenerators_h +#define eoRndGenerators_h + +#include "eoRNG.h" +#include +#include + +/** @defgroup Random Random number generation + * + * @ingroup Utilities + * @{ + */ + +using eo::rng; + +/** + By popular demand re-introducing a base class for a family of + random number generators. Derived members of this class are useful + to initialize fixed/variable length genotypes that have an 'atomic' type + in an indepent way (thus without employing any knowledge about the problem domain). + + See derived classes eoUniformGenerator, eoBooleanGenerator, eoNormalGenerator and eoNegExpGenerator +*/ +template +class eoRndGenerator : public eoF +{ + typedef T AtomType; +}; + +/** + The class eoUniform can be used in the STL generate function + to easily generate random floats and doubles. It can also + be used for ints and unsigneds by virtue of the static_cast + in the generator function. + + Also present is a specialization for boolean, that will + ignore the minima and maxima that are possibly set and will + return an unbiased flip of a coin. For a biased flip, use the eoBoolean + + either in [0, _max) if only 1 value (_max) is given + (or none, as _max defaults to 1.0) + or in [_min,_max) if 2 values are given (_min, _max) +*/ +template class eoUniformGenerator : public eoRndGenerator +{ + // added new ctor with 2 params, and modified the data to minim and range + // (was maxim only). MS 3/11/2000 + public : + eoUniformGenerator(T _max = T(1.0), eoRng& _rng = rng) : + minim(T(0.0)), range(_max), uniform(_rng) {} + eoUniformGenerator(T _min, T _max, eoRng& _rng = rng) : + minim(_min), range(_max-_min), uniform(_rng) + { + if (_min>_max) + throw std::logic_error("Min is greater than Max in uniform_generator"); + } + + /** + Generates the number, uses a static_cast to get the right behaviour + for ints and unsigneds + */ + T operator()(void) { return minim+static_cast(uniform.uniform(range)); } + /** @example t-eoUniform.cpp + */ + +private : + T minim; + T range; + eoRng& uniform; +}; +/** @example t-eoRandom.cpp + */ + + +/// Specialization for bool, does an unbiased coin flip +template <> +inline bool eoUniformGenerator::operator()(void) +{ + return uniform.flip(0.5); +} + +/** + The class eoBooleanGenerator can be used in the STL generate function + to easily generate random booleans with a specified bias + \ingroup bitstring +*/ +class eoBooleanGenerator : public eoRndGenerator +{ + public : + eoBooleanGenerator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {} + + bool operator()(void) { return gen.flip(bias); } + private : + float bias; + eoRng& gen; +}; + +/** + The class normal_generator can be used in the STL generate function + to easily generate gaussian distributed floats and doubles. The user + can supply a standard deviation which defaults to 1. +*/ +template class eoNormalGenerator : public eoRndGenerator +{ + public : + eoNormalGenerator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} + + T operator()(void) { return (T) normal.normal(stdev); } + + private : + T stdev; + eoRng& normal; +}; + +/** + The class negexp_generator can be used in the STL generate function + to easily generate negative exponential distributed floats and doubles. The user + can supply a mean. +*/ +template class eoNegExpGenerator : public eoRndGenerator +{ + public : + eoNegExpGenerator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {} + + T operator()(void) { return (T) negexp.negexp(mean); } + + private : + T mean; + eoRng& negexp; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/eoScalarFitnessStat.h b/deprecated/eo/src/utils/eoScalarFitnessStat.h new file mode 100644 index 000000000..e56e46822 --- /dev/null +++ b/deprecated/eo/src/utils/eoScalarFitnessStat.h @@ -0,0 +1,65 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoScalarFitnessStat.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoScalarFitnessStat_h +#define _eoScalarFitnessStat_h + +#include +#include + +/** + The fitnesses of a whole population, as a std::vector + + @ingroup Stats +*/ +template +class eoScalarFitnessStat : public eoSortedStat > +{ +public: + + using eoSortedStat >::value; + + eoScalarFitnessStat(std::string _description = "FitnessES", + eoRealVectorBounds & _bounds = eoDummyVectorNoBounds) + : eoSortedStat >(std::vector(0), _description), + range(*_bounds[0]) + {} + + virtual void operator()(const std::vector& _popPters) + { + value().resize(_popPters.size()); + for (unsigned i=0; i<_popPters.size(); i++) + { + value()[i] = _popPters[i]->fitness(); + range.truncate(value()[i]); + } + } + +private : + eoRealBounds & range; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoSignal.cpp b/deprecated/eo/src/utils/eoSignal.cpp new file mode 100644 index 000000000..745d21bd3 --- /dev/null +++ b/deprecated/eo/src/utils/eoSignal.cpp @@ -0,0 +1,36 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/** + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: http://eodev.sourceforge.net + + Autors: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + Caner.Candan@univ-angers.fr +*/ + +#include + +/** + * @addtogroup Continuators + * @{ + */ + +// --- Global variables - but don't know what else to do - MS --- +std::map< int, bool > signals_called; + +/** @} */ diff --git a/deprecated/eo/src/utils/eoSignal.h b/deprecated/eo/src/utils/eoSignal.h new file mode 100644 index 000000000..9a89cb196 --- /dev/null +++ b/deprecated/eo/src/utils/eoSignal.h @@ -0,0 +1,106 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/** + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: http://eodev.sourceforge.net + + Authors: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + Caner.Candan@univ-angers.fr +*/ + +#ifndef _eoSignal_h +#define _eoSignal_h + +#include +#include +#include + +#include +#include + +/** + * @addtogroup Continuators + * @{ + */ + +extern std::map< int, bool > signals_called; + +/** eoSignal inherits from eoCheckPoint including signals handling (see signal(7)) + * + * @ingroup Utilities + */ +template +class eoSignal : public eoCheckPoint +{ +public : + + eoSignal( int sig = SIGINT ) : eoCheckPoint( _dummyContinue ), _sig( sig ) + { + ::signals_called[_sig] = false; + +#ifndef _WINDOWS +#ifdef SIGQUIT + ::signal( _sig, handler ); +#endif // !SIGQUIT +#endif // !_WINDOWS + } + + eoSignal( eoContinue& _cont, int sig = SIGINT ) : eoCheckPoint( _cont ), _sig( sig ) + { + ::signals_called[_sig] = false; + +#ifndef _WINDOWS +#ifdef SIGQUIT + ::signal( _sig, handler ); +#endif // !SIGQUIT +#endif // !_WINDOWS + } + + bool operator()( const eoPop& _pop ) + { + bool& called = ::signals_called[_sig]; + if ( called ) + { + eo::log << eo::logging << "Signal granted…" << std::endl ; + called = false; + return this->eoCheckPoint::operator()( _pop ); + } + return true; + } + + virtual std::string className(void) const { return "eoSignal"; } + + static void handler( int sig ) + { + ::signals_called[sig] = true; + eo::log << eo::logging << "Signal wished…" << std::endl ; + } + +private: + class DummyContinue : public eoContinue + { + public: + bool operator() ( const eoPop& ) { return true; } + } _dummyContinue; + + int _sig; +}; + +/** @} */ + +#endif // !_eoSignal_h diff --git a/deprecated/eo/src/utils/eoStat.h b/deprecated/eo/src/utils/eoStat.h new file mode 100644 index 000000000..32c3bf9f6 --- /dev/null +++ b/deprecated/eo/src/utils/eoStat.h @@ -0,0 +1,495 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStat.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +// (c) 2010 Thales group +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Contact: http://eodev.sourceforge.net + + Authors: + todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + Johann Dréo + */ +//----------------------------------------------------------------------------- + +#ifndef _eoStat_h +#define _eoStat_h + +#include // accumulate + +#include +#include +#include +#include +//#include + +/** @defgroup Stats Statistics computation + * + * Compute various statistics on a population. + * + * Objects of those classes are generally called by an eoCheckPoint + * to compute statistics about the population at a given generation. + * As they inherit from eoValueParam, they can be printed drectly, + * for instance by an eoMonitor. + * + * @see eoCheckPoint + * @see eoMonitor + * + * @ingroup Utilities + * @{ + */ + +/** + Base class for all statistics that need to be calculated + over the (unsorted) population + (I guess it is not really necessary? MS. + Depstd::ends, there might be reasons to have a stat that is not an eoValueParam, + but maybe I'm just kidding myself, MK) +*/ +template +class eoStatBase : public eoUF&, void> +{ +public: + virtual void lastCall(const eoPop&) {} + virtual std::string className(void) const { return "eoStatBase"; } +}; + + +template class eoCheckPoint; + +/** + The actual class that will be used as base for all statistics + that need to be calculated over the (unsorted) population + It is an eoStatBase AND an eoValueParam so it can be used in Monitors. +*/ +template +class eoStat : public eoValueParam, public eoStatBase +{ +public: + + eoStat(T _value, std::string _description) + : eoValueParam(_value, _description) + {} + + virtual std::string className(void) const + { return "eoStat"; } + + + eoStat& addTo(eoCheckPoint& cp) { cp.add(*this); return *this; } + eoStat& addTo(eoMonitor& mon) { mon.add(*this); return *this; } +}; + + + +/** + Base class for statistics calculated over a sorted snapshot of the population +*/ +template +class eoSortedStatBase : public eoUF&, void> +{ +public: + virtual void lastCall(const std::vector&) {} + virtual std::string className(void) const { return "eoSortedStatBase"; } + +}; + +/** + The actual class that will be used as base for all statistics + that need to be calculated over the sorted population + It's an eoSortedStatBase AND an eoValueParam so it can be used in Monitors. +*/ +template +class eoSortedStat : public eoSortedStatBase, public eoValueParam +{ +public : + eoSortedStat(ParamType _value, std::string _desc) : eoValueParam(_value, _desc) {} + virtual std::string className(void) const { return "eoSortedStat"; } + + eoSortedStat& addTo(eoCheckPoint& cp) { cp.add(*this); return *this; } + eoSortedStat& addTo(eoMonitor& mon) { mon.add(*this); return *this; } +}; + +/** + Average fitness of a population. Fitness can be: + - double + - eoMinimizingFitness or eoMaximizingFitness + The average of each objective is evaluated. + + ( For eoScalarFitnessAssembled user eoAssembledFitnessStat classes.) +*/ +#if defined(_MSC_VER) && (_MSC_VER < 1300) +template class eoAverageStat : public eoStat +#else +template class eoAverageStat : public eoStat +#endif +{ +public : + + using eoStat::value; + + typedef typename EOT::Fitness Fitness; + + eoAverageStat(std::string _description = "Average Fitness") + : eoStat(Fitness(), _description) {} + + static Fitness sumFitness(double _sum, const EOT& _eot){ + _sum += _eot.fitness(); + return _sum; + } + + eoAverageStat(double _value, std::string _desc) : eoStat(_value, _desc) {} + + virtual void operator()(const eoPop& _pop){ + doit(_pop, Fitness()); // specializations for scalar and std::vector + } + + virtual std::string className(void) const { return "eoAverageStat"; } + +private : + + // Default behavior + template + void doit(const eoPop& _pop, T) + { + Fitness v = std::accumulate(_pop.begin(), _pop.end(), Fitness(0.0), eoAverageStat::sumFitness); + + value() = v / _pop.size(); + } + +}; + +/** + Average fitness + Std. dev. of a population, fitness needs to be scalar. +*/ +template +class eoSecondMomentStats : public eoStat > +{ +public : + + using eoStat >::value; + + typedef typename EOT::Fitness fitness_type; + + typedef std::pair SquarePair; + + eoSecondMomentStats(std::string _description = "Average & Stdev") + : eoStat(std::make_pair(0.0,0.0), _description) + {} + + static SquarePair sumOfSquares(SquarePair _sq, const EOT& _eo) + { + double fitness = _eo.fitness(); + + _sq.first += fitness; + _sq.second += fitness * fitness; + return _sq; + } + + virtual void operator()(const eoPop& _pop) + { + SquarePair result = std::accumulate(_pop.begin(), _pop.end(), std::make_pair(0.0, 0.0), eoSecondMomentStats::sumOfSquares); + + double n = _pop.size(); + value().first = result.first / n; // average + value().second = sqrt( (result.second - n * value().first * value().first) / (n - 1.0)); // stdev + } + + virtual std::string className(void) const { return "eoSecondMomentStats"; } +}; + +/** + The n_th element fitness in the population (see eoBestFitnessStat) +*/ +#if defined(_MSC_VER) && (_MSC_VER < 1300) +template +class eoNthElementFitnessStat : public eoSortedStat +#else +template +class eoNthElementFitnessStat : public eoSortedStat +#endif +{ +public : + using eoSortedStat::value; + + typedef typename EOT::Fitness Fitness; + + eoNthElementFitnessStat(unsigned _whichElement, std::string _description = "nth element fitness") + : eoSortedStat(Fitness(), _description), whichElement(_whichElement) {} + + virtual void operator()(const std::vector& _pop) + { + if (whichElement > _pop.size()) + throw std::logic_error("fitness requested of element outside of pop"); + + doit(_pop, Fitness()); + } + + virtual std::string className(void) const { return "eoNthElementFitnessStat"; } +private : + + struct CmpFitness + { + CmpFitness(unsigned _whichElement, bool _maxim) : whichElement(_whichElement), maxim(_maxim) {} + + bool operator()(const EOT* a, const EOT* b) + { + if (maxim) + return a->fitness()[whichElement] > b->fitness()[whichElement]; + + return a->fitness()[whichElement] < b->fitness()[whichElement]; + } + + unsigned whichElement; + bool maxim; + }; + + // for everything else + template + void doit(const std::vector& _pop, T) + { + value() = _pop[whichElement]->fitness(); + } + + unsigned whichElement; +}; + +/* Actually, you shouldn't need to sort the population to get the best fitness + MS - 17/11/00 + + But then again, if another stat needs sorted fitness anyway, getting the best + out would be very fast. + MK - 09/01/03 + +template +class eoBestFitnessStat : public eoStat +{ +public : + typedef typename EOT::Fitness Fitness; + + eoBestFitnessStat(std::string _description = "Best Fitness") : + eoStat(Fitness(), _description) {} + + virtual void operator()(const eoPop& _pop) + { + value() = _pop.nth_element_fitness(0); + } + +}; +*/ + +/** + Best fitness of a population. Fitness can be: + - double + - eoMinimizingFitness or eoMaximizingFitness + + ( For eoScalarFitnessAssembled look at eoAssembledFitnessStat ) +*/ + +#if defined(_MSC_VER) && (_MSC_VER < 1300) +template +class eoBestFitnessStat : public eoStat +#else +template +class eoBestFitnessStat : public eoStat +#endif +{ +public: + + using eoStat::value; + + typedef typename EOT::Fitness Fitness; + + eoBestFitnessStat(std::string _description = "Best ") + : eoStat(Fitness(), _description) + {} + + void operator()(const eoPop& _pop) { + doit(_pop, Fitness() ); // specializations for scalar and std::vector + } + + virtual std::string className(void) const { return "eoBestFitnessStat"; } + + +private : + + struct CmpFitness + { + CmpFitness(unsigned _which, bool _maxim) : which(_which), maxim(_maxim) {} + + bool operator()(const EOT& a, const EOT& b) + { + if (maxim) + return a.fitness()[which] < b.fitness()[which]; + + return a.fitness()[which] > b.fitness()[which]; + } + + unsigned which; + bool maxim; + }; + + // default + template + void doit(const eoPop& _pop, T) + { // find the largest elements + value() = _pop.best_element().fitness(); + } + +}; +/** @example t-eoSSGA.cpp + */ + +template +class eoDistanceStat : public eoStat +{ +public: + + using eoStat::value; + + eoDistanceStat(std::string _name = "distance") + : eoStat(0.0, _name) + {} + + template + double distance(T a, T b) + { + T res = a-b; + return res < 0? -res : res; + } + + double distance(bool a, bool b) + { + return (a==b)? 0 : 1; + } + + void operator()(const eoPop& _pop) + { + double& v = value(); + v = 0.0; + + for (unsigned i = 0; i < _pop.size(); ++i) + { + for (unsigned j = 0; j < _pop.size(); ++j) + { + for (unsigned k = 0; k < _pop[i].size(); ++k) + { + v += distance(_pop[i][k], _pop[j][k]); + } + } + } + + double sz = _pop.size(); + v /= sz * sz * _pop[0].size(); + } + virtual std::string className(void) const { return "eoDistanceStat"; } + +}; + + + +/* +template +class eoStdevStat : public eoStat +{ +public : + typedef typename eoSecondMomentStats::SquarePair SquarePair; + + eoStdevStat(std::string _description = "Stdev") : eoStat(0.0, _description) {} + + virtual void operator()(const eoPop& _pop) + { + SquarePair result = std::accumulate(pop.begin(), pop.end(), std::make_pair(0.0, 0.0), eoSecondMomentStats::sumOfSquares); + + double n = pop.size(); + value() = sqrt( (result.second - (result.first / n)) / (n - 1.0)); // stdev + } +}; +*/ + + +//! A robust measure of dispersion (also called midspread or middle fifty) that is the difference between the third and the first quartile. +template +class eoInterquartileRangeStat : public eoStat< EOT, typename EOT::Fitness > +{ +public: + using eoStat::value; + + eoInterquartileRangeStat( typename EOT::Fitness start, std::string description = "IQR" ) : eoStat( start, description ) {} + + virtual void operator()( const eoPop & _pop ) + { + if( _pop.size() == 0 ) { + // how to implement value() = 0 ? + + } else { + eoPop pop = _pop; + + unsigned int quartile = pop.size()/4; + std::nth_element( pop.begin(), pop.begin()+quartile*1, pop.end() ); + typename EOT::Fitness Q1 = pop[quartile].fitness(); + + std::nth_element( pop.begin(), pop.begin()+quartile*3, pop.end() ); + typename EOT::Fitness Q3 = pop[quartile*3].fitness(); + + value() = Q3 - Q1; + } + } + + virtual std::string className(void) const { return "eoInterquartileRangeStat"; } +}; +/** @example t-eoIQRStat.cpp + */ + +/** Compute the average size of indivudals over the population + * + * Obviously, will work only on representations that implement the (standard) "size()" method, + * like any STL container. + */ +template +class eoAverageSizeStat : public eoStat< EOT, double> +{ +public: + + using eoStat::value; + + eoAverageSizeStat( std::string description = "Av.Size" ) : + eoStat( 0.0, description ) {} // 0 by default + + virtual void operator()( const eoPop & pop ) + { + size_t pop_size = pop.size(); + + std::vector sizes; + sizes.reserve(pop_size); + + for( unsigned int i=0, s = pop_size; i(sum) / static_cast(pop_size); + } + + virtual std::string className(void) const { return "eoAverageSizeStat"; } +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/eoState.cpp b/deprecated/eo/src/utils/eoState.cpp new file mode 100644 index 000000000..d9d06d99e --- /dev/null +++ b/deprecated/eo/src/utils/eoState.cpp @@ -0,0 +1,194 @@ +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include "eoState.h" +#include "eoObject.h" +#include "eoPersistent.h" + +using namespace std; + + + +void removeComment(string& str, string comment) +{ + string::size_type pos = str.find(comment); + + if (pos != string::npos) + { + str.erase(pos, str.size()); + } +} + +bool is_section(const string& str, string& name) +{ + string::size_type pos = str.find("\\section{"); + + if (pos == string::npos) + return false; + //else + + string::size_type end = str.find("}"); + + if (end == string::npos) + return false; + // else + + name = str.substr(pos + 9, end-9); + + return true; +} + +eoState::~eoState(void) +{ + for (unsigned i = 0; i < ownedObjects.size(); ++i) + { + delete ownedObjects[i]; + } +} + +void eoState::registerObject(eoPersistent& registrant) +{ + string name = createObjectName(dynamic_cast(®istrant)); + + pair res = objectMap.insert(make_pair(name, ®istrant)); + + if (res.second == true) + { + creationOrder.push_back(res.first); + } + else + { + throw logic_error("Interval error: object already present in the state"); + } +} + +void eoState::load(const string& _filename) +{ + ifstream is (_filename.c_str()); + + if (!is) + { + string str = "Could not open file " + _filename; + throw runtime_error(str); + } + + load(is); +} + +void eoState::load(std::istream& is) +{ + string str; + string name; + + getline(is, str); + + if (is.fail()) + { + string str = "Error while reading stream"; + throw runtime_error(str); + } + + while(! is.eof()) + { // parse section header + if (is_section(str, name)) + { + string fullString; + ObjectMap::iterator it = objectMap.find(name); + + if (it == objectMap.end()) + { // ignore + while (getline(is, str)) + { + if (is_section(str, name)) + break; + } + } + else + { + + eoPersistent* object = it->second; + + // now we have the object, get lines, remove comments etc. + + string fullstring; + + while (getline(is, str)) + { + if (is.eof()) + throw runtime_error("No section in load file"); + if (is_section(str, name)) + break; + + removeComment(str, getCommentString()); + fullstring += str + "\n"; + } + istringstream the_stream(fullstring); + object->readFrom(the_stream); + } + } + else // if (is_section(str, name)) - what if file empty + { + getline(is, str); // try next line! + // if (is.eof()) + // throw runtime_error("No section in load file"); + } + } + +} + +void eoState::save(const string& filename) const +{ // saves in order of insertion + ofstream os(filename.c_str()); + + if (!os) + { + string msg = "Could not open file: " + filename + " for writing!"; + throw runtime_error(msg); + } + + save(os); +} + +void eoState::save(std::ostream& os) const +{ // saves in order of insertion + for (vector::const_iterator it = creationOrder.begin(); it != creationOrder.end(); ++it) + { + os << "\\section{" << (*it)->first << "}\n"; + (*it)->second->printOn(os); + os << '\n'; + } +} + +string eoState::createObjectName(eoObject* obj) +{ + if (obj == 0) + { + ostringstream os; + os << objectMap.size(); + return os.str(); + } + // else + + string name = obj->className(); + ObjectMap::const_iterator it = objectMap.find(name); + + unsigned count = 1; + while (it != objectMap.end()) + { + ostringstream os; + os << obj->className().c_str() << count++; + name = os.str(); + it = objectMap.find(name); + } + + return name; +} diff --git a/deprecated/eo/src/utils/eoState.h b/deprecated/eo/src/utils/eoState.h new file mode 100644 index 000000000..53c3a83d5 --- /dev/null +++ b/deprecated/eo/src/utils/eoState.h @@ -0,0 +1,138 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoState.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoState_h +#define eoState_h + +#include +#include +#include +#include + +#include + +class eoObject; +class eoPersistent; + +/** + eoState can be used to register derivants of eoPersistent. It will + then in turn implement the persistence framework through members load + and save, that will call readFrom and printOn for the registrated objects. + + It is derived from eoFunctorStore, so that it also serves as a place where + all those nifty eo functors can be stored. This is useful in the case you + want to use one of the make_* functions. These functions generally take as their + last argument an eoFunctorStore (or a state) which is used to hold all dynamically + generated data. Note however, that unlike with eoPersistent derived classes, eoFunctorBase + derived classes are not saved or loaded. To govern the creation of functors, + command-line parameters (which can be stored) are needed. + + @ingroup Utilities +*/ +class eoState : public eoFunctorStore +{ +public : + + eoState(void) {} + + ~eoState(void); + + /** + * Object registration function, note that it does not take ownership! + */ + void registerObject(eoPersistent& registrant); + + /** + * Copies the object (MUST be derived from eoPersistent) + * and returns a reference to the owned object. + * Note: it does not register the object, this must be done afterwards! + */ + template + T& takeOwnership(const T& persistent) + { + // If the compiler budges here, T is not a subclass of eoPersistent + ownedObjects.push_back(new T(persistent)); + return static_cast(*ownedObjects.back()); + } + + /** + * Loading error thrown when nothing seems to work. + */ + struct loading_error : public std::runtime_error + { + loading_error(std::string huh = "Error while loading") : std::runtime_error(huh) {} + }; + + std::string getCommentString(void) const { return "#"; } + + /** + * Reads the file specified + * + * @param _filename the name of the file to load from + */ + void load(const std::string& _filename); + + /** + * Reads the file specified + * + * @param is the stream to load from + */ + void load(std::istream& is); + + /** + * Saves the state in file specified + * + * @param _filename the name of the file to save into + */ + void save(const std::string& _filename) const; + + /** + * Saves the state in file specified + * + * @param os the stream to save into + */ + void save(std::ostream& os) const; + +private : + std::string createObjectName(eoObject* obj); + + // first is Persistent, second is the raw data associated with it. + typedef std::map ObjectMap; + + ObjectMap objectMap; + + std::vector creationOrder; + std::vector ownedObjects; + + // private copy and assignment as eoState is supposed to be unique + eoState(const eoState&); + eoState& operator=(const eoState&); + +}; +/** @example t-eoStateAndParser.cpp + */ + +#endif diff --git a/deprecated/eo/src/utils/eoStdoutMonitor.h b/deprecated/eo/src/utils/eoStdoutMonitor.h new file mode 100644 index 000000000..07c5a02f6 --- /dev/null +++ b/deprecated/eo/src/utils/eoStdoutMonitor.h @@ -0,0 +1,61 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +/* +(c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +(c) Thales group, 2010 + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Contact: http://eodev.sourceforge.net + +Authors: + todos@geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + Johann Dréo +*/ + +#ifndef _eoStdoutMonitor_h +#define _eoStdoutMonitor_h + +#include + +#include +#include + +/** + Prints statistics to stdout + + @ingroup Monitors +*/ +class eoStdoutMonitor : public eoOStreamMonitor +{ +public : + eoStdoutMonitor(bool _verbose, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + eoOStreamMonitor( std::cout, _verbose, _delim, _width, _fill) + { +#ifndef DEPRECATED_MESSAGES + eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoStdoutMonitor constructor is deprecated and will be removed in the next release" << std::endl; +#endif // !DEPRECATED_MESSAGES + } + + eoStdoutMonitor(std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + eoOStreamMonitor( std::cout, _delim, _width, _fill) + {} + + virtual std::string className(void) const { return "eoStdoutMonitor"; } +}; + +#endif diff --git a/deprecated/eo/src/utils/eoTimeCounter.h b/deprecated/eo/src/utils/eoTimeCounter.h new file mode 100644 index 000000000..623714156 --- /dev/null +++ b/deprecated/eo/src/utils/eoTimeCounter.h @@ -0,0 +1,74 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoTimeCounter.h +// (c) Marc Schoenauer, Maarten Keijzer, and GeNeura Team, 2002 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@inria.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoTimeCounter_h +#define _eoTimeCounter_h + +#include +#include + + +/** + An eoStat that simply gives the user time since first generation + It has to be tempatized by EOT because it must be an eoStat + + @ingroup Stats +*/ +class eoTimeCounter : public eoUpdater, public eoValueParam +{ +public: + eoTimeCounter() : eoValueParam(0.0, "Time") // : firstTime(true) + { + start = time(NULL); + } + + /** simply stores the time spent in process in its value() */ + virtual void operator()() + { + // ask for system time + utime = clock(); + + // if (firstTime) /* first generation */ + // { + // firstTime=false; + // firstUtime = tmsStruct.tms_utime; + // } + // store elapsed user time + // value(tmsStruct.tms_utime - firstUtime); + // value()=double(utime)/CLOCKS_PER_SEC; + double seconds_elapsed = time(NULL) - start; + + value() = (seconds_elapsed > 2140) ? seconds_elapsed : double(utime)/CLOCKS_PER_SEC; + } + +private: +// bool firstTime; +// clock_t firstUtime; + clock_t utime; + time_t start; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoTimedMonitor.h b/deprecated/eo/src/utils/eoTimedMonitor.h new file mode 100644 index 000000000..a06ae6cce --- /dev/null +++ b/deprecated/eo/src/utils/eoTimedMonitor.h @@ -0,0 +1,88 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoTimedMonitor.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2005 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoTimedMonitor_h +#define _eoTimedMonitor_h + +#include +#include + +#include +#include + +/** + Holds a collection of monitors and only fires them when a time limit + has been reached + + @ingroup Monitors +*/ +class eoTimedMonitor : public eoMonitor +{ +public: + + /** Constructor + + No negative time can be specified, use 0 if you want it to fire "always". + @param seconds_ Specify time limit (s). + */ + eoTimedMonitor(unsigned seconds_) : last_tick(0), seconds(seconds_) {} + + eoMonitor& operator()(void) { + bool monitor = false; + if (last_tick == 0) { + monitor = true; + last_tick = clock(); + } + + clock_t tick = clock(); + + if ( (unsigned)(tick-last_tick) >= seconds * CLOCKS_PER_SEC) { + monitor = true; + } + + if (monitor) { + for (unsigned i = 0; i < monitors.size(); ++i) { + (*monitors[i])(); + } + last_tick = clock(); + } + return *this; + } + + void add(eoMonitor& mon) { monitors.push_back(&mon); } + + virtual std::string className(void) const { return "eoTimedMonitor"; } + +private: + + clock_t last_tick; + + unsigned seconds; + + std::vector monitors; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoUniformInit.h b/deprecated/eo/src/utils/eoUniformInit.h new file mode 100644 index 000000000..cede61b73 --- /dev/null +++ b/deprecated/eo/src/utils/eoUniformInit.h @@ -0,0 +1,161 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoUniformInit.h + + (c) Maarten Keijzer, GeNeura Team, Marc Schoenauer, 1999 - 2002 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@inria.fr + */ + +//----------------------------------------------------------------------------- +/** Copied from the eoRndGenerators to have objects deriving from eoInit + * As the whole initialization mechanism in EO is based on eoInit rather than + * eoRndGenerators, we might as well have these directly written without + * overhead + +@class eoUniformInit uniform initialization for doubles, floats, ints, ... +@class eoBooleanInit biased init for booleans +@class eoNormalInit normal intialization for doubles and floats +@class eoNegExpInit negative exponential distributions " +*/ + +#ifndef eoUniformInit_h +#define eoUniformInit_h + +#include "eoRNG.h" +#include "eoInit.h" +#include "eoRealBounds.h" +#include + + +/** @addtogroup Initializators + * @{ + */ + +using eo::rng; + +/** + The class eoUniformInit can be used in the STL apply function + to easily randomize floats and doubles. It can also + be used for ints and unsigneds by virtue of the static_cast + + Also present is a specialization for boolean, that will + ignore the minima and maxima that are possibly set and will + return an unbiased flip of a coin. For a biased flip, use the eoBoolean + + either in [0, _max) if only 1 value (_max) is given + (or none, as _max defaults to 1.0) + or in [_min,_max) if 2 values are given (_min, _max) + +*/ +template class 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) + {} + + /** Ctor with an eoRealBound */ + eoUniformInit(eoRealBounds & _bound, eoRng& _rng = rng) : + minim(_bound.minimum()), range(_bound.range()), uniform(_rng) + {} + + /** Ctor with explicit min and max */ + eoUniformInit(T _min, T _max, eoRng& _rng = rng) : + minim(_min), range(_max-_min), uniform(_rng) + { + if (_min>_max) + throw std::logic_error("Min is greater than Max in uniform_generator"); + } + + /** + Generates the number, uses a static_cast to get the right behaviour + for ints and unsigneds + */ + void operator()(T & _t) + { + _t = minim+static_cast(uniform.uniform(range)); + } + +private : + T minim; + T range; + eoRng& uniform; +}; + + +/** Specialization for bool, does an unbiased coin flip */ +template <> +inline void eoUniformInit::operator()(bool & _b) +{ + _b = uniform.flip(0.5); +} + +/** + The class eoBooleanInit can be used in the STL apply function + to easily generate random booleans with a specified bias +*/ +class eoBooleanInit : public eoInit +{ + public : + eoBooleanInit(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {} + + void operator()(bool & _b) { _b = gen.flip(bias); } + private : + float bias; + eoRng& gen; +}; + +/** + The class normal_generator can be used in the STL generate function + to easily generate gaussian distributed floats and doubles. The user + can supply a standard deviation which defaults to 1. +*/ +template class eoNormalInit : public eoInit +{ + public : + eoNormalInit(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} + + void operator()(T & _t) { _t = (T) normal.normal(stdev); } + + private : + T stdev; + eoRng& normal; +}; + +/** + The class negexp_generator can be used in the STL generate function + to easily generate negative exponential distributed floats and doubles. The user + can supply a mean. +*/ +template class eoNegExpInit : public eoInit +{ + public : + eoNegExpInit(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {} + + void operator()(T & _t) { _t = (T) negexp.negexp(mean); } + + private : + T mean; + eoRng& negexp; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/eoUpdatable.h b/deprecated/eo/src/utils/eoUpdatable.h new file mode 100644 index 000000000..202ef962c --- /dev/null +++ b/deprecated/eo/src/utils/eoUpdatable.h @@ -0,0 +1,119 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoUpdatable.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoUpdatable_h +#define _eoUpdatable_h + +#include + +/** + eoUpdatable is a generic class for adding updatation to an existing class + Just says it has an update() method + + @ingroup Utilities +*/ +class eoUpdatable +{ +public: + + /** @brief Virtual destructor */ + virtual ~eoUpdatable() {}; + + virtual void update() = 0; +}; + + + +/** + A base class to actually update an eoUpdatable object + + @ingroup Utilities +*/ +class eoDynUpdater : public eoUpdater +{public : + eoDynUpdater(eoUpdatable & _toUpdate) : toUpdate(_toUpdate) {}; + + virtual void operator()() + { + toUpdate.update(); + } + +private: + eoUpdatable& toUpdate; +}; + +/** + An eoUpdater to update an eoUpdatable object every given time interval + + @ingroup Utilities +*/ +class eoTimedDynUpdate : public eoDynUpdater +{ +public : + eoTimedDynUpdate(eoUpdatable & _toUpdate, time_t _interval) : + eoDynUpdater(_toUpdate), + interval(_interval), last_time(time(0)), first_time(time(0)) {} + + void operator()(void) + { + time_t now = time(0); + + if (now >= last_time + interval) + { + last_time = now; + eoDynUpdater::operator() (); + } + } +private : + const time_t interval; + time_t last_time; + const time_t first_time; +}; + +/** + An eoUpdater to update an eoUpdatable object every given tic + + @ingroup Utilities +*/ +class eoCountedDynUpdate : public eoDynUpdater +{ +public : + eoCountedDynUpdate(eoUpdatable & _toUpdate, unsigned _interval) + : eoDynUpdater(_toUpdate), interval(_interval), counter(0) {} + + void operator()(void) + { + if (++counter % interval == 0) + { + eoDynUpdater::operator() (); + } + } +private : + const unsigned interval; + unsigned counter; +}; + +#endif diff --git a/deprecated/eo/src/utils/eoUpdater.cpp b/deprecated/eo/src/utils/eoUpdater.cpp new file mode 100644 index 000000000..dd6a38960 --- /dev/null +++ b/deprecated/eo/src/utils/eoUpdater.cpp @@ -0,0 +1,46 @@ +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +#include +#include + +using namespace std; + +void eoTimedStateSaver::operator()(void) +{ + time_t now = time(0); + + if (now >= last_time + interval) + { + last_time = now; + ostringstream os; + os << prefix << (now - first_time) << '.' << extension; + state.save(os.str()); + } +} + +void eoCountedStateSaver::doItNow(void) +{ + ostringstream os; + os << prefix << counter << '.' << extension; + state.save(os.str()); +} + +void eoCountedStateSaver::operator()(void) +{ + if (++counter % interval == 0) + doItNow(); +} + +void eoCountedStateSaver::lastCall(void) +{ + if (saveOnLastCall) + doItNow(); +} diff --git a/deprecated/eo/src/utils/eoUpdater.h b/deprecated/eo/src/utils/eoUpdater.h new file mode 100644 index 000000000..072b9a9bb --- /dev/null +++ b/deprecated/eo/src/utils/eoUpdater.h @@ -0,0 +1,172 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoUpdater.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoUpdater_h +#define _eoUpdater_h + +#include +#include +#include +#include + +template class eoCheckPoint; + +/** + eoUpdater is a generic procudere for updating whatever you want. + Yet again an empty name + + @ingroup Utilities +*/ +class eoUpdater : public eoF +{ +public: + virtual void lastCall() {} + virtual std::string className(void) const { return "eoUpdater"; } + + template + eoUpdater& addTo(eoCheckPoint& cp) { cp.add(*this); return *this; } +}; + +/** + an eoUpdater that simply increments a counter + + @ingroup Utilities +*/ +template +class eoIncrementor : public eoUpdater +{public : + /** Default Ctor - requires a reference to the thing to increment */ + eoIncrementor(T& _counter, T _stepsize = 1) : counter(_counter), stepsize(_stepsize) {} + + /** Simply increments */ + virtual void operator()() + { + counter += stepsize; + } + + virtual std::string className(void) const { return "eoIncrementor"; } +private: + T& counter; + T stepsize; +}; + +/** an eoUpdater that is an eoValueParam (and thus OWNS its counter) + * Mandatory for generation counter in make_checkpoint + + @ingroup Utilities +*/ +template +class eoIncrementorParam : public eoUpdater, public eoValueParam +{ +public: + + using eoValueParam::value; + + /** Default Ctor : a name and optionally an increment*/ + eoIncrementorParam( std::string _name, T _stepsize = 1) : + eoValueParam(T(0), _name), stepsize(_stepsize) {} + + /** Ctor with a name and non-zero initial value + * and mandatory stepSize to remove ambiguity + */ + eoIncrementorParam( std::string _name, T _countValue, T _stepsize) : + eoValueParam(_countValue, _name), stepsize(_stepsize) {} + + /** Simply increments */ + virtual void operator()() + { + value() += stepsize; + } + + virtual std::string className(void) const { return "eoIncrementorParam"; } + +private: + T stepsize; +}; + +#include + +/** + an eoUpdater that saves a state every given time interval + + @ingroup Utilities +*/ +class eoTimedStateSaver : public eoUpdater +{ +public : + eoTimedStateSaver(time_t _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav") : state(_state), + interval(_interval), last_time(time(0)), first_time(time(0)), + prefix(_prefix), extension(_extension) {} + + void operator()(void); + + virtual std::string className(void) const { return "eoTimedStateSaver"; } +private : + const eoState& state; + + const time_t interval; + time_t last_time; + const time_t first_time; + const std::string prefix; + const std::string extension; +}; + +/** + an eoUpdater that saves a state every given generations + + @ingroup Utilities +*/ +class eoCountedStateSaver : public eoUpdater +{ +public : + eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix, bool _saveOnLastCall, std::string _extension = "sav", unsigned _counter = 0) + : state(_state), interval(_interval), counter(_counter), + saveOnLastCall(_saveOnLastCall), + prefix(_prefix), extension(_extension) {} + + eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav", unsigned _counter = 0) + : state(_state), interval(_interval), counter(_counter), + saveOnLastCall(true), + prefix(_prefix), extension(_extension) {} + + virtual void lastCall(void); + void operator()(void); + + virtual std::string className(void) const { return "eoCountedStateSaver"; } +private : + void doItNow(void); + + const eoState& state; + const unsigned interval; + unsigned counter; + bool saveOnLastCall; + + const std::string prefix; + const std::string extension; +}; + + +#endif diff --git a/deprecated/eo/src/utils/make_help.cpp b/deprecated/eo/src/utils/make_help.cpp new file mode 100644 index 000000000..a7ab040cd --- /dev/null +++ b/deprecated/eo/src/utils/make_help.cpp @@ -0,0 +1,120 @@ +//----------------------------------------------------------------------------- +// make_help.h +// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- +#ifdef _MSC_VER +// to avoid long name warnings +#pragma warning(disable:4786) +#endif + +#include +#include +#include + +#include + +using namespace std; + +/** Generation of the status file, and output of the help message if needed + * + * MUST be called after ALL parameters have been read in order to list them + * + * Warning: this is a plain .cpp file and shoudl NOT be included anywhere, + * but compiled separately and stored in a library. + * + * It is declared in all make_xxx.h files in representation-dependent dirs + * but it is NOT representation-dependent itself - that's why it's in utils + */ +void make_help(eoParser & _parser) +{ + // name of the "status" file where all actual parameter values will be saved + string str_status = _parser.ProgramName() + ".status"; // default value + eoValueParam& statusParam = _parser.createParam(str_status, "status","Status file",'\0', "Persistence" ); + + // dump status file BEFORE help, so the user gets a chance to use it: + // it's probably the case where she/he needs it most!!! + // Only help parameter will not be in status file - but who cares??? + if (statusParam.value() != "") + { + ofstream os(statusParam.value().c_str()); + os << _parser; // and you can use that file as parameter file + } + // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED + // i.e. in case you need parameters somewhere else, postpone these + if (_parser.userNeedsHelp()) + { + _parser.printHelp(cout); + cout << "You can use an edited copy of file " << statusParam.value() + << " as parameter file" << endl; + exit(1); + } +} + +/** test a dir. + * Creates it if does not exist + * If exists, throws an exception or erase everything there, + * depending on last parameter + * + * Always return true (for code easy writing on the other side :-) + */ +bool testDirRes(std::string _dirName, bool _erase=true) +{ + string s = "test -d " + _dirName; + int res = system(s.c_str()); + // test for (unlikely) errors + if ( (res==-1) || (res==127) ) + { + s = "Problem executing test of dir " + _dirName; + throw runtime_error(s); + } + // now make sure there is a dir without any file in it - or quit + if (res) // no dir present + { + s = string("mkdir ")+ _dirName; + int res = system(s.c_str()); + (void)res; + return true; + } + // else + if (_erase) // OK to erase + { + s = string("/bin/rm ")+ _dirName + "/*"; + int res = system(s.c_str()); + (void)res; + return true; + } + //else + // WARNING: bug if dir exists and is empty; this says it is not! + // shoudl use scandir instead - no time now :-((( MS Aug. 01 + s = "Dir " + _dirName + " is not empty"; + throw runtime_error(s); + return true; +} + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/pipecom.cpp b/deprecated/eo/src/utils/pipecom.cpp new file mode 100644 index 000000000..a175112f9 --- /dev/null +++ b/deprecated/eo/src/utils/pipecom.cpp @@ -0,0 +1,175 @@ +/* ---------------------------------------------------------------------- + * Where........: CMAP - Polytechnique + * File.........: pipecom.c + * Author.......: Bertrand Lamy (Equipe genetique) + * Created......: Mon Mar 13 13:50:11 1995 + * Description..: Communication par pipe bidirectionnel avec un autre process + * ---------------------------------------------------------------------- + */ + +// MSC equivalent must be written and tested or some #idef instructions added +// with a clear message at compile time that this is for Unix only ??? + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifndef _WINDOWS + +#include +#include +#include +#include +#include + +#include "pipecom.h" + + + +int Check( PCom *com ) +{ + if( ! com ) { + fprintf( stderr, "PipeCom: Null pointer.\n" ); + fflush( stderr ); + return 0; + } + if( kill( com->pid, 0 ) != 0 ) { + fprintf( stderr, "PipeCom: process doesn't exists.\n" ); + fflush( stderr ); + return 0; + } + return 1; +} + + +PCom * PipeComOpen( char *prog ) +{ + char *args[2]; + args[0] = prog; + args[1] = NULL; + return PipeComOpenArgv( prog, args ); +} + + +PCom * PipeComOpenArgv( char *prog, char *argv[] ) +{ + int toFils[2]; + int toPere[2]; + int sonPid; + PCom * ret = NULL; + + if( pipe( toFils ) < 0 ) { + perror( "PipeComOpen: Creating pipes" ); + return ret; + } + if( pipe( toPere ) < 0 ) { + perror( "PipeComOpen: Creating pipes" ); + return ret; + } + + switch( (sonPid = vfork()) ) { + case -1: + perror("PipeComOpen: fork failed" ); + return ret; + break; + + case 0: + /* --- Here's the son --- */ + /* --- replace old stdin --- */ + if( dup2( toFils[0], fileno(stdin) ) < 0 ) { + perror( "PipeComOpen(son): could not connect" ); + exit( -1 ); + /* --- AVOIR: kill my father --- */ + } + if( dup2( toPere[1], fileno(stdout) ) < 0 ) { + perror( "PipeComOpen(son): could not connect" ); + exit( -1 ); + } + if( execvp( prog, argv ) < 0 ) { + perror( prog ); + perror( "PipeComOpen: can't exec" ); + exit(1); + } + break; + default: + ret = (PCom *) malloc( sizeof(PCom) ); + if( ! ret ) + return NULL; + + ret->fWrit = (FILE *)fdopen( toFils[1], "w" ); + ret->fRead = (FILE *)fdopen( toPere[0], "r" ); + ret->pid = sonPid; + } + return ret; +} + + +int PipeComSend( PCom *to, const char *line ) +{ + int nb = 0; + if( ! Check(to ) ) + return nb; + nb = fprintf( to->fWrit, line, 0 ); + fflush( to->fWrit ); + return nb; +} + + +int PipeComSendn( PCom *to, const char *data, int n ) +{ + int nb = 0; + if( ! Check(to) ) + return nb; + + nb = fwrite( data, 1, n, to->fWrit ); + fflush( to->fWrit ); + return nb; +} + + +int PipeComReceive( PCom *from, char *data, int max ) +{ + if( ! Check(from) ) + return 0; + if( ! data ) { + fprintf( stderr, "PipeComReceive: Invalid data pointer\n" ); + fflush( stderr ); + return 0; + } + if( fgets( data, max, from->fRead ) ) + return strlen(data); + return 0; +} + + + +int PipeComClose( PCom *to ) +{ + if( ! Check(to) ) + return 0; + fclose( to->fRead ); + fclose( to->fWrit ); + free( to ); + return 1; +} + + + +int PipeComWaitFor( PCom *from, char *what ) +{ + char buffer[256]; + do { + if( ! PipeComReceive( from, buffer, 256 ) ) + return 0; + } while( strcmp( buffer, what ) ); + return 1; +} + +#endif /*_MSC_VER*/ + + +// Local Variables: +// coding: iso-8859-1 +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/pipecom.h b/deprecated/eo/src/utils/pipecom.h new file mode 100644 index 000000000..56b031708 --- /dev/null +++ b/deprecated/eo/src/utils/pipecom.h @@ -0,0 +1,47 @@ +/* ---------------------------------------------------------------------- + * Where........: CMAP - Polytechnique + * File.........: pipecom.h + * Author.......: Bertrand Lamy (EEAAX) + * Created......: Thu Mar 9 17:21:15 1995 + * Description..: Pipe communication with a process + * ---------------------------------------------------------------------- + */ + +// This file cannot be used from C any more due to some const additions. +// However, if you remove the const, it should work in C as well. + +#ifndef EO_PIPECOM_H +#define EO_PIPECOM_H + +#include + + +typedef struct PipeCommunication { + FILE *fWrit; + FILE *fRead; + int pid; +} PCom; + + +extern PCom *PipeComOpen( char *prog ); +extern PCom *PipeComOpenArgv( char *prog, char *argv[] ); + +extern int PipeComSend( PCom *to, const char *line ); +extern int PipeComSendn( PCom *to, const char *data, int n ); + +extern int PipeComReceive( PCom *from, char *data, int max ); + +extern int PipeComClose( PCom *to ); +extern int PipeComWaitFor( PCom *from, char *what ); + + +#endif // EO_PIPECOM_H + + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/src/utils/rnd_generators.h b/deprecated/eo/src/utils/rnd_generators.h new file mode 100644 index 000000000..d71caf803 --- /dev/null +++ b/deprecated/eo/src/utils/rnd_generators.h @@ -0,0 +1,173 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + rnd_generators.h + Some utility functors for generating random generators: + uniform_generator : generates uniform floats or doubles + random_generator : generates unsigneds, ints etc. + normal_generator : normally distributed floats or doubles + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +//----------------------------------------------------------------------------- + +#ifndef eoRND_GENERATORS_H +#define eoRND_GENERATORS_H + +#include "eoRNG.h" +#include + +/** @addtogroup Random + * @{ + */ + +/** + The class uniform_generator can be used in the STL generate function + to easily generate random floats and doubles + either in [0, _max) if only 1 value (_max) is given + (or none, as _max defaults to 1.0) + or in [_min,_max) if 2 values are given (_min, _max) +*/ +template class uniform_generator +{ + // added new ctor with 2 params, and modified the data to minim and range + // (was maxim only). MS 3/11/2000 + public : + uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : + minim(T(0.0)), range(_max), uniform(_rng) {} + uniform_generator(T _min, T _max, eoRng& _rng = rng) : + minim(_min), range(_max-_min), uniform(_rng) + { + if (_min>_max) + throw std::logic_error("Min is greater than Max in uniform_generator"); + } + + T operator()(void) { return minim+static_cast(uniform.uniform(range)); } + +private : + T minim; + T range; + eoRng& uniform; +}; + +/** + The class boolean_generator can be used in the STL generate function + to easily generate random booleans with a specified bias +*/ +class boolean_generator +{ + public : + boolean_generator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {} + + bool operator()(void) { return gen.flip(bias); } + private : + float bias; + eoRng& gen; +}; + +/** + The class random_generator can be used in the STL generate function + to easily generate random ints + either between [0, _max) if only one value (_max) is given to the ctor + or in [_min,_max) if 2 values are given (_min, _max) +*/ +template class random_generator +{ + public : + // added new ctor with 2 params, and modified the data to minim and range + // (was maxim only). MS 3/11/2000 + random_generator(T _max, eoRng& _rng = rng) : + minim(T(0.0)), range(_max), random(_rng) {} + random_generator(T _min, T _max, eoRng& _rng = rng) : + minim(_min), range(_max-_min), random(_rng) + { + if (_min>_max) + throw std::logic_error("Min is greater than Max in random_generator"); + } + + T operator()(void) { return (T) (minim + random.random(range)); } + +private : + T minim; + T range; + eoRng& random; +}; + +/// Specialization for bool +template <> +inline bool random_generator::operator()(void) +{ + return random.flip(0.5); +} + +/** + Another class random_generator that can be used in the STL random_shuffle + function (see eoPop::shuffle): its operator() takes an unsigned argument m + and must return an unsigned uniformly distributed in [0,m} +*/ +template class UF_random_generator +{ + public : + UF_random_generator(eoRng& _rng = rng) : + random(_rng) {} + + T operator()(T _t) { return (T) (random.random(_t)); } + +private : + eoRng& random; +}; + + +/** + The class normal_generator can be used in the STL generate function + to easily generate gaussian distributed floats and doubles. The user + can supply a standard deviation which defaults to 1. +*/ +template class normal_generator +{ + public : + normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} + + T operator()(void) { return (T) normal.normal(stdev); } + + private : + T stdev; + eoRng& normal; +}; + +/** + The class negexp_generator can be used in the STL generate function + to easily generate negative exponential distributed floats and doubles. The user + can supply a mean. +*/ +template class negexp_generator +{ + public : + negexp_generator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {} + + T operator()(void) { return (T) negexp.negexp(mean); } + + private : + T mean; + eoRng& negexp; +}; + +/** @} */ +#endif diff --git a/deprecated/eo/src/utils/selectors.h b/deprecated/eo/src/utils/selectors.h new file mode 100644 index 000000000..37df7997b --- /dev/null +++ b/deprecated/eo/src/utils/selectors.h @@ -0,0 +1,340 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + selectors.h + A bunch of useful selector functions. They generally have three forms: + + template + It select(It begin, It end, params, eoRng& gen = rng); + + template + const EOT& select(const eoPop& pop, params, eoRng& gen = rng); + + template + EOT& select(eoPop& pop, params, eoRng& gen = rng); + + where select is one of: roulette_wheel, deterministic_tournament + and stochastic_tournament (at the moment). + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef SELECT__H +#define SELECT__H + +#include + +#include "eoRNG.h" +#include +/** +@addtogroup Selectors +@{ +*/ + +template +bool minimizing_fitness() +{ + EOT eo1; // Assuming people don't do anything fancy in the default constructor! + EOT eo2; + + /* Dear user, when the two line below do not compile you are most + likely not working with scalar fitness values. In that case we're sorry + but you cannot use lottery or roulette_wheel selection... + */ + +#ifdef _MSC_VER + eo1.fitness( EOT::Fitness(0.0) ); + eo2.fitness( EOT::Fitness(1.0) ); +#else + eo1.fitness( typename EOT::Fitness(0.0) ); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this + eo2.fitness( typename EOT::Fitness(1.0) ); +#endif + + return eo2 < eo1; // check whether we have a minimizing fitness +} + +inline double scale_fitness(const std::pair& _minmax, double _value) +{ + if (_minmax.first == _minmax.second) + { + return 0.0; // no differences in fitness, population converged! + } + // else + + return (_value - _minmax.first) / (_minmax.second - _minmax.first); +} + +template +double sum_fitness(It begin, It end) +{ + double sum = 0.0; + + for (; begin != end; ++begin) + { + double v = static_cast(begin->fitness()); + if (v < 0.0) + throw std::logic_error("sum_fitness: negative fitness value encountered"); + sum += v; + } + + return sum; +} + +template +double sum_fitness(const eoPop& _pop) +{ + return sum_fitness(_pop.begin(), _pop.end()); +} + +template +double sum_fitness(const eoPop& _pop, std::pair& _minmax) +{ + double rawTotal, scaledTotal; + + typename eoPop::const_iterator it = _pop.begin(); + + _minmax.first = it->fitness(); + _minmax.second = it++->fitness(); + + for(; it != _pop.end(); ++it) + { + double v = static_cast(it->fitness()); + + _minmax.first = std::min(_minmax.first, v); + _minmax.second = std::max(_minmax.second, v); + + rawTotal += v; + } + + if (minimizing_fitness()) + { + std::swap(_minmax.first, _minmax.second); + } + + scaledTotal = 0.0; + + // unfortunately a second loop is neccessary to scale the fitness + for (it = _pop.begin(); it != _pop.end(); ++it) + { + double v = scale_fitness(_minmax, static_cast(it->fitness())); + + scaledTotal += v; + } + + return scaledTotal; +} + +template +It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) +{ + + double roulette = _gen.uniform(total); + + if (roulette == 0.0) // covers the case where total==0.0 + return _begin + _gen.random(_end - _begin); // uniform choice + + It i = _begin; + + while (roulette > 0.0) + { + roulette -= static_cast(*(i++)); + } + + return --i; +} + +template +const EOT& roulette_wheel(const eoPop& _pop, double total, eoRng& _gen = rng) +{ + double roulette = _gen.uniform(total); + + if (roulette == 0.0) // covers the case where total==0.0 + return _pop[_gen.random(_pop.size())]; // uniform choice + + typename eoPop::const_iterator i = _pop.begin(); + + while (roulette > 0.0) + { + roulette -= static_cast((i++)->fitness()); + } + + return *--i; +} + +template +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 + return _pop[_gen.random(_pop.size())]; // uniform choice + + typename eoPop::iterator i = _pop.begin(); + + while (roulette > 0.0) + { + roulette -= static_cast((i++)->fitness()); + } + + return *--i; +} + +template +It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) +{ + It best = _begin + _gen.random(_end - _begin); + + for (unsigned i = 0; i < _t_size - 1; ++i) + { + It competitor = _begin + _gen.random(_end - _begin); + + if (*best < *competitor) + { + best = competitor; + } + } + + return best; +} + +template +const EOT& deterministic_tournament(const eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +EOT& deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) +{ + It worst = _begin + _gen.random(_end - _begin); + + for (unsigned i = 1; i < _t_size; ++i) + { + It competitor = _begin + _gen.random(_end - _begin); + + if (competitor == worst) + { + --i; + continue; // try again + } + + if (*competitor < *worst) + { + worst = competitor; + } + } + + return worst; +} + +template +const EOT& inverse_deterministic_tournament(const eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +EOT& inverse_deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) +{ + It i1 = _begin + _gen.random(_end - _begin); + It i2 = _begin + _gen.random(_end - _begin); + + bool return_better = _gen.flip(_t_rate); + + if (*i1 < *i2) + { + if (return_better) return i2; + // else + + return i1; + } + else + { + if (return_better) return i1; + // else + } + // else + + return i2; +} + +template +const EOT& stochastic_tournament(const eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +template +EOT& stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +template +It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) +{ + It i1 = _begin + _gen.random(_end - _begin); + It i2 = _begin + _gen.random(_end - _begin); + + bool return_worse = _gen.flip(_t_rate); + + if (*i1 < *i2) + { + if (return_worse) return i1; + // else + + return i2; + } + else + { + if (return_worse) return i2; + // else + } + // else + + return i1; +} + +template +const EOT& inverse_stochastic_tournament(const eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +template +EOT& inverse_stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +/** @} */ + +#endif diff --git a/deprecated/eo/test/CMakeLists.txt b/deprecated/eo/test/CMakeLists.txt new file mode 100644 index 000000000..ed9575e85 --- /dev/null +++ b/deprecated/eo/test/CMakeLists.txt @@ -0,0 +1,116 @@ +############################################################################### +## +## CMakeLists file for eo/test +## +############################################################################### + + +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/contrib) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/contrib/MGE) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) + +###################################################################################### +### 3) Define your targets and link the librairies +###################################################################################### + +SET (TEST_LIST + t-eofitness + t-eoRandom + t-eobin + t-eoVirus + t-MGE + t-MGE1bit + t-MGE-control + t-eoStateAndParser + t-eoCheckpointing + t-eoSSGA + t-eoExternalEO + t-eoSymreg + t-eo + t-eoReplacement + t-eoSelect + t-eoGenOp + t-eoGA + t-eoReal + t-eoVector + t-eoESAll + t-eoPBIL + t-eoFitnessAssembled + t-eoFitnessAssembledEA + t-eoRoulette + t-eoSharing + t-eoCMAES + t-eoSecondsElapsedContinue + t-eoRNG + t-eoEasyPSO + t-eoInt + t-eoInitPermutation + t-eoSwapMutation + t-eoShiftMutation + t-eoTwoOptMutation + t-eoRingTopology + t-eoSyncEasyPSO + t-eoOrderXover + t-eoExtendedVelocity + t-eoLogger + #t-eoIQRStat # Temporary by-passed in order to test coverage + t-eoParallel + #t-openmp # does not work anymore since functions used in this test were removed from EO + #t-eoDualFitness + t-eoParser + ) + + +FOREACH (test ${TEST_LIST}) + SET ("T_${test}_SOURCES" "${test}.cpp") +ENDFOREACH (test) + + +IF(ENABLE_MINIMAL_CMAKE_TESTING) + + SET (MIN_TEST_LIST t-eoEasyPSO) + FOREACH (mintest ${MIN_TEST_LIST}) + SET ("T_${mintest}_SOURCES" "${mintest}.cpp") + ADD_EXECUTABLE(${mintest} ${T_${mintest}_SOURCES}) + ADD_TEST(${mintest} ${mintest}) + TARGET_LINK_LIBRARIES(${mintest} ga es cma eoutils eo) + ENDFOREACH (mintest) + +ELSEIF(ENABLE_CMAKE_TESTING) + + FOREACH (test ${TEST_LIST}) + ADD_EXECUTABLE(${test} ${T_${test}_SOURCES}) + ADD_TEST(${test} ${test}) + TARGET_LINK_LIBRARIES(${test} ga es cma eoutils eo) + INSTALL(TARGETS ${test} RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/test COMPONENT test) + ENDFOREACH (test) + + SET(RESOURCES + boxplot.py + boxplot_to_png.py + boxplot_to_pdf.py + t-openmp.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/deprecated/eo/test/ChangeLog b/deprecated/eo/test/ChangeLog new file mode 100644 index 000000000..747025387 --- /dev/null +++ b/deprecated/eo/test/ChangeLog @@ -0,0 +1,36 @@ +2006-12-04 Jochen Kpper + + * Makefile.am: Add t-eoRNG + + * t-eoRNG.cpp: Start test for random number generator. + +2006-12-02 Jochen Kpper + + * t-MGE1bit.cpp: Change float to double. + + * 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. + + +2006-07-02 Thomas Legrand + + * test/t-eoEasyPSO.cpp: added PSO test + + * test/Makefile.am: added PSO test + + +2006-02-27 Thomas Legrand + + * 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: diff --git a/deprecated/eo/test/RoyalRoad.h b/deprecated/eo/test/RoyalRoad.h new file mode 100644 index 000000000..5592f3cd5 --- /dev/null +++ b/deprecated/eo/test/RoyalRoad.h @@ -0,0 +1,60 @@ +/* + RoyalRoad.h + -- Implementation of the Royal Road function for any length and block size + (c) GeNeura Team 2001, 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 + 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 +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 $ +*/ + +#ifndef RoyalRoad_h +#define RoyalRoad_h + +template +class RoyalRoad: public eoEvalFunc { + + public: + + typedef typename EOT::Fitness FitT; + + /// Ctor: takes a length, and divides that length in equal parts + RoyalRoad( unsigned _div ): eoEvalFunc(), div( _div ) {}; + + // Applies the function + virtual void operator() ( EOT & _eo ) { + FitT fitness = 0; + if (_eo.invalid()) { + for ( unsigned i = 0; i < _eo.size()/div; i ++ ) { + bool block = true; + for ( unsigned j = 0; j < div; j ++ ) { + block &= _eo[i*div+j]; + } + if (block) { + fitness += div; + } + } + _eo.fitness( fitness ); + } + }; + + private: + unsigned div; + +}; + +#endif diff --git a/deprecated/eo/test/binary_value.h b/deprecated/eo/test/binary_value.h new file mode 100644 index 000000000..59dc4cc3c --- /dev/null +++ b/deprecated/eo/test/binary_value.h @@ -0,0 +1,16 @@ +#include + +//----------------------------------------------------------------------------- + +/** Just the simple function that takes binary value of a chromosome and sets + the fitnes. + @param _chrom A binary chromosome +*/ + +template double binary_value(const Chrom& _chrom) +{ + double sum = 0.0; + for (unsigned i=0; i<_chrom.size(); i++) + sum += _chrom[i]; + return sum; +} diff --git a/deprecated/eo/test/boxplot.py b/deprecated/eo/test/boxplot.py new file mode 100755 index 000000000..20273c18f --- /dev/null +++ b/deprecated/eo/test/boxplot.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python + +import pylab +import sys + +if __name__ == '__main__': + if len(sys.argv) < 2: + 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.xlabel('iterations') + pylab.show() diff --git a/deprecated/eo/test/boxplot_to_pdf.py b/deprecated/eo/test/boxplot_to_pdf.py new file mode 100755 index 000000000..f29edeb21 --- /dev/null +++ b/deprecated/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/deprecated/eo/test/boxplot_to_png.py b/deprecated/eo/test/boxplot_to_png.py new file mode 100755 index 000000000..17fb35bc9 --- /dev/null +++ b/deprecated/eo/test/boxplot_to_png.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_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.xlabel('iterations') + pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='png', transparent=True, papertype='a0' ) diff --git a/deprecated/eo/test/fitness_traits.cpp b/deprecated/eo/test/fitness_traits.cpp new file mode 100644 index 000000000..4af0e34bb --- /dev/null +++ b/deprecated/eo/test/fitness_traits.cpp @@ -0,0 +1,431 @@ +#include // for pair +#include +#include +#include +#include +#include // for exp + +using namespace std; + +/* fitness_traits.h */ + +// default traits: defaults to a double that needs to be maximized +template +struct fitness_traits +{ + // Needs mapping can be used to figure out whether you need to do fitness scaling (or not) + const static bool needs_mapping = false; + + // storage_type: what to store next to the genotype + typedef T storage_type; + + // performance_type: what the eoEvalFunc calculates + typedef T performance_type; + + // worth_type: what the scaling function does + typedef T worth_type; + + // access_performance: how to get from what is stored to a mutable performance + static performance_type& access_performance(storage_type& a) { return a; } + + // access_worth: how to get from what is stored to a mutable worth + static worth_type& access_worth(storage_type& a) { return a; } + + // get_performance: from storage_type to a performance figure + static performance_type get_performance(storage_type a) { return a; } + + // get_worth: from storage_type to a worth figure + static worth_type get_worth(storage_type a) { return a; } + + // get the fitness out of the individual + template + static worth_type get_fitness(const EOT& _eo) { return _eo.performance(); } + + // compare the two individuals + template + static bool is_better(const EOT& _eo1, const EOT& _eo2) + { + return _eo1.performance() > _eo2.performance(); + } +}; + +struct minimization {}; +struct maximization {}; + +struct fitness_traits : public fitness_traits +{ + // for minimization, invert the is_better + template + static bool is_better(const EOT& _eo1, const EOT& _eo2) + { + return _eo1.performance() < _eo2.performance(); + } +}; + +// for maximization, just take the default behaviour +struct fitness_traits : public fitness_traits {}; + +// forward declaration +//template class eoPop; +//template class EO; + +// unfortunately, partial template specialization is not approved by Microsoft (though ANSI says it's ok) +// Probably need some macro-magic to make this work (MicroSoft == MacroHard) +// A pair class: first == performance, second == worth, redefine all types, data and functions +template +struct fitness_traits< pair > +{ + typedef pair storage_type; + typedef Performance performance_type; + typedef Worth worth_type; + + const static bool needs_mapping = true; + + static performance_type& access_performance(storage_type& a) { return a.first; } + static worth_type& access_worth(storage_type& a) { return a.second; } + + static performance_type get_performance(const storage_type& a) { return a.first; } + static worth_type get_worth(const storage_type& a) { return a.second; } + + // This function calls _eo.worth() which in turn checks the fitness flag and calls get_worth above + // The compiler should be able to inline all these calls and come up with a very compact solution + template + static worth_type get_fitness(const EOT& _eo) { return _eo.worth(); } + + template + static bool is_better(const EOT& _eo1, const EOT& _eo2) + { + return _eo1.worth() > _eo2.worth(); + } +}; + +/* end fitness_traits.h */ + +/* EO.h + +The Fitness template argument is there for backward compatibility reasons + +*/ + +template > +class EO +{ +public : + + typedef Traits fitness_traits; + typedef typename Traits::storage_type storage_type; + typedef typename Traits::performance_type performance_type; + typedef typename Traits::worth_type worth_type; + + EO() : valid_performance(false), valid_worth(false), rep_fitness() {} + + // for backwards compatibility + void fitness(performance_type perf) + { + performance(perf); + } + + void performance(performance_type perf) + { + valid_performance = true; + Traits::access_performance(rep_fitness) = perf; + } + + performance_type performance(void) const + { + if(!valid_performance) throw runtime_error("no performance"); + return Traits::get_performance(rep_fitness); + } + + void worth(worth_type worth) + { + valid_worth = true; + Traits::access_worth(rep_fitness) = worth; + } + + worth_type worth(void) const + { + if(!valid_worth) throw runtime_error("no worth"); + if(!Traits::needs_mapping) throw runtime_error("no mapping"); + return Traits::get_worth(rep_fitness); + } + + worth_type fitness(void) const + { + return Traits::get_fitness(*this); + } + + void invalidate(void) + { + valid_performance = false; + valid_worth = false; + } + + void invalidate_worth(void) + { + valid_worth = false; + } + + bool operator<(const EO& other) const + { + return !Traits::is_better(other, *this); + } + + bool operator>(const EO& other) const + { + return Traits::is_better(other, *this); + } + + private : + + bool valid_performance; + bool valid_worth; + storage_type rep_fitness; +}; + +/* end EO.h */ + +/* eoPerf2Worth.h */ + +// get the name known +template class eoPop; + +template +void exponential_scaling(eoPop& _pop) +{ + for (unsigned i = 0; i < _pop.size(); ++i) + { // change minimimization into maximization + _pop[i].worth(exp(-_pop[i].performance())); + } +} + +template +class eoPerf2Worth /* : public eoUF&, void> */ +{ +public : + virtual void operator()(eoPop& _pop) + { + return exponential_scaling(_pop); + } +}; + +/* end eoPerf2Worth.h */ + + +/* eoPop.h */ + +template +class eoPop : public vector +{ +public : + + typedef typename EOT::fitness_traits fitness_traits; + + eoPop(void) : p2w(0) {} + + void sort() + { + scale(); // get the worths up to date + + std::sort(begin(), end(), greater()); + } + + void scale() + { + if (p2w) + { + if (!fitness_traits::needs_mapping) + { + throw runtime_error("eoPop: no scaling needed, yet a scaling function is defined"); + } + + (*p2w)(*this); + } + else if (fitness_traits::needs_mapping) + { + throw runtime_error("eoPop: no scaling function attached to the population, while one was certainly called for"); + } + } + + void setPerf2Worth(eoPerf2Worth& _p2w) + { + p2w = &_p2w; + } + + void setPerf2Worth(eoPerf2Worth* _p2w) + { + p2w = _p2w; + } + + eoPerf2Worth* getPerf2Worth() { return p2w; } + + void swap(eoPop& other) + { + vector::swap(other); + eoPerf2Worth* tmp = p2w; + p2w = other.p2w; + other.p2w = tmp; + } + +private : + + // a pointer as it can be emtpy + eoPerf2Worth* p2w; +}; + +// need this one to be able to swap the members as well... +template +void swap(eoPop& _p1, eoPop& _p2) +{ + _p1.swap(_p2); +} + +/* end eoPop.h */ + +/* main and test */ + +template +void algo(eoPop& _pop) +{ + eoPop offspring; // how to get the scaling info into this guy?? + offspring.setPerf2Worth(_pop.getPerf2Worth()); // like this! + + std::copy(_pop.begin(), _pop.end(), back_inserter(offspring)); + + offspring.sort(); // should call scale + + swap(_pop, offspring); +} + +void minimization_test() +{ + typedef EO eo_type; + + eo_type eo1; + eo_type eo2; + + eo1.performance(1.0); + eo2.performance(2.0); + + std::cout << "With minimizing fitness" << std::endl; + std::cout << eo1.fitness() << " < " << eo2.fitness() << " returns " << (eo1 < eo2) << std::endl; + std::cout << eo2.fitness() << " < " << eo1.fitness() << " returns " << (eo2 < eo1) << std::endl; +} + +void the_main() +{ + typedef EO simple_eo; + typedef EO > scaled_eo; + + simple_eo eo1; + simple_eo eo3; + +/* First test some simple comparisons */ + + eo1.fitness(10); // could also use performance() + eo3.fitness(5); + + std::cout << eo1.fitness() << std::endl; + std::cout << eo3.fitness() << std::endl; + + std::cout << "eo1 < eo3 = " << (eo1 < eo3) << std::endl; + + + scaled_eo eo2; + scaled_eo eo4; + eo2.performance(10); + eo4.performance(8); + +/* Now test if the worth gets accessed and if the flag protects it */ + + try + { + std::cout << eo2.fitness() << std::endl; + std::cout << "did not throw" << std::endl; + assert(false); // should throw + } + catch(std::exception& e) + { + std::cout << "Fitness threw exception, as it should" << std::endl; + std::cout << e.what() << std::endl; + } + +/* Set the worth and all is well (this is normally done by some perf2worth functor */ + + eo2.worth(3); + eo4.worth(5); + + std::cout << "with maximization " << std::endl; + std::cout << eo2.fitness() << std::endl; + std::cout << eo4.fitness() << std::endl; + std::cout << eo2.fitness() << " < " << eo4.fitness() << " returns " << (eo2 < eo4) << std::endl; + +/* Test the minimization of fitness */ + minimization_test(); + + +/* Populations */ + +// test pop without scaling, should have no overhead save for a single empty pointer in pop + eoPop pop0; + pop0.resize(1); + pop0[0].fitness(1); + + algo(pop0); + + std::cout << pop0[0].fitness() << std::endl; + + assert(pop0[0].fitness() == 1); + +/* test pop with scaling */ + + eoPerf2Worth perf2worth; + eoPop pop1; + + pop1.resize(1); + + pop1[0].fitness(1.0); // emulate evaluation + + // at this point getting the fitness should throw + try + { + std::cout << pop1[0].fitness() << std::endl; + std::cout << "did not throw" << std::endl; + assert(false); // should throw + } + catch(std::exception& e) + { + std::cout << "Fitness threw exception, as it should" << std::endl; + std::cout << e.what() << std::endl; + } + + // at this point trying to scale should throw + try + { + algo(pop1); // should complain that it cannot scale + assert(false); // so it would never get here + } + catch(std::exception& e) + { // but rather ends here + std::cout << e.what() << std::endl; + } + + // ok, now set the scaling + pop1.setPerf2Worth(perf2worth); + + algo(pop1); + + std::cout << "the fitness has been transformed from " << pop1[0].performance() << " to exp(-1) = " << pop1[0].fitness() << std::endl; +} + +int main() +{ + try + { + the_main(); + } + catch(std::exception& e) + { + std::cout << e.what() << std::endl; + } +} diff --git a/deprecated/eo/test/real_value.h b/deprecated/eo/test/real_value.h new file mode 100644 index 000000000..8b58d3175 --- /dev/null +++ b/deprecated/eo/test/real_value.h @@ -0,0 +1,16 @@ +#include +//----------------------------------------------------------------------------- + + +/** Just a simple function that takes an eoEsBase and sets the fitnes + to sphere + @param _ind vector +*/ + +double real_value(const std::vector& _ind) +{ + double sum = 0; + for (unsigned i = 0; i < _ind.size(); i++) + sum += _ind[i] * _ind[i]; + return sum/_ind.size(); +} diff --git a/deprecated/eo/test/run_tests b/deprecated/eo/test/run_tests new file mode 100755 index 000000000..22b9644ac --- /dev/null +++ b/deprecated/eo/test/run_tests @@ -0,0 +1,9 @@ +#!/bin/sh + +echo "Testing -h" +./t-eoCheckpointing -h + +echo "Finished" + +#TODO test if an error occured +echo "Ok" diff --git a/deprecated/eo/test/t-MGE-control.cpp b/deprecated/eo/test/t-MGE-control.cpp new file mode 100644 index 000000000..240dd3688 --- /dev/null +++ b/deprecated/eo/test/t-MGE-control.cpp @@ -0,0 +1,104 @@ +//----------------------------------------------------------------------------- +// t-eoMGE.cpp +//----------------------------------------------------------------------------- + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include "eo" +#include "ga/eoBitOp.h" + +#include "RoyalRoad.h" + +// Viri +#include "VirusOp.h" +#include "eoVirus.h" +#include "eoInitVirus.h" + +//----------------------------------------------------------------------------- + +typedef eoVirus Chrom; + +//----------------------------------------------------------------------------- + +int main() +{ + const unsigned POP_SIZE = 10, CHROM_SIZE = 12; + unsigned i; + eoBooleanGenerator gen; + + // the populations: + eoPop pop; + + // Evaluation + RoyalRoad rr( 8 ); + eoEvalFuncCounter eval( rr ); + + eoInitVirus random(CHROM_SIZE, gen); + for (i = 0; i < POP_SIZE; ++i) { + Chrom chrom; + random(chrom); + 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 + eoStochTournamentSelect lottery(0.9 ); + + // breeder + eoOneBitFlip vm; + eoUBitXover xover; + eoProportionalOp propSel; + eoGeneralBreeder breeder( lottery, propSel ); + propSel.add(vm, 0.2); + propSel.add(xover, 0.8); + + // Replace a single one + eoCommaReplacement replace; + + // Terminators + eoGenContinue continuator1(10); + eoFitContinue continuator2(CHROM_SIZE); + eoCombinedContinue continuator(continuator1, continuator2); + eoCheckPoint checkpoint(continuator); + eoStdoutMonitor monitor; + checkpoint.add(monitor); + eoSecondMomentStats stats; + eoPopStat dumper( 10 ); + monitor.add(stats); + checkpoint.add(dumper); + checkpoint.add(stats); + + // GA generation + eoEasyEA ea(checkpoint, eval, breeder, replace ); + + // evolution + try + { + ea(pop); + } + catch (std::exception& e) + { + 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; + + std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl; + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-MGE.cpp b/deprecated/eo/test/t-MGE.cpp new file mode 100644 index 000000000..a122b5e70 --- /dev/null +++ b/deprecated/eo/test/t-MGE.cpp @@ -0,0 +1,108 @@ +//----------------------------------------------------------------------------- +// t-eoMGE.cpp +//----------------------------------------------------------------------------- + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include +#include + +#include "RoyalRoad.h" + +// Viri +#include "VirusOp.h" +#include "eoVirus.h" +#include "eoInitVirus.h" + +//----------------------------------------------------------------------------- + +typedef eoVirus Chrom; + +//----------------------------------------------------------------------------- + +int main() +{ + const unsigned POP_SIZE = 10, CHROM_SIZE = 12; + unsigned i; + eoBooleanGenerator gen; + + // the populations: + eoPop pop; + + // Evaluation + RoyalRoad rr( 8 ); + eoEvalFuncCounter eval( rr ); + + eoInitVirus random(CHROM_SIZE, gen); + for (i = 0; i < POP_SIZE; ++i) { + Chrom chrom; + random(chrom); + 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 + eoStochTournamentSelect lottery(0.9 ); + + // breeder + VirusMutation vm; + VirusTransmission vt; + VirusBitFlip vf; + eoUBitXover xover; + eoProportionalOp propSel; + eoGeneralBreeder breeder( lottery, propSel ); + propSel.add(vm, 0.1); + propSel.add(vf, 0.05); + propSel.add(vt, 0.05); + propSel.add(xover, 0.8); + + // Replace a single one + eoCommaReplacement replace; + + // Terminators + eoGenContinue continuator1(10); + eoFitContinue continuator2(CHROM_SIZE); + eoCombinedContinue continuator(continuator1, continuator2); + eoCheckPoint checkpoint(continuator); + eoStdoutMonitor monitor; + checkpoint.add(monitor); + eoSecondMomentStats stats; + eoPopStat dumper( 10 ); + monitor.add(stats); + checkpoint.add(dumper); + checkpoint.add(stats); + + // GA generation + eoEasyEA ea(checkpoint, eval, breeder, replace ); + + // evolution + try + { + ea(pop); + } + catch (std::exception& e) + { + 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; + + std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl; + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-MGE1bit.cpp b/deprecated/eo/test/t-MGE1bit.cpp new file mode 100644 index 000000000..842f5cd77 --- /dev/null +++ b/deprecated/eo/test/t-MGE1bit.cpp @@ -0,0 +1,111 @@ +//----------------------------------------------------------------------------- +// t-eoMGE.cpp +//----------------------------------------------------------------------------- + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include "eo" +#include "ga/eoBitOp.h" +#include "RoyalRoad.h" + +// Viri +#include "VirusOp.h" +#include "eoVirus.h" +#include "eoInitVirus.h" + +//----------------------------------------------------------------------------- + +typedef eoVirus Chrom; + +//----------------------------------------------------------------------------- + +int main() +{ + const unsigned POP_SIZE = 10, CHROM_SIZE = 12; + unsigned i; + eoBooleanGenerator gen; + + // the populations: + eoPop pop; + + // Evaluation + RoyalRoad rr( 8 ); + eoEvalFuncCounter eval( rr ); + + eoInitVirus1bit random(CHROM_SIZE, gen); + for (i = 0; i < POP_SIZE; ++i) { + Chrom chrom; + random(chrom); + 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 + eoStochTournamentSelect lottery(0.9 ); + + // breeder + VirusShiftMutation vm; + VirusTransmission vt; + VirusBitFlip vf; + eoUBitXover xover; + eoProportionalOp propSel; + eoGeneralBreeder breeder( lottery, propSel ); + propSel.add(vm, 0.8); + propSel.add(vf, 0.05); + propSel.add(vt, 0.05); + propSel.add(xover, 0.1); + + // Replace a single one + eoCommaReplacement replace; + + // Terminators + eoGenContinue continuator1(10); + eoFitContinue continuator2(CHROM_SIZE); + eoCombinedContinue continuator(continuator1, continuator2); + eoCheckPoint checkpoint(continuator); + eoStdoutMonitor monitor; + checkpoint.add(monitor); + eoSecondMomentStats stats; + eoPopStat dumper( 10 ); + monitor.add(stats); + checkpoint.add(dumper); + checkpoint.add(stats); + + // GA generation + eoEasyEA ea(checkpoint, eval, breeder, replace); + + // evolution + try { + ea(pop); + } catch (std::exception& e) { + std::cerr << "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; + + std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl; + return EXIT_SUCCESS; +} + +//----------------------------------------------------------------------------- + + + +// Local Variables: +// mode: C++ +// c-file-style: "Stroustrup" +// End: diff --git a/deprecated/eo/test/t-eo.cpp b/deprecated/eo/test/t-eo.cpp new file mode 100644 index 000000000..f2c0e177b --- /dev/null +++ b/deprecated/eo/test/t-eo.cpp @@ -0,0 +1,14 @@ +#include + +typedef EO Chrom; + +int main() +{ + Chrom chrom1, chrom2; + + // EO objects can be printed with stream operators + std::cout << "chrom1 = " << chrom1 << std::endl + << "chrom2 = " << chrom2 << std::endl; + + return 0; +} diff --git a/deprecated/eo/test/t-eo2dVector.cc b/deprecated/eo/test/t-eo2dVector.cc new file mode 100644 index 000000000..0288fdc50 --- /dev/null +++ b/deprecated/eo/test/t-eo2dVector.cc @@ -0,0 +1,220 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +/* +----------------------------------------------------------------------------- +File............: t-eo2dVector.cc +Author..........: Geneura Team (this file: Victor Rivas, vrivas@ujaen.es) +Date............: 01-Oct-1999, at Fac. of Sciences, Univ. of Granada (Spain) +Description.....: Test for 2 dimensional eoVector. + + ================ Modif. 1 ================ + Author........: + Date..........: + Description...: + +----------------------------------------------------------------------------- +*/ + +#include +#include // eo2dVector +#include // Random generator + +//----------------------------------------------------------------------------- + +typedef unsigned T; +typedef double fitnessT; +typedef eo2dVector C; + +//----------------------------------------------------------------------------- + +main() +{ + { + C c1; + cout << "Default constructor:" << endl + << c1 << endl; + } + { + 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 ); + cout << "Copy constructor: " << endl + << "Original chromosome: " << endl + << c1 << endl + << "Copy chromosome: " << endl + << c2 << endl; + } + + eoUniform aleat( 1,10 ); + C c1( 3,4,aleat ); + + cout << "-----------------------------------------------------" << endl + << "Since now on all the operations are applied to " << endl + << c1 + << "-----------------------------------------------------" << endl; + { + cout << "getGene(2,2): " + << c1.getGene(2,2) << endl; + } + { + c1.setGene( 2,2,300 ); + cout << "setGene(2,2,300): " << endl + << c1 << endl; + } + { + unsigned u1=0, u3=333, u5=555; + vector v1( 4,u1 ), v2( 4,u3 ), v3( 4,u5 ); + c1.insertRow( 0,v1 ); + c1.insertRow( 3,v2 ); + c1.insertRow( 5,v3 ); + cout << "Insert rows at positions 0, 3 and 5: " << endl + << c1 << endl; + } + { + c1.deleteRow( 5 ); + c1.deleteRow( 3 ); + c1.deleteRow( 0 ); + cout << "Delete rows at positions 5, 3 and 0: " << endl + << c1 << endl; + } + { + unsigned u1=0, u3=333, u6=666; + vector v1( 3,u1 ), v2( 3,u3 ), v3( 3,u6 ); + c1.insertCol( 0,v1 ); + c1.insertCol( 3,v2 ); + c1.insertCol( 6,v3 ); + cout << "Insert columns at positions 0, 3 and 6: " << endl + << c1 << endl; + } + { + c1.deleteCol( 6 ); + c1.deleteCol( 3 ); + c1.deleteCol( 0 ); + cout << "Delete columns at positions 6, 3 and 0: " << endl + << c1 << endl; + } + { + cout << "Number of Rows: " << endl + << c1.numOfRows() << endl; + } + { + cout << "Number of Columns: " << endl + << c1.numOfCols() << endl; + } + + { + cout << "Class Name: " << endl + << c1.className() << endl; + } + + + cout << "-----------------------------------------------------" << endl + << "Catching exceptions: " << endl + << c1 + << "-----------------------------------------------------" << endl; + { + cout << "* Trying getGene(10,1): " << endl; + try { + c1.getGene( 10,1 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + { + cout << "* Trying getGene(1,10): " << endl; + try { + c1.getGene( 1,10) ; + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + { + cout << "* Trying setGene( 10,1,999 ): " << endl; + try { + c1.setGene( 10,1,999 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + { + cout << "* Trying setGene( 1,10,999 ): " << endl; + try { + c1.setGene( 1,10,999 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + { + unsigned u1=111; + vector v1( 4, u1 ); + cout << "* Trying insertRow( 10, v1 ): " << endl; + try { + c1.insertRow( 10,v1 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + { + unsigned u1=111; + vector v1( 5, u1 ); + cout << "* Trying insertRow( 1, v1 ) with v1.size()=5: " << endl; + try { + c1.insertRow( 1,v1 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + + { + cout << "* Trying deleteRow( 10 ): " << endl; + try { + c1.deleteRow( 10 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + + { + unsigned u1=111; + vector v1( 3, u1 ); + cout << "* Trying insertCol( 10,v1 ): " << endl; + try { + c1.insertCol( 10,v1 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + + { + unsigned u1=111; + vector v1( 5, u1 ); + cout << "* Trying insertCol( 1,v1 ) with v1.size()=5: " << endl; + try { + c1.insertCol( 1,v1 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + + { + cout << "* Trying deleteCol( 10 ): " << endl; + try { + c1.deleteCol( 10 ); + } catch (exception& e ) { + cerr << e.what() << endl; + } + } + +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoCMAES.cpp b/deprecated/eo/test/t-eoCMAES.cpp new file mode 100644 index 000000000..07b59509a --- /dev/null +++ b/deprecated/eo/test/t-eoCMAES.cpp @@ -0,0 +1,124 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +using namespace eo; +using namespace std; + +typedef eoMinimizingFitness FitT; +typedef eoVector EoType; + +double sqr(double x) { return x*x; } + +eoValueParam evals(0,"Function Evals","Number of Evaluations"); + +double f_sphere(const vector& values) { + double sum = 0.0; + for (unsigned i = 0; i < values.size(); ++i) { + sum += values[i] * values[i]; + } + ++evals.value(); + return sum; +} + +double f_rosen(const vector& x) { + double sum =0.0; + + for (unsigned i = 0; i < x.size()-1; ++i) { + sum += 100 * sqr(sqr(x[i])-x[i+1]) + sqr(1.-x[i]); + } + ++evals.value(); + return sum; +} + + + +int main(int argc, char* argv[]) { + + // make sure we have a dimensionality parameter (for testing) + char** rargv = new char*[argc+1]; + rargv[0] = argv[0]; + rargv[1] = (char*)"-N10"; + for (int i = 2; i < argc; ++i) { + rargv[i] = argv[i-1]; + } + + eoParser parser(argc+1, rargv); + + CMAParams params(parser); + + vector initial_point(params.n, 0.0); + + CMAState state(params, initial_point); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + return 1; + } + + eoCMAInit init(state); + + eoPop pop(params.mu, init); + + eoEvalFuncPtr&> eval( f_rosen ); + + eoCMABreed breed(state, params.lambda); + + for (unsigned i = 0; i < pop.size(); ++i) { + eval(pop[i]); + } + + eoCommaReplacement comma; + + eoGenContinue gen(params.maxgen); + eoFitContinue fit(1e-10); + + eoCheckPoint checkpoint(gen); + checkpoint.add(fit); + + eoBestFitnessStat stat; + + eoStdoutMonitor mon; + mon.add(stat); + mon.add(evals); + + eoTimedMonitor timed(1);// 1 seconds + timed.add(mon); // wrap it + + checkpoint.add(timed); + checkpoint.add(stat); + + eoEasyEA algo( + checkpoint, + eval, + breed, + comma); + + + algo(pop); + pop.sort(); + + cout << pop[0] << endl; + cout << "Fitness achieved = " << pop[0].fitness() << endl; + cout << "Function evaluations = " << evals.value() << endl; +} diff --git a/deprecated/eo/test/t-eoCheckpointing.cpp b/deprecated/eo/test/t-eoCheckpointing.cpp new file mode 100644 index 000000000..134b05cc4 --- /dev/null +++ b/deprecated/eo/test/t-eoCheckpointing.cpp @@ -0,0 +1,173 @@ +// to avoid long name warnings +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include // runtime_error + +// general +#include // Random number generators +#include +#include +#include +#include + +// include package checkpointing +#include + +struct Dummy : public EO +{ + typedef double Type; +}; + + +struct eoDummyPop : public eoPop +{ +public : + eoDummyPop(int s = 2) { resize(s); } +}; + + +int the_main(int argc, char **argv) +{ // ok, we have a command line parser and a state + + typedef eoBit Chrom; + + eoParser parser(argc, argv); + + // Define Parameters + eoValueParam rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); + eoValueParam factor(0.99, "mutationFactor", "Decrease factor for mutation rate"); + eoValueParam seed(time(0), "seed", "Random number seed"); + eoValueParam load_name("", "Load","Load",'L'); + eoValueParam save_name("", "Save","Save",'S'); + + // Register them + parser.processParam(rate, "Genetic Operators"); + parser.processParam(factor, "Genetic Operators"); + parser.processParam(load_name, "Persistence"); + parser.processParam(save_name, "Persistence"); + parser.processParam(seed, "Rng seeding"); + + eoState state; + state.registerObject(parser); + + if (load_name.value() != "") + { // load the parser. This is only neccessary when the user wants to + // be able to change the parameters in the state file by hand. + state.load(load_name.value()); // load the parser + } + + // Create the algorithm here + typedef Dummy EoType; + + eoDummyPop pop; + + eoGenContinue genTerm(5); // run for 5 generations + + eoCheckPoint checkpoint(genTerm); + // The algorithm will now quit after five generations + + // Create a counter parameter + eoValueParam generationCounter(0, "Generation"); + + // Create an incrementor (wich is an eoUpdater). Note that the + // Parameter's value is passed by reference, so every time the incrementer increments, + // the data in generationCounter will change. + eoIncrementor increment(generationCounter.value()); + + // Add it to the checkpoint, this will result in the counter being incremented every generation + checkpoint.add(increment); + + // The file monitor will print parameters to a comma seperated file + eoFileMonitor monitor("monitor.csv"); + + // the checkpoint mechanism can handle multiple monitors + checkpoint.add(monitor); + + // the monitor can monitor parameters such as the generationCounter + monitor.add(generationCounter); + + // Second moment stats: average and stdev + eoSecondMomentStats stats; + + // Add it to the checkpoint to get it called at the appropriate time + checkpoint.add(stats); + + // Add it to the monitor to get it written to the file + monitor.add(stats); + + // save state every third generation + eoCountedStateSaver stateSaver1(3, state, "generation"); + // save state every 2 seconds + eoTimedStateSaver stateSaver2(2, state, "time"); + + // And add the two savers to the checkpoint + checkpoint.add(stateSaver1); + checkpoint.add(stateSaver2); + + // Register the algorithm + state.registerObject(rng); + state.registerObject(pop); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + return 0; + } + + // Either load or initialize + if (load_name.value() != "") + { + state.load(load_name.value()); // load the rest + } + else + { + // else + + // initialize rng and population + + rng.reseed(seed.value()); + + pop.resize(2); + + pop[0].fitness(1); + pop[1].fitness(2); + } + + while(checkpoint(pop)) + { + pop[0].fitness(pop[0].fitness() + 1); + + time_t now = time(0); + + while (time(0) == now) {} // wait a second to test timed saver + + std::cout << "gen " << generationCounter.value() << std::endl; + } + + // run the algorithm + + // 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); + } + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << std::endl; + } + +} diff --git a/deprecated/eo/test/t-eoDualFitness.cpp b/deprecated/eo/test/t-eoDualFitness.cpp new file mode 100644 index 000000000..6b8fd6e17 --- /dev/null +++ b/deprecated/eo/test/t-eoDualFitness.cpp @@ -0,0 +1,88 @@ +#include + +#include +#include +#include + +typedef eoVector,double> DualVector; + +template +class DualSphere : public eoEvalFunc +{ +public: + virtual void operator()( EOT & x ) + { + if( x.invalid() ) { return; } + + double sum = 0; + int sign = 1; + for( unsigned int i=0, s=x.size(); i0 ? true : false ) ); + } +}; + + +double test( eoPop& pop, double target_value ) +{ + DualSphere eval; + + eoPopLoopEval pop_eval(eval); + + pop_eval(pop,pop); + + eoInterquartileRangeStat iqr_stat( std::make_pair(0.0,false), "IQR" ); + + iqr_stat( pop ); + + std::cout << iqr_stat.longName() << "=" << iqr_stat.value() << " should be " << target_value << std::endl; + + return iqr_stat.value().value(); +} + + +int main() +{ + eoPop pop; + + // fixed test + DualVector sol1(2,-1); + DualVector sol2(2,-1); + DualVector sol3(2,1); + DualVector sol4(2,1); + pop.push_back( sol1 ); + pop.push_back( sol2 ); + pop.push_back( sol3 ); + pop.push_back( sol4 ); + // on the sphere function everyone has the same fitness of 1 + if( test(pop, 0) != 0 ) { + exit(1); + } + + pop.erase(pop.begin(),pop.end()); + + // fixed test + sol1 = DualVector(2,0); + sol2 = DualVector(2,0); + sol3 = DualVector(2,1); + sol4 = DualVector(2,1); + pop.push_back( sol1 ); + pop.push_back( sol2 ); + pop.push_back( sol3 ); + pop.push_back( sol4 ); + if( test(pop, 1) != 1 ) { + exit(1); + } + + // test on a random normal distribution + eoNormalGenerator normal(1,rng); + eoInitFixedLength init_N(2, normal); + pop = eoPop( 1000000, init_N ); + double iqr = test(pop, 1.09); + if( iqr < 1.08 || iqr > 1.11 ) { + exit(1); + } +} diff --git a/deprecated/eo/test/t-eoESAll.cpp b/deprecated/eo/test/t-eoESAll.cpp new file mode 100644 index 000000000..3a77b6292 --- /dev/null +++ b/deprecated/eo/test/t-eoESAll.cpp @@ -0,0 +1,150 @@ +// Program to test several EO-ES features + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER + #include +#endif + +using namespace std; + +#include + +// representation specific +#include + +#include "real_value.h" // the sphere fitness + +// Now the main +/////////////// +typedef eoMinimizingFitness FitT; + +template +void runAlgorithm(EOT, eoParser& _parser, eoState& _state); + +int main_function(int argc, char *argv[]) +{ + // Create the command-line parser + 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"); + eoValueParam& stdevsParam = parser.getORcreateParam(false, "Stdev", + "One self-adaptive stDev per variable", + 's', "ES mutation"); + eoValueParam& corrParam = parser.getORcreateParam(false, "Correl", + "Use correlated mutations", + 'c', "ES mutation"); + // Run the appropriate algorithm + if (simpleParam.value() == false) + { + 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); + } + else if (corrParam.value() == false) + { + std::cout << "Using eoEsStdev" << std::endl; + runAlgorithm(eoEsStdev(), parser, state); + } + else + { + std::cout << "Using eoEsFull" << std::endl; + runAlgorithm(eoEsFull(), parser, state); + } + return 0; +} + + + +// A main that catches the exceptions +int main(int argc, char **argv) +{ +#ifdef _MSC_VER + // rng.reseed(42); + int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); + flag |= _CRTDBG_LEAK_CHECK_DF; + _CrtSetDbgFlag(flag); + // _CrtSetBreakAlloc(100); +#endif + try + { + main_function(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << '\n'; + } +} + + + +/** The templatized main (sort of) + +quite similar to the main of other genotypes (e.g. t-eoReal and t-eoGA +in test dir) +*/ +template +void runAlgorithm(EOT, eoParser& _parser, eoState& _state) +{ + typedef typename EOT::Fitness FitT; + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> mainEval( real_value ); + eoEvalFuncCounter eval(mainEval); + + // the genotype - through a genotype initializer + eoRealInitBounded& init = make_genotype(_parser, _state, EOT()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(_parser, _state, init); + + //// Now the representation-independent things + ////////////////////////////////////////////// + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(_parser, _state, init); + apply(eval, pop); + + // stopping criteria + eoContinue & term = make_continue(_parser, _state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(_parser, _state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(_parser, _state, eval, checkpoint, op); + + ///// End of construction of the algorith + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(_parser); + + //// GO + /////// + std::cout << "Initial Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + + run_ea(ga, pop); // run the ga + + std::cout << "Final Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; +} diff --git a/deprecated/eo/test/t-eoESFull.cpp b/deprecated/eo/test/t-eoESFull.cpp new file mode 100644 index 000000000..7c5e84d99 --- /dev/null +++ b/deprecated/eo/test/t-eoESFull.cpp @@ -0,0 +1,180 @@ +// Program to test several EO-ES features + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include +#include +#include +#include + +using namespace std; + +#include + +// representation specific +#include + +#include "real_value.h" // the sphere fitness + +// Now the main +/////////////// +typedef eoMinimizingFitness FitT; + +template +void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam _load_name); + +int main_function(int argc, char *argv[]) +{ + // Create the command-line parser + eoParser parser( argc, argv, "Basic EA for vector with adaptive mutations"); + + // Define Parameters and load them + eoValueParam& seed = parser.createParam(static_cast(time(0)), + "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'); + eoValueParam& corr = parser.createParam(false, "Correl", "Use correlated mutations", 'c'); + eoValueParam& chromSize = parser.createParam(unsigned(50), "ChromSize", "Number of chromosomes", 'n'); + eoValueParam& minimum = parser.createParam(-1.0, "Min", "Minimum for Objective Variables", 'l'); + eoValueParam& maximum = parser.createParam(1.0, "Max", "Maximum for Objective Variables", 'h'); + + eoState state; + state.registerObject(parser); + rng.reseed(seed.value()); + + if (!load_name.value().empty()) + { // load the parser. This is only neccessary when the user wants to + // be able to change the parameters in the state file by hand + // Note that only parameters inserted in the parser at this point + // will be loaded!. + state.load(load_name.value()); // load the parser + } + + state.registerObject(rng); + + eoRealVectorBounds bounds(chromSize.value(), minimum.value(), maximum.value()); + + // Run the appropriate algorithm + if (stdevs.value() == false && corr.value() == false) + { + runAlgorithm(eoEsSimple() ,parser, state, bounds, load_name); + } + else if (corr.value() == true) + { + runAlgorithm(eoEsFull(),parser, state, bounds, load_name); + } + else + { + 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); + } + + return 0; +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ +#ifdef _MSC_VER + // rng.reseed(42); + int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); + flag |= _CRTDBG_LEAK_CHECK_DF; + _CrtSetDbgFlag(flag); +// _CrtSetBreakAlloc(100); +#endif + + try + { + main_function(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} + +template +void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam _load_name) +{ + // evaluation + eoEvalFuncPtr&> eval( real_value ); + + // population parameters, unfortunately these can not be altered in the state file + eoValueParam mu = _parser.createParam(unsigned(7), "mu","Size of the population"); + eoValueParamlambda_rate = _parser.createParam(double(7.0), "lambda_rate", "Factor of children to produce"); + + if (lambda_rate.value() < 1.0f) + { + throw logic_error("lambda_rate must be larger than 1 in a comma strategy"); + } + + // Initialization + eoEsChromInit init(_bounds); + + // State takes ownership of pop because it needs to save it in caller + eoPop& pop = _state.takeOwnership(eoPop(mu.value(), init)); + + _state.registerObject(pop); + + if (!_load_name.value().empty()) + { // The real loading happens here when all objects are registered + _state.load(_load_name.value()); // load all and everything + } + else + { + // evaluate initial population + apply(eval, pop); + } + + // Ok, time to set up the algorithm + // Proxy for the mutation parameters + eoEsMutationInit mutateInit(_parser); + + eoEsMutate mutate(mutateInit, _bounds); + + // monitoring, statistics etc. + eoAverageStat average; + eoStdoutMonitor monitor; + + monitor.add(average); + + eoGenContinue cnt(100); + eoCheckPoint checkpoint(cnt); + checkpoint.add(monitor); + checkpoint.add(average); + + // only mutation (== with rate 1.0) + eoMonGenOp op(mutate); + + // the selection: sequential selection + eoSequentialSelect select; + // the general breeder (lambda is a rate -> true) + eoGeneralBreeder breed(select, op, lambda_rate.value(), true); + + // the replacement - hard-coded Comma replacement + eoCommaReplacement replace; + + // now the eoEasyEA + eoEasyEA es(checkpoint, eval, breed, replace); + + es(pop); + + pop.sort(); + std::cout << "Final population\n" << pop << std::endl; + +} diff --git a/deprecated/eo/test/t-eoEasyEA.cpp b/deprecated/eo/test/t-eoEasyEA.cpp new file mode 100644 index 000000000..ba3035d22 --- /dev/null +++ b/deprecated/eo/test/t-eoEasyEA.cpp @@ -0,0 +1,74 @@ +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include + +#include "binary_value.h" + +typedef eoBin Chrom; + +main() +{ + const unsigned POP_SIZE = 8, CHROM_SIZE = 16; + unsigned i; + +// a chromosome randomizer + eoBinRandom random; +// the populations: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( binary_value ); + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + 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; + + // breeder + eoBinBitFlip bitflip; + eoBinCrossover xover; + eoProportionalOpSel propSel; + eoBreeder breeder( propSel ); + propSel.addOp(bitflip, 0.25); + propSel.addOp(xover, 0.75); + + // replacement + eoInclusion inclusion; + + // Terminators + eoFitTerm term( pow(2.0, CHROM_SIZE), 1 ); + + // GA generation + eoEasyEA ea(lottery, breeder, inclusion, eval, term); + + // evolution + try + { + ea(pop); + } + catch (std::exception& e) + { + 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/deprecated/eo/test/t-eoEasyPSO.cpp b/deprecated/eo/test/t-eoEasyPSO.cpp new file mode 100644 index 000000000..af290e13f --- /dev/null +++ b/deprecated/eo/test/t-eoEasyPSO.cpp @@ -0,0 +1,102 @@ +//----------------------------------------------------------------------------- +// t-eoEasyPSO.cpp +//----------------------------------------------------------------------------- + +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include + +//----------------------------------------------------------------------------- +typedef eoMinimizingFitness FitT; +typedef eoRealParticle < FitT > Particle; +//----------------------------------------------------------------------------- + +// the objective function +double real_value (const Particle & _particle) +{ + double sum = 0; + for (unsigned i = 0; i < _particle.size ()-1; i++) + sum += pow(_particle[i],2); + return (sum); +} + + +int main() +{ + const unsigned int VEC_SIZE = 2; + const unsigned int POP_SIZE = 20; + const unsigned int NEIGHBORHOOD_SIZE= 5; + unsigned i; + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( real_value ); + + // position init + eoUniformGenerator < double >uGen (-3, 3); + eoInitFixedLength < Particle > random (VEC_SIZE, uGen); + + // velocity init + eoUniformGenerator < double >sGen (-2, 2); + eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); + + // local best init + eoFirstIsBestInit < Particle > localInit; + + // 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); + + // velocity + eoStandardVelocity velocity (topology,1,1.6,2,bnds); + + // flight + eoStandardFlight flight; + + // 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; + 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; + for (i = 0; i < pop.size(); ++i) + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + } + catch (std::exception& e) + { + std::cout << "exception: " << e.what() << std::endl;; + exit(EXIT_FAILURE); + } + + + + return 0; +} diff --git a/deprecated/eo/test/t-eoExtendedVelocity.cpp b/deprecated/eo/test/t-eoExtendedVelocity.cpp new file mode 100644 index 000000000..3fca3f30c --- /dev/null +++ b/deprecated/eo/test/t-eoExtendedVelocity.cpp @@ -0,0 +1,76 @@ +//----------------------------------------------------------------------------- +// t-eoExtendedVelocity.cpp +//----------------------------------------------------------------------------- + + +#include + +typedef eoRealParticle < double > Particle; + +//Evaluation function +double f (const Particle & _particle) +{ + double sum = 0; + for (unsigned i = 0; i < _particle.size (); i++) + sum += pow(_particle[i],2); + return (-sum); +} + +int main_function(int argc, char **argv) +{ + const unsigned POP_SIZE = 6, VEC_SIZE = 2, NEIGHBORHOOD_SIZE=2; + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( f ); + + // position + velocity + best init + eoUniformGenerator < double >uGen (-3, 3); + eoInitFixedLength < Particle > random (VEC_SIZE, uGen); + eoUniformGenerator < double >sGen (-2, 2); + eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); + eoFirstIsBestInit < Particle > localInit; + pop.append (POP_SIZE, random); + + // topology + eoLinearTopology topology(NEIGHBORHOOD_SIZE); + eoInitializer init(eval,veloRandom,localInit,topology,pop); + init(); + + // velocity + eoExtendedVelocity velocity (topology,1,1,1,1); + + // the test itself + for (unsigned int i = 0; i < POP_SIZE; i++) + { + std::cout << " Initial particle n°" << i << " velocity: " << std::endl; + for (unsigned int j = 0; j < VEC_SIZE; j++) + std::cout << " v" << j << "=" << pop[i].velocities[j] << std::endl; + } + + for (unsigned int i = 0; i < POP_SIZE; i++) + velocity (pop[i],i); + + for (unsigned int i = 0; i < POP_SIZE; i++) + { + std::cout << " Final particle n°" << i << " velocity: " << std::endl; + for (unsigned int j = 0; j < VEC_SIZE; j++) + std::cout << " v" << j << "=" << pop[i].velocities[j] << std::endl; + } + return EXIT_SUCCESS; +} + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << " in t-eoExtendedVelocity" << std::endl; + } + return EXIT_SUCCESS; +} diff --git a/deprecated/eo/test/t-eoExternalEO.cpp b/deprecated/eo/test/t-eoExternalEO.cpp new file mode 100644 index 000000000..8246863f6 --- /dev/null +++ b/deprecated/eo/test/t-eoExternalEO.cpp @@ -0,0 +1,132 @@ +// to avoid long name warnings +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include // runtime_error + +#include +#include +#include + +using namespace std; + +struct UserDefStruct +{ + int a; + float b; + double c; + enum Enum { just, another, test } d; +}; + +std::ostream& operator<<(std::ostream& os, const UserDefStruct& str) +{ + return os << str.a << ' ' << str.b << ' ' << str.c << ' ' << static_cast(str.d) << ' '; +} + +istream& operator>>(istream& is, UserDefStruct& str) +{ + is >> str.a; + is >> str.b; + is >> str.c; + int i; + is >> i; + str.d = static_cast(i); + + return is; +} + + +UserDefStruct RandomStruct() +{ + std::cout << "RandomStruct\n"; + + UserDefStruct result; + + result.a = rng.random(5); + result.b = rng.uniform(); + result.c = rng.uniform(); + result.d = UserDefStruct::another; + + return result; +} + +// reading and writing + + +bool UserDefMutate(UserDefStruct& a) +{ + std::cout << "UserDefMutate\n"; + a = RandomStruct(); // just for testing + + if (rng.flip(0.1f)) + a.d = UserDefStruct::test; + else + a.d = UserDefStruct::another; + return true; +} + +bool UserDefBinCrossover(UserDefStruct& a, const UserDefStruct& b) +{ + std::cout << "UserDefBinCrossover\n"; + + if (rng.flip(0.5)) + a.a = b.a; + if (rng.flip(0.5)) + a.b = b.b; + if (rng.flip(0.5)) + a.c = b.c; + if (rng.flip(0.5)) + a.d = b.d; + return true; +} + +bool UserDefQuadCrossover(UserDefStruct& a, UserDefStruct& b) +{ + std::cout << "UserDefQuadCrossover\n"; + if (rng.flip(0.5)) + swap(a.a, b.a); + if (rng.flip(0.5)) + swap(a.b, b.b); + if (rng.flip(0.5)) + swap(a.c, b.c); + if (rng.flip(0.5)) + swap(a.d, b.d); + + return true; +} + +float UserDefEvalFunc(const UserDefStruct& a) +{ + std::cout << "UserDefEvalFunc\n"; + return a.b; +} + +int main() +{ + typedef UserDefStruct External; + typedef float FitnessType; + typedef eoExternalEO EoType; + + eoExternalInit init(RandomStruct); + eoExternalMonOp mutate(UserDefMutate); + eoExternalBinOp cross1(UserDefBinCrossover); + eoExternalQuadOp cross2(UserDefQuadCrossover); + + // eoExternalEvalFunc eval(UserDefEvalFunc); + + EoType eo1; + init(eo1); + EoType eo2; + init(eo2); + + std::cout << "before mutation " << eo1 << '\n'; + mutate(eo1); + std::cout << "after mutation " << eo1 << '\n'; + cross1(eo1, eo2); + std::cout << "after crossover " << eo1 << '\n'; + + cross2(eo1,eo2); + +} diff --git a/deprecated/eo/test/t-eoFitnessAssembled.cpp b/deprecated/eo/test/t-eoFitnessAssembled.cpp new file mode 100644 index 000000000..018d739a4 --- /dev/null +++ b/deprecated/eo/test/t-eoFitnessAssembled.cpp @@ -0,0 +1,104 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// t-eoFitnessAssembled.cpp +// Marc Wintermantel & Oliver Koenig +// IMES-ST@ETHZ.CH +// March 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 + 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 +*/ +//----------------------------------------------------------------------------- +#include +#include + +#include "eoScalarFitnessAssembled.h" + +void test_eoScalarFitnessAssembledClass(){ + + // Create instances + eoAssembledMinimizingFitness A,B,C(5, 1.3, "C value"); + + // Add some values to them + A.push_back( 5.6, "first value" ); + A.push_back( 3.2, "second value" ); + A.push_back( 2.6, "third value" ); + + B.push_back( 1.2 ); + B.push_back( 3.2 ); + B.push_back( 5.2 ); + + B.setDescription( 1, "B descr" ); + + std::cout << "Created instances A,B and C, added some vals; testing << operator " << std::endl; + std::cout << "A= " << A << std::endl; + std::cout << "B= " << B << std::endl; + 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 << "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; + + std::cout << "Access fitness values of A and B: " << "f(A)= " << (double) A << " f(B)= " << (double) B << std::endl; + + // Testing constructors and assignments + eoAssembledMinimizingFitness D(A) ,E(3.2); + std::cout << "D(A) = " << D << "\t" << "E(3.2)= " << E << std::endl; + eoAssembledMinimizingFitness F,G; + 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; + std::cout << "A<=B: " << (A<=B) << std::endl; + std::cout << "A>=B: " << (A>=B) << std::endl; + +} + + + +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){ + std::cout << e.what() << std::endl; + return 1; + } + + std::cout << "END t-eoFitnessAssembled" << std::endl; + std::cout << "----------------------------------" << std::endl; + + return 0; + +} diff --git a/deprecated/eo/test/t-eoFitnessAssembledEA.cpp b/deprecated/eo/test/t-eoFitnessAssembledEA.cpp new file mode 100644 index 000000000..e04535673 --- /dev/null +++ b/deprecated/eo/test/t-eoFitnessAssembledEA.cpp @@ -0,0 +1,174 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// t-eoFitnessAssembledEA.cpp +// Marc Wintermantel & Oliver Koenig +// IMES-ST@ETHZ.CH +// March 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 + 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 +*/ +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +// General eo includes +#include +#include // The real bounds (not yet in general eo include) + +// Representation dependent includes and typedefs +#include // Definition of representation +#include // Uniformly initializes real vector in bounds +#include // Initialization of a genotype +#include // Base class for fitness evaluation +#include // Variation operators using standard Real operators +#include // The fitness class +typedef eoReal Indi; + +// Representation independent modules +#include // Initialization of population +#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 + +// Define a fitness class +template +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); + tmpfit.setDescription(0,"Fitness"); + tmpfit.setDescription(1,"Some Value"); + tmpfit.setDescription(2,"Other Value"); + + } + + void operator()(EOT& _eo){ + + // 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 ); + + } +}; + +// checks for help demand, and writes the status file and make_help; in libutils +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 + eoState state; // keeps all things allocated + + //// + // A) Representation dependent stuff + //// + + // The fitness + eoAssembledEvalFunc plainEval; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // The genotype + eoRealInitBounded& init = do_make_genotype(parser, state, Indi() ); + + // The variation operators + eoGenOp& op = do_make_op(parser, state, init); + + //// + // B) Create representation independent stuff + //// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = do_make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = do_make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = do_make_checkpoint_assembled(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = do_make_algo_scalar(parser, state, eval, checkpoint, op); + + + make_help(parser); // To be called after all parameters have been read ! + + //// + // C) Run the algorithm + //// + + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out + std::cout << "Initial Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + + do_run(ga, pop); // run the ga + + std::cout << "Final Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + + } + catch(std::exception& e) + { + std::cout << e.what() << std::endl; + return 1; + } + + std::cout << "-----------------------------------" << std::endl; + std::cout << "END t-eoFitnessAssembledEA" << std::endl; + + return 0; + +} diff --git a/deprecated/eo/test/t-eoFunctor.cpp b/deprecated/eo/test/t-eoFunctor.cpp new file mode 100644 index 000000000..f309eebcf --- /dev/null +++ b/deprecated/eo/test/t-eoFunctor.cpp @@ -0,0 +1,48 @@ +#include +#include + +void f(eoInit& func) +{ + int i; + func(i); +} + +class Tester : public eoInit +{ +public : + void operator()(int& i) + { + i=1; + } +}; + +#include +#include +#include + +using namespace std; + +int main(void) +{ + Tester test; + + eoFunctorStore store; + + /// make a counter and store it in 'store' + eoInit& cntr = make_counter(functor_category(test), test, store); + + eoUnaryFunctorCounter > cntr2(test); + + f(cntr); + f(cntr2); + f(cntr2); + f(test); + + typedef eoVariableLength EoType; + EoType eo; + + eo.push_back(1); + eo.push_back(2); + + return 1; +} diff --git a/deprecated/eo/test/t-eoGA.cpp b/deprecated/eo/test/t-eoGA.cpp new file mode 100644 index 000000000..fafed297d --- /dev/null +++ b/deprecated/eo/test/t-eoGA.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include +#include "binary_value.h" +#include + +using namespace std; + +int main(int argc, char* argv[]) +{ + + try + { + typedef eoBit EOT; + + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr mainEval( binary_value ); + eoEvalFuncCounter eval(mainEval); + + // the genotype - through a genotype initializer + eoInit& init = make_genotype(parser, state, EOT()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + //// Now the representation-independent things + ////////////////////////////////////////////// + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorith + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // print it out + std::cout << "Initial Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + + run_ea(ga, pop); // run the ga + + std::cout << "Final Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + } + catch(std::exception& e) + { + std::cout << e.what() << std::endl; + } +} diff --git a/deprecated/eo/test/t-eoGenOp.cpp b/deprecated/eo/test/t-eoGenOp.cpp new file mode 100644 index 000000000..c959a3bb9 --- /dev/null +++ b/deprecated/eo/test/t-eoGenOp.cpp @@ -0,0 +1,427 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenOp.cpp +// (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 + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +/** test program for the general operator - millenium version! + * uses dummy individuals + */ + +#include + +#include +#include +#include + +struct Dummy : public EO +{ + Dummy(std::string _s="") : s(_s) {} + + void printOn(std::ostream & _os) const + { + EO::printOn(_os); + _os << " - " << s ; + } + + std::string s; +}; + +typedef Dummy EOT; + +unsigned int pSize; // global to be used as marker in the fitness + +// DEFINITIONS of the eoOps +class monop : public eoMonOp +{ + public : + monop(char * _sig){sig=_sig;} + bool operator()(EOT& _eo) + { + _eo.s = sig + "(" + _eo.s + ")"; + _eo.fitness(_eo.fitness()+pSize); + return false; + } + std::string className() const {return sig;} + private: + std::string sig; +}; + +class binop: public eoBinOp +{ + public : + bool operator()(EOT& _eo1, const EOT& _eo2) + { + _eo1.s = "bin(" + _eo1.s + "," + _eo2.s + ")"; + double f= (_eo1.fitness()+_eo2.fitness()) * pSize; + _eo1.fitness(_eo1.fitness()+f); + return false; + } + std::string className() const {return "binop";} +}; + +class quadop: public eoQuadOp +{ + public : + std::string className() const {return "quadop";} + bool operator()(EOT& a, EOT& b) + { + EOT oi = a; + EOT oj = b; + + a.s = "quad1(" + oi.s + "," + oj.s + ")"; + b.s = "quad2(" + oj.s + "," + oi.s + ")"; + double f= (a.fitness()+b.fitness()+2*pSize) * pSize; + a.fitness(a.fitness()+f); + b.fitness(b.fitness()+f); + return false; + } +}; +// an eoQuadOp that does nothing +class quadClone: public eoQuadOp +{ + public : + std::string className() const {return "quadclone";} + bool operator()(EOT& , EOT& ) {return false;} +}; + +// User defined General Operator... adapted from Marc's example + +class one2threeOp : public eoGenOp // :-) +{ + public: + unsigned max_production(void) { return 3; } + + void apply(eoPopulator& _plop) + { + EOT& eo = *_plop; // select the guy + + ++_plop; // advance + _plop.insert("v(" + eo.s + ", 1)"); + ++_plop; + _plop.insert("v(" + eo.s + ", 2)"); + eo.s = "v(" + eo.s + ", 0)"; // only now change the thing + // oh right, and invalidate fitnesses + } + virtual std::string className() const {return "one2threeOp";} +}; + + +class two2oneOp : public eoGenOp // :-) +{ + public: + unsigned max_production(void) { return 1; } + + void apply(eoPopulator& _plop) + { + EOT& eo = *_plop; // select the guy + const EOT& eo2 = _plop.select(); + eo.s = "221(" + eo.s + ", " + eo2.s + ")"; + // oh right, and invalidate fitnesses + } + virtual std::string className() const {return "two2oneOp";} +}; + +class three2threeOp : public eoGenOp // :-) +{ + public: + unsigned max_production(void) { return 3; } + + void apply(eoPopulator& _plop) + { + EOT& eo1 = *_plop; // select 1st guy + EOT& eo2 = *++_plop; // select 2nd guy + EOT& eo3 = *++_plop; // select 3rd guy + EOT a = eo1; + EOT b = eo2; + EOT c = eo3; + std::cout << "les selectionnes: a=" << a << " et b=" << b << " et c=" << c << std::endl; + eo1.s = "323-1(" + a.s + ", " + b.s + ", " + c.s + ")"; + eo2.s = "323-2(" + a.s + ", " + b.s + ", " + c.s + ")"; + eo3.s = "323-3(" + a.s + ", " + b.s + ", " + c.s + ")"; + // oh right, and invalidate fitnesses + std::cout << "les enfants: a=" << eo1 << " et b=" << eo2 << " et c=" << eo3 << std::endl; + } + virtual std::string className() const {return "three2threeOp";} +}; + + +// dummy intialization. Re-init if no pSize, resize first if pSize +void init(eoPop & _pop, unsigned _pSize) +{ + if (_pSize) + { + _pop.resize(_pSize); + } + else + { + throw std::runtime_error("init pop with 0 size"); + } + for (unsigned i=0; i<_pSize; i++) + { + std::ostringstream os; + os << i; + _pop[i] = Dummy(os.str()); + _pop[i].fitness(i); + } +} + +// ok, now for the real work +int the_main(int argc, char **argv) +{ + eoParser parser(argc, argv); + eoValueParam parentSizeParam( + parser.createParam(unsigned(10), "parentSize", "Parent size",'P')); + pSize = parentSizeParam.value(); // global variable + + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + parser.processParam( seedParam ); + eo::rng.reseed(seedParam.value()); + + // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED + // i.e. in case you need parameters somewhere else, postpone these + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + ////////////////////////////////// define operators + monop mon((char*)"mon1"); + monop clone((char*)"clone"); + binop bin; + quadop quad; + quadClone quadclone; + + // our own operator + one2threeOp o2t; + two2oneOp t2o; + three2threeOp t2t; + + + // a selector + eoDetTournamentSelect select; + // and a recognizable selector for testing the inbedded selector mechanism + eoBestSelect selectBest; + + // proportional selection between quad and bin + // so we either do a quad or a bin + eoProportionalOp pOp; + pOp.add(quad, 0.1); + pOp.add(bin, 0.1); + + // sequential selection between pOp and mon + eoSequentialOp sOp; + sOp.add(pOp, 0.9); + sOp.add(mon, 0.1); + + // with one2three op + eoSequentialOp sOp2; + sOp2.add(o2t, 1); + // sOp2.add(quad, 1); + + // with three2three op + eoSequentialOp sOp3; + sOp3.add(t2t, 1); + +// eoSequentialOp sOp3; +// sOp3.add(t2o, 1); +// sOp3.add(bin, 1); +// sOp3.add(quad, 1); + // try adding quads and bins to see what results you'll get + + // now a sequential selection that is a simple "addition" + eoSequentialOp sOpQuadPlusMon; + sOpQuadPlusMon.add(quad, 1); + sOpQuadPlusMon.add(mon, 1); + + // this corresponds + eoProportionalOp pOpSAGLike; + pOpSAGLike.add(sOpQuadPlusMon, 0.24); + pOpSAGLike.add(quad, 0.56); + pOpSAGLike.add(mon, 0.06); + pOpSAGLike.add(clone, 0.14); + + // init + eoPop pop; + eoPop offspring; + + init(pop, pSize); +// sort pop so seqPopulator is identical to SelectPopulator(SequentialSelect) + pop.sort(); + std::cout << "Population initiale" << std::endl << pop << std::endl; + + // To simulate SGA: first a prop between quadOp and quadClone + eoProportionalOp pSGAOp; + pSGAOp.add(quad, 0.8); + pSGAOp.add(quadclone, 0.2); + // sequential selection between pSGAOp and mon + eoSequentialOp virtualSGA; + virtualSGA.add(pSGAOp, 1.0); + virtualSGA.add(mon, 0.3); + + eoSeqPopulator popit(pop, offspring); // no selection, a copy of pop + + // until we filled a new population + try + { + while (offspring.size() < pop.size()) + { + virtualSGA(popit); + std::cout << "SeqPopulator boucle et incremente\n"; + ++popit; + } + } + catch(eoPopulator::OutOfIndividuals&) + { + std::cout << "Warning: not enough individuals to handle\n"; + } + + + std::swap(pop, offspring); + offspring.clear(); + + // ok, now print + std::cout << "Apres virtualSGA \n" << pop << std::endl; + init(pop, pSize); + + std::cout << "=========================================================\n"; + std::cout << "Now the eoSelectPopulator version !" << std::endl; + + eoSequentialSelect seqSelect; + // select.init(); should be sorted out: is it the setup method??? + eoSelectivePopulator it_step3(pop, offspring, seqSelect); + + while (offspring.size() < 2*pop.size()) + { + virtualSGA(it_step3); + std::cout << "SelectPopulator boucle et incremente\n"; + ++it_step3; + } + + std::swap(pop, offspring); + offspring.clear(); + + // ok, now print + std::cout << "Apres SGA-like eoSelectivePopulator\n" << pop << std::endl; + + std::cout << "=========================================================\n"; + std::cout << "Now the pure addition !" << std::endl; + + init(pop, pSize); + eoSelectivePopulator it_step4(pop, offspring, seqSelect); + while (offspring.size() < 2*pop.size()) + { + sOpQuadPlusMon(it_step4); + ++it_step4; + } + + std::swap(pop, offspring); + offspring.clear(); + + // ok, now print + std::cout << "Apres Quad+Mon ds un eoSelectivePopulator\n" << pop << std::endl; + + // On teste 1->3 + init(pop, pSize); + eoSelectivePopulator it_step5(pop, offspring, seqSelect); + while (offspring.size() < 2*pop.size()) + { + sOp2(it_step5); + ++it_step5; + } + + std::swap(pop, offspring); + offspring.clear(); + + // ok, now print + std::cout << "Apres 1->3 seul ds un eoSelectivePopulator\n" << pop << std::endl; + + // On teste 3->3 + init(pop, pSize); + eoSelectivePopulator it_step6(pop, offspring, seqSelect); + while (offspring.size() < 2*pop.size()) + { + sOp3(it_step6); + ++it_step6; + } + + std::swap(pop, offspring); + offspring.clear(); + + // ok, now print + std::cout << "Apres 3->3 seul ds un eoSelectivePopulator\n" << pop << std::endl; + + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << std::endl; + } + +} + +/* +If you want to build an SGA, you will need a copying quad op: + +class quadclone : ... +{ + operator(EOT& a, EOT& b) + { + // do nothing + } + +} + +Then the SGA operator will look like: + +quadop quad; +guadclone clone; + +ProportionalGenOp pOp; +pOp.add(quad, 0.8); +pOp.add(clone, 0.2); // so 80% xover rate + +SequentialGenOp sOp; +sOp.add(pOp, 1,0); // always try a xover (clone 20%) +sOp.add(mut, 0.1); // low mutation rate + +will result in an algorithm with: + +p_xover = 0.8 +p_mut = 0.1; + +p_reproduction = 0.2 * 0.9 = 0.18 + +this does not add up to 1 because xover and mutation can be applied to a single indi + +So what do you think? + +*/ diff --git a/deprecated/eo/test/t-eoIQRStat.cpp b/deprecated/eo/test/t-eoIQRStat.cpp new file mode 100644 index 000000000..e49dc38d4 --- /dev/null +++ b/deprecated/eo/test/t-eoIQRStat.cpp @@ -0,0 +1,67 @@ +#include +#include +#include + +#include "real_value.h" + +typedef eoReal realVec; + +double test( eoPop& pop, double target_value ) +{ + eoEvalFuncPtr&> eval( real_value ); + + eoPopLoopEval pop_eval(eval); + + pop_eval(pop,pop); + + eoInterquartileRangeStat iqr_stat(0.0, "IQR"); + + iqr_stat( pop ); + + std::cout << iqr_stat.longName() << "=" << iqr_stat.value() << " should be " << target_value << std::endl; + + return iqr_stat.value(); +} + +int main() +{ + eoPop pop; + + // fixed test + realVec sol1(2,-1); + realVec sol2(2,-1); + realVec sol3(2,1); + realVec sol4(2,1); + pop.push_back( sol1 ); + pop.push_back( sol2 ); + pop.push_back( sol3 ); + pop.push_back( sol4 ); + // on the sphere function everyone has the same fitness of 1 + if( test(pop, 0) != 0 ) { + exit(1); + } + + pop.erase(pop.begin(),pop.end()); + + // fixed test + sol1 = realVec(2,0); + sol2 = realVec(2,0); + sol3 = realVec(2,1); + sol4 = realVec(2,1); + pop.push_back( sol1 ); + pop.push_back( sol2 ); + pop.push_back( sol3 ); + pop.push_back( sol4 ); + if( test(pop, 1) != 1 ) { + exit(1); + } + + // test on a random normal distribution + eoNormalGenerator normal(1,rng); + eoInitFixedLength init_N(2, normal); + pop = eoPop( 1000000, init_N ); + double iqr = test(pop, 1.09); + if( iqr < 1.08 || iqr > 1.11 ) { + exit(1); + } +} diff --git a/deprecated/eo/test/t-eoInitPermutation.cpp b/deprecated/eo/test/t-eoInitPermutation.cpp new file mode 100644 index 000000000..e4a683b15 --- /dev/null +++ b/deprecated/eo/test/t-eoInitPermutation.cpp @@ -0,0 +1,68 @@ +//----------------------------------------------------------------------------- +// t-eoInitPermutation.cpp +//----------------------------------------------------------------------------- + +#include + +#include + +//----------------------------------------------------------------------------- + +typedef eoInt Chrom; + +//----------------------------------------------------------------------------- + + +double real_value(const Chrom & _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + sum += _chrom[i]; + return sum/_chrom.size(); +} + +// Return true if the given chromosome corresponds to a permutation +// There must be an nicer way to do it (set?) ... +bool check_permutation(const Chrom & _chrom) +{ + for (unsigned i = 0; i < _chrom.size(); ++i) + for (unsigned j = 0; j < _chrom.size(); ++j) + if(i!=j) + if(_chrom[i]==_chrom[j]){ + std::cout << " Error: Wrong permutation !" << std::endl; + std::string s; + s.append( " Wrong permutation in t-eoInitPermutation"); + throw std::runtime_error( s ); + } + return true; +} + +int main() +{ + const unsigned POP_SIZE = 8, CHROM_SIZE = 16; + unsigned i; + + // a chromosome randomizer + eoInitPermutation random(CHROM_SIZE); + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( real_value ); + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + std::cout << " Initial chromosome n°" << i << " : " << chrom << "..." << std::endl; + random(chrom); + eval(chrom); + std::cout << " ... becomes : " << chrom << " after initialization" << std::endl; + check_permutation(chrom); + pop.push_back(chrom); + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoInt.cpp b/deprecated/eo/test/t-eoInt.cpp new file mode 100644 index 000000000..279803ce3 --- /dev/null +++ b/deprecated/eo/test/t-eoInt.cpp @@ -0,0 +1,24 @@ +//----------------------------------------------------------------------------- +// t-eoInt.cpp +//----------------------------------------------------------------------------- + +#include +#include + +//----------------------------------------------------------------------------- + +typedef eoInt Chrom; + +//----------------------------------------------------------------------------- + +int main() +{ + Chrom chrom1, chrom2; + + std::cout << "chrom1 = " << chrom1 << std::endl + << "chrom2 = " << chrom2 << std::endl; + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoLogger.cpp b/deprecated/eo/test/t-eoLogger.cpp new file mode 100644 index 000000000..198a88720 --- /dev/null +++ b/deprecated/eo/test/t-eoLogger.cpp @@ -0,0 +1,50 @@ +//----------------------------------------------------------------------------- +// t-eoLogger.cpp +//----------------------------------------------------------------------------- + +#include + +//----------------------------------------------------------------------------- + +int main(int ac, char** av) +{ + eoParser parser(ac, av); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + make_help(parser); + make_verbose(parser); + + eo::log << eo::setlevel(eo::debug); + + eo::log << eo::warnings; + + eo::log << "We are writing on the default output stream" << std::endl; + + eo::log << eo::file("test.txt") << "In FILE" << std::endl; + eo::log << std::cout << "on COUT" << std::endl; + + eo::log << eo::setlevel("errors"); + eo::log << eo::setlevel(eo::errors); + + eo::log << eo::quiet << "1) in quiet mode" << std::endl; + + eo::log << eo::setlevel(eo::warnings) << eo::warnings << "2) in warnings mode" << std::endl; + + eo::log << eo::setlevel(eo::logging); + + eo::log << eo::errors; + eo::log << "3) in errors mode"; + eo::log << std::endl; + + eo::log << eo::debug << 4 << ')' + << "4) in debug mode\n"; + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoOrderXover.cpp b/deprecated/eo/test/t-eoOrderXover.cpp new file mode 100644 index 000000000..32e44dad9 --- /dev/null +++ b/deprecated/eo/test/t-eoOrderXover.cpp @@ -0,0 +1,72 @@ +//----------------------------------------------------------------------------- +// t-eoOrderXover.cpp +//----------------------------------------------------------------------------- + +#include + +#include +#include +#include + + +//----------------------------------------------------------------------------- + +typedef eoInt Chrom; + +//----------------------------------------------------------------------------- +// Return true if the given chromosome corresponds to a permutation +bool check_permutation(const Chrom& _chrom){ + unsigned size= _chrom.size(); + std::set verif; + for(unsigned i=0; i< size; i++){ + if(verif.insert(_chrom[i]).second==false){ + std::cout << " Error: Wrong permutation !" << std::endl; + std::string s; + s.append( " Wrong permutation in t-eoShiftMutation"); + throw std::runtime_error( s ); + return false; + } + } + return true; +} + + +int main() +{ + const unsigned POP_SIZE = 3, CHROM_SIZE = 8; + unsigned i; + + // a chromosome randomizer + eoInitPermutation random(CHROM_SIZE); + + // the population: + eoPop pop; + + // Evaluation + //eoEvalFuncPtr eval( real_value ); + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + //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; + check_permutation(pop[i]); + } + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoPBIL.cpp b/deprecated/eo/test/t-eoPBIL.cpp new file mode 100644 index 000000000..1d2654b83 --- /dev/null +++ b/deprecated/eo/test/t-eoPBIL.cpp @@ -0,0 +1,148 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// t-eoPBIL.cpp +// (c) Marc Schoenauer, 2001 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: Marc.Schoenauer@inria.fr + */ +//----------------------------------------------------------------------------- + +/** test program for PBIL algorithm */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include "binary_value.h" +#include +#include +#include +#include +#include + + +using namespace std; + +typedef eoBit Indi; + +// instanciating the outside subroutine that creates the distribution +#include "ga/make_PBILdistrib.h" +eoPBILDistrib & make_PBILdistrib(eoParser& _parser, eoState&_state, Indi _eo) +{ + return do_make_PBILdistrib(_parser, _state, _eo); +} + +// instanciating the outside subroutine that creates the update rule +#include "ga/make_PBILupdate.h" +eoDistribUpdater & make_PBILupdate(eoParser& _parser, eoState&_state, Indi _eo) +{ + return do_make_PBILupdate(_parser, _state, _eo); +} + + +int main(int argc, char* argv[]) +{ + + try + { + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr mainEval( binary_value); + eoEvalFuncCounter eval(mainEval); + + // Construction of the distribution + eoPBILDistrib & distrib = make_PBILdistrib(parser, state, Indi()); + // and the update rule + eoDistribUpdater & update = make_PBILupdate(parser, state, Indi()); + + //// Now the representation-independent things + ////////////////////////////////////////////// + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + + // add a graphical output for the distribution + // first, get the direname from the parser + // it has been enetered in make_checkoint + + eoParam* ptParam = parser.getParamWithLongName(string("resDir")); + eoValueParam* ptDirNameParam = dynamic_cast*>(ptParam); + if (!ptDirNameParam) // not found + throw runtime_error("Parameter resDir not found where it was supposed to be"); + + // now create the snapshot monitor + eoValueParam& plotDistribParam = parser.getORcreateParam(false, "plotDistrib", + "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"); + state.storeFunctor(distribSnapshot); + // add the distribution (it is an eoValueParam >) + distribSnapshot->add(distrib); + // and of course add it to the checkpoint + checkpoint.add(*distribSnapshot); +#endif + } + + // 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(); + eoSimpleEDA eda(update, eval, popSize, checkpoint); + + ///// End of construction of the algorith + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + + eda(distrib); // run the eda + + std::cout << "Final Distribution\n"; + distrib.printOn(std::cout); + std::cout << std::endl; + + // wait - for graphical output + if (plotDistribParam.value()) + { + string foo; + cin >> foo; + } + } + catch(std::exception& e) + { + std::cout << e.what() << std::endl; + } +} diff --git a/deprecated/eo/test/t-eoParallel.cpp b/deprecated/eo/test/t-eoParallel.cpp new file mode 100644 index 000000000..72d4f264a --- /dev/null +++ b/deprecated/eo/test/t-eoParallel.cpp @@ -0,0 +1,56 @@ +//----------------------------------------------------------------------------- +// t-eoParallel.cpp +//----------------------------------------------------------------------------- + +#include + +#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; + +#pragma omp parallel + { + if ( 0 == omp_get_thread_num() ) + { + eo::log << "num of threads: " << omp_get_num_threads() << std::endl; + } + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoParser.cpp b/deprecated/eo/test/t-eoParser.cpp new file mode 100644 index 000000000..1fd6c7fdb --- /dev/null +++ b/deprecated/eo/test/t-eoParser.cpp @@ -0,0 +1,31 @@ +#include +#include + +int main(int ac, char** av) +{ + eoParser parser(ac, av); + + unsigned int alpha1 = parser.createParam(10, "alpha1", "Alpha parameter").value(); + unsigned int alpha2 = parser.createParam(10, "alpha2", "Alpha parameter").value(); + unsigned int alpha3 = parser.createParam(10, "alpha3", "Alpha parameter").value(); + unsigned int alpha4 = parser.createParam(10, "alpha4", "Alpha parameter").value(); + unsigned int alpha5 = parser.createParam(10, "alpha5", "Alpha parameter").value(); + unsigned int alpha6 = parser.createParam(10, "alpha6", "Alpha parameter").value(); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + make_help(parser); + + std::cout << "alpha1: " << alpha1 << std::endl; + std::cout << "alpha2: " << alpha2 << std::endl; + std::cout << "alpha3: " << alpha3 << std::endl; + std::cout << "alpha4: " << alpha4 << std::endl; + std::cout << "alpha5: " << alpha5 << std::endl; + std::cout << "alpha6: " << alpha6 << std::endl; + + return 0; +} diff --git a/deprecated/eo/test/t-eoRNG.cpp b/deprecated/eo/test/t-eoRNG.cpp new file mode 100644 index 000000000..1ece31a06 --- /dev/null +++ b/deprecated/eo/test/t-eoRNG.cpp @@ -0,0 +1,53 @@ +//----------------------------------------------------------------------------- +// t-rng.cpp +//----------------------------------------------------------------------------- + +// This file really needs to be implementes usign some stringent tests, for now +// we simply check that the impementation of some methods does generally work... + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + + +using namespace std; + + +int main() +{ + const size_t num(10000); + double mean(100.); + 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; + } + 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; + } + return 0; +} + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/test/t-eoRandom.cpp b/deprecated/eo/test/t-eoRandom.cpp new file mode 100644 index 000000000..30da63e30 --- /dev/null +++ b/deprecated/eo/test/t-eoRandom.cpp @@ -0,0 +1,66 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + t-eoRandom.cpp + Test program for random generator + + (c) GeNeura Team, 1999 + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; 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 + +*/ + +/** +CVS Info: $Date: 2003-02-27 19:20:24 $ $Author: okoenig $ $Revision: 1.13 $ +*/ + +//----------------------------------------------------------------------------- + +#include // cout +#include // ostrstream, istrstream +#include // eoBin +//#include +//#include + +//----------------------------------------------------------------------------- + +int main() { + eoUniformGenerator u1(-2.5,3.5); + eoUniformGenerator u2(0.003, 0.05 ); + eoUniformGenerator u3( 10000U, 10000000U); + + try + { // throws an error + eoUniformGenerator utest( 10000000U, 10000U); + throw; // if this succeeds something is wrong, make sure that that is noticed + } + catch (std::logic_error& e) + { + std::cout << e.what() << std::endl; + } + + std::ofstream os("t-eoRandom.out"); + + for ( unsigned i = 0; i < 100; i ++) + { + os << u1() << "\t" << u2() << "\t" << u3() << std::endl; + } + + return 0; // to avoid VC++ complaints + +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoReal.cpp b/deprecated/eo/test/t-eoReal.cpp new file mode 100644 index 000000000..163b0ea86 --- /dev/null +++ b/deprecated/eo/test/t-eoReal.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include "real_value.h" +#include + +using namespace std; + +int main(int argc, char* argv[]) +{ + + try + { + typedef eoReal EOT; + + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + mainEval( real_value ); + eoEvalFuncCounter eval(mainEval); + + // the genotype - through a genotype initializer + eoRealInitBounded& init = make_genotype(parser, state, EOT()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + //// Now the representation-independent things + ////////////////////////////////////////////// + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ea = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorith + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // print it out + std::cout << "Initial Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + + run_ea(ea, pop); // run the ea + + std::cout << "Final Population\n"; + pop.sortedPrintOn(std::cout); + std::cout << std::endl; + } + catch(std::exception& e) + { + std::cout << e.what() << std::endl; + } +} diff --git a/deprecated/eo/test/t-eoReplacement.cpp b/deprecated/eo/test/t-eoReplacement.cpp new file mode 100644 index 000000000..fc44543d8 --- /dev/null +++ b/deprecated/eo/test/t-eoReplacement.cpp @@ -0,0 +1,223 @@ +//----------------------------------------------------------------------------- + +// to avoid long name warnings +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include // runtime_error + +//----------------------------------------------------------------------------- +// tt.cpp: +// +//----------------------------------------------------------------------------- + + +// general +#include +//----------------------------------------------------------------------------- + +struct Dummy : public EO +{ + typedef double Type; + void printOn(std::ostream & _os) const + { + _os << " - "; + EO::printOn(_os); + } +}; + + +struct eoDummyPop : public eoPop +{ +public : + eoDummyPop(int s=0) { resize(s); } +}; + +//----------------------------------------------------------------------------- + +int the_main(int argc, char **argv) +{ + eoParser parser(argc, argv); + eoValueParam parentSizeParam(10, "parentSize", "Parent size",'P'); + parser.processParam( parentSizeParam ); + unsigned int pSize = parentSizeParam.value(); + + eoValueParam offsrpringSizeParam(10, "offsrpringSize", "Offsrpring size",'O'); + parser.processParam( offsrpringSizeParam ); + unsigned int oSize = offsrpringSizeParam.value(); + + eoValueParam tournamentSizeParam(2, "tournamentSize", "Deterministic tournament size",'T'); + parser.processParam( tournamentSizeParam ); + unsigned int tSize = tournamentSizeParam.value(); + + eoValueParam tournamentRateParam(0.75, "tournamentRate", "Stochastic tournament rate",'R'); + parser.processParam( tournamentRateParam ); + double tRate = tournamentRateParam.value(); + + eoValueParam sParentsElitismRateParam(0.1, "sParentsElitismRateParam", "Strong elitism rate for parents",'E'); + parser.processParam( sParentsElitismRateParam ); + double sParentsElitismRate = sParentsElitismRateParam.value(); + + eoValueParam sParentsEugenismRateParam(0, "sParentsEugenismRateParam", "Strong Eugenism rate",'e'); + parser.processParam( sParentsEugenismRateParam ); + double sParentsEugenismRate = sParentsEugenismRateParam.value(); + + eoValueParam sOffspringElitismRateParam(0, "sOffspringElitismRateParam", "Strong elitism rate for parents",'E'); + parser.processParam( sOffspringElitismRateParam ); + double sOffspringElitismRate = sOffspringElitismRateParam.value(); + + eoValueParam sOffspringEugenismRateParam(0, "sOffspringEugenismRateParam", "Strong Eugenism rate",'e'); + parser.processParam( sOffspringEugenismRateParam ); + double sOffspringEugenismRate = sOffspringEugenismRateParam.value(); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + unsigned i; + + std::cout << "Testing the replacements\nParents SIze = " << pSize + << " and offspring size = " << oSize << std::endl; + + rng.reseed(42); + + + eoDummyPop orgParents(pSize); + eoDummyPop orgOffspring(oSize); + + // initialize so we can recognize them later! + for (i=0; i genReplace; + eoPlusReplacement plusReplace; + eoEPReplacement epReplace(tSize); + eoCommaReplacement commaReplace; + eoWeakElitistReplacement weakElitistReplace(commaReplace); + // the SSGA replacements + eoSSGAWorseReplacement ssgaWorseReplace; + eoSSGADetTournamentReplacement ssgaDTReplace(tSize); + eoSSGAStochTournamentReplacement ssgaDSReplace(tRate); + + // here we go + // Generational + parents = orgParents; + offspring = orgOffspring; + + std::cout << "eoGenerationalReplacement\n"; + std::cout << "=========================\n"; + genReplace(parents, offspring); +std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (orogonally even\n" << offspring << std::endl; + + // Plus + parents = orgParents; + offspring = orgOffspring; + + std::cout << "eoPlusReplacement\n"; + std::cout << "=================\n"; + plusReplace(parents, offspring); +std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + + // EP (proche d'un PLUS + parents = orgParents; + offspring = orgOffspring; + + std::cout << "eoEPReplacement\n"; + std::cout << "===============\n"; + epReplace(parents, offspring); +std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + + // Comma + parents = orgParents; + offspring = orgOffspring; + + if (parents.size() > offspring.size() ) + std::cout << "Skipping Comma Replacement, more parents than offspring\n"; + else + { + std::cout << "eoCommaReplacement\n"; + std::cout << "==================\n"; + commaReplace(parents, offspring); + std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + + // Comma with weak elitism + parents = orgParents; + offspring = orgOffspring; + + std::cout << "The same, with WEAK elitism\n"; + std::cout << "===========================\n"; + weakElitistReplace(parents, offspring); + std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + } + + // preparing SSGA replace worse + parents = orgParents; + offspring = orgOffspring; + + if (parents.size() < offspring.size() ) + std::cout << "Skipping all SSGA Replacements, more offspring than parents\n"; + else + { + std::cout << "SSGA replace worse\n"; + std::cout << "==================\n"; + ssgaWorseReplace(parents, offspring); + std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + + // SSGA deterministic tournament + parents = orgParents; + offspring = orgOffspring; + + std::cout << "SSGA deterministic tournament\n"; + std::cout << "=============================\n"; + ssgaDTReplace(parents, offspring); + std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + + // SSGA stochastic tournament + parents = orgParents; + offspring = orgOffspring; + + std::cout << "SSGA stochastic tournament\n"; + std::cout << "==========================\n"; + ssgaDTReplace(parents, offspring); + std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + } + + // the general replacement + eoDeterministicSaDReplacement sAdReplace(sParentsElitismRate, sParentsEugenismRate, sOffspringElitismRate, sOffspringEugenismRate);// 10% parents survive + + parents = orgParents; + offspring = orgOffspring; + + std::cout << "General - strong elitism\n"; + std::cout << "========================\n"; + sAdReplace(parents, offspring); + std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl; + + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << std::endl; + } + +} diff --git a/deprecated/eo/test/t-eoRingTopology.cpp b/deprecated/eo/test/t-eoRingTopology.cpp new file mode 100644 index 000000000..de2824c26 --- /dev/null +++ b/deprecated/eo/test/t-eoRingTopology.cpp @@ -0,0 +1,67 @@ +//----------------------------------------------------------------------------- +// t-eoRingTopology.cpp +//----------------------------------------------------------------------------- + + +#include + +typedef eoRealParticle < double >Indi; + +//Evaluation function +double f (const Indi & _indi) +{ + double sum = 0; + for (unsigned i = 0; i < _indi.size (); i++) + sum += pow(_indi[i],2); + return (-sum); +} + +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; + + rng.reseed (33); + eoEvalFuncPtr plainEval(f); + eoEvalFuncCounter < Indi > eval (plainEval); + eoUniformGenerator < double >uGen (0., 5.); + eoInitFixedLength < Indi > random (VEC_SIZE, uGen); + eoUniformGenerator < double >sGen (-1., 1.); + eoVelocityInitFixedLength < Indi > veloRandom (VEC_SIZE, sGen); + eoFirstIsBestInit < Indi > localInit; + eoPop < Indi > pop; + pop.append (POP_SIZE, random); + apply(eval, pop); + apply < Indi > (veloRandom, pop); + apply < Indi > (localInit, pop); + eoRingTopology topology(NEIGHBORHOOD_SIZE); + topology.setup(pop); + std::cout<<"\n\n\nPopulation :\n\n"< +#include +#include +#include + +class TestEO : public EO { public: unsigned index; }; + +using namespace std; + +template +int test_select() +{ + vector probs(4); + probs[0] = 0.1; + probs[1] = 0.4; + probs[2] = 0.2; + probs[3] = 0.3; + + vector counts(4,0.0); + + // setup population + eoPop pop; + for (unsigned i = 0; i < probs.size(); ++i) + { + pop.push_back( TestEO()); + pop.back().fitness( probs[i] * 2.1232 ); // some number to check scaling + pop.back().index = i; + } + + 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)) { + cout << "ERROR" << endl; + return 1; + } + } + + cout << endl; + return 0; +} + +int main() +{ + rng.reseed(44); + + if (test_select >()) return 1; + + return test_select >(); +} diff --git a/deprecated/eo/test/t-eoSSGA.cpp b/deprecated/eo/test/t-eoSSGA.cpp new file mode 100644 index 000000000..d1c467e5a --- /dev/null +++ b/deprecated/eo/test/t-eoSSGA.cpp @@ -0,0 +1,117 @@ +#include + +// tests a Steady State GA + +// Needed to define this breeder, maybe make it a breeder +template +class eoBreedOne : public eoBreed +{ +public : + eoBreedOne(eoSelectOne& _select, eoGenOp& _op) : select(_select), op(_op) {} + + void operator()(const eoPop& _src, eoPop& _dest) + { + _dest.clear(); + eoSelectivePopulator pop(_src, _dest, select); + op(pop); + } + +private : + eoSelectOne& select; + eoGenOp& op; +}; + +typedef eoMinimizingFitness FitnessType; +typedef eoVector EoType; + +template +class eoMyEval : public eoEvalFunc +{ + public : + + void operator()(EOT& _eo) + { + _eo.fitness(*std::max_element(_eo.begin(), _eo.end())); + } +}; + +template +class Xover : public eoBinOp +{ + bool operator()(EOT& _eo, const EOT& _eo2) + { + unsigned point = rng.random(_eo.size()); + std::copy(_eo2.begin() + point, _eo2.end(), _eo.begin() + point); + return true; + } +}; + +template +class Mutate : public eoMonOp +{ + bool operator()(EOT& _eo) + { + unsigned point = rng.random(_eo.size()); + _eo[point] = rng.random(1024); + return true; + } +}; + + +int main() +{ + int pop_size = 10; + + eoGenContinue cnt(10); + eoCheckPoint cp(cnt); + + + Xover xover; + Mutate mutate; + + eoProportionalOp opsel; + + opsel.add(xover, 0.8); + opsel.add(mutate, 0.2); + + + eoDetTournamentSelect selector(3); + eoBreedOne breed(selector, opsel); + + // Replace a single one + eoSSGAWorseReplacement replace; + + +// eoRandomSelect selector; +// eoGeneralBreeder breed(selector, opsel); +// eoPlusReplacement replace; + + + eoMyEval eval; + + eoEasyEA algo(cp, eval, breed, replace); + + eoUniformGenerator unif(0,1024); + eoInitFixedLength init(20, unif); + + eoPop pop(pop_size, init); + + // evaluate + apply(eval, pop); + + eoBestFitnessStat best("Best_Fitness"); + eoAverageStat avg("Avg_Fitness"); + eoStdoutMonitor mon; + + cp.add(best); + cp.add(avg); + +// cp.add(mon); + + mon.add(best); + mon.add(avg); + + // and run + algo(pop); + +} diff --git a/deprecated/eo/test/t-eoSecondsElapsedContinue.cpp b/deprecated/eo/test/t-eoSecondsElapsedContinue.cpp new file mode 100644 index 000000000..d6124c22e --- /dev/null +++ b/deprecated/eo/test/t-eoSecondsElapsedContinue.cpp @@ -0,0 +1,30 @@ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include + +class Dummy : public EO {}; + +int main() { + + eoPop pop; + + eoSecondsElapsedContinue cnt(1); + + time_t start_time = time(0); + + while (cnt(pop)) {} + + time_t end_time = time(0); + + int diff = end_time = start_time; + + if (diff < 1) return 1; + + return 0; + +} diff --git a/deprecated/eo/test/t-eoSelect.cpp b/deprecated/eo/test/t-eoSelect.cpp new file mode 100644 index 000000000..23d76c48c --- /dev/null +++ b/deprecated/eo/test/t-eoSelect.cpp @@ -0,0 +1,222 @@ +// to avoid long name warnings +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include + +#include + +//----------------------------------------------------------------------------- + +struct Dummy : public EO +{ + typedef double Type; + void printOn(std::ostream & _os) const + { + _os << " - "; + EO::printOn(_os); + } +}; + +bool operator==(const Dummy & _d1, const Dummy & _d2) +{ + return _d1.fitness() == _d2.fitness(); +} + +struct eoDummyPop : public eoPop +{ +public : + eoDummyPop(int s=0) { resize(s); } +}; + +// helper - DOES NOT WORK if different individuals have same fitness!!! +template +unsigned isInPop(EOT & _indi, eoPop & _pop) +{ + for (unsigned i=0; i<_pop.size(); i++) + if (_pop[i] == _indi) + return i; + return _pop.size(); +} + +unsigned int pSize; // global variable, bouh! +std::string fitnessType; // yes, a global variable :-) +eoDummyPop parentsOrg; + +template +void testSelectMany(eoSelect & _select, std::string _name) +{ + unsigned i; + std::cout << "\n\n" << fitnessType + _name << std::endl; + std::cout << "===============\n"; + + eoDummyPop parents(parentsOrg); + eoDummyPop offspring(0); + + // do the selection + _select(parents, offspring); + + // compute stats + std::vector nb(parents.size(), 0); + for (i=0; i(offspring[i], parents); + if (trouve == parents.size()) // pas trouve + throw std::runtime_error("Pas trouve ds parents"); + nb[trouve]++; + } + // dump to file so you can plot using gnuplot - dir name is hardcoded! + std::string fName = "ResSelect/" + fitnessType + _name + ".select"; + std::ofstream os(fName.c_str()); + for (i=0; i " << ( (double)nb[i])/offspring.size() << std::endl; + os << i << " " << ( (double)nb[i])/offspring.size() << std::endl; + } + +} + +template +void testSelectOne(eoSelectOne & _select, eoHowMany & _offspringRate, + eoHowMany & _fertileRate, std::string _name) +{ + eoTruncatedSelectOne truncSelect(_select, _fertileRate); + eoSelectMany percSelect(truncSelect, _offspringRate); + testSelectMany(percSelect, _name); +} + + +//----------------------------------------------------------------------------- + +int the_main(int argc, char **argv) +{ + eoParser parser(argc, argv); + eoValueParam parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); + pSize = parentSizeParam.value(); // global variable + +// eoValueParam offsrpringRateParam = parser.createParam(1.0, "offsrpringRate", "Offsrpring rate",'O'); +// double oRate = offsrpringRateParam.value(); + eoValueParam offsrpringRateParam = parser.createParam(eoHowMany(1.0), "offsrpringRate", "Offsrpring rate (% or absolute)",'O'); + eoHowMany oRate = offsrpringRateParam.value(); + + eoValueParam fertileRateParam = parser.createParam(eoHowMany(1.0), "fertileRate", "Fertility rate (% or absolute)",'F'); + eoHowMany fRate = fertileRateParam.value(); + +eoValueParam tournamentSizeParam = parser.createParam(unsigned(2), "tournamentSize", "Deterministic tournament size",'T'); + unsigned int tSize = tournamentSizeParam.value(); + + eoValueParam tournamentRateParam = parser.createParam(1.0, "tournamentRate", "Stochastic tournament rate",'t'); + double tRate = tournamentRateParam.value(); + + eoValueParam rankingPressureParam = parser.createParam(2.0, "rankingPressure", "Selective pressure for the ranking selection",'p'); + double rankingPressure = rankingPressureParam.value(); + + eoValueParam rankingExponentParam = parser.createParam(1.0, "rankingExponent", "Exponent for the ranking selection",'e'); + double rankingExponent = rankingExponentParam.value(); + + eoValueParam fitTypeParam = parser.createParam(std::string("linear"), "fitType", "Type of fitness (linear, exp, log, super",'f'); + fitnessType = fitTypeParam.value(); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(0); + } + + // hard-coded directory name ... + system("mkdir ResSelect"); + std::cout << "Testing the Selections\nParents size = " << pSize + << ", offspring rate = " << oRate; + std::cout << " and putting rsulting files in dir ResSelect" << std::endl; + + // initialize parent population + parentsOrg.resize(pSize); + if (fitnessType == std::string("linear")) + for (unsigned i=0; i& seedParam = parser.createParam(uint32_t(0), "seed", + "Random number seed", 'S'); + if (seedParam.value() == 0) + seedParam.value() = time(0); + rng.reseed(seedParam.value()); + + char fileName[1024]; + +// the selection procedures under test + // eoDetSelect detSelect(oRate); + // testSelectMany(detSelect, "detSelect"); + + // Roulette + eoProportionalSelect propSelect; + testSelectOne(propSelect, oRate, fRate, "PropSelect"); + + // Linear ranking using the perf2Worth construct + eoRankingSelect newRankingSelect(rankingPressure); + sprintf(fileName,"LinRank_%g",rankingPressure); + testSelectOne(newRankingSelect, oRate, fRate, fileName); + + // Exponential ranking using the perf2Worth construct + std::cout << "rankingExponent " << rankingExponent << std::endl; + eoRankingSelect expRankingSelect(rankingPressure,rankingExponent); + sprintf(fileName,"ExpRank_%g_%g",rankingPressure, rankingExponent); + testSelectOne(expRankingSelect, oRate, fRate, fileName); + + // Det tournament + eoDetTournamentSelect detTourSelect(tSize); + sprintf(fileName,"DetTour_%d",tSize); + testSelectOne(detTourSelect, oRate, fRate, fileName); + + // Stoch tournament + eoStochTournamentSelect stochTourSelect(tRate); + sprintf(fileName,"StochTour_%g",tRate); + testSelectOne(stochTourSelect, oRate, fRate, fileName); + + // Fitness scaling + eoFitnessScalingSelect newFitScaleSelect(rankingPressure); + sprintf(fileName,"LinFitScale_%g",rankingPressure); + testSelectOne(newFitScaleSelect, oRate, fRate, fileName); + + // Sequential selections + eoSequentialSelect seqSel(false); + strcpy(fileName,"Sequential"); + testSelectOne(seqSel, oRate, fRate, fileName); + + eoEliteSequentialSelect eliteSeqSel; + strcpy(fileName,"EliteSequential"); + testSelectOne(eliteSeqSel, oRate, fRate, fileName); + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << std::endl; + return 1; + } +} diff --git a/deprecated/eo/test/t-eoSharing.cpp b/deprecated/eo/test/t-eoSharing.cpp new file mode 100644 index 000000000..86721b098 --- /dev/null +++ b/deprecated/eo/test/t-eoSharing.cpp @@ -0,0 +1,240 @@ +#ifdef HAVE_CONFIG_H +#include +#endif + +// to avoid long name warnings +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include +#include + +// general +#include +#include + +//----------------------------------------------------------------------------- + +struct Dummy : public EO +{ + typedef double Type; + void printOn(std::ostream & _os) const + { + EO::printOn(_os); + std::cout << " " << xdist ; + } + double xdist; +}; + +class +eoDummyDistance : public eoDistance +{ + double operator()(const Dummy & _v1, const Dummy & _v2) + { + double r= _v1.xdist - _v2.xdist; + return sqrt(r*r); + } +}; + + +bool operator==(const Dummy & _d1, const Dummy & _d2) +{ + return _d1.fitness() == _d2.fitness(); +} + +struct eoDummyPop : public eoPop +{ +public : + eoDummyPop(int s=0) { resize(s); } +}; + +// helper - DOES NOT WORK if different individuals have same fitness!!! +template +unsigned isInPop(EOT & _indi, eoPop & _pop) +{ + for (unsigned i=0; i<_pop.size(); i++) + if (_pop[i] == _indi) + return i; + return _pop.size(); +} + +unsigned int pSize; // global variable, bouh! +std::string fitnessType; // yes, a global variable :-) +eoDummyPop parentsOrg; + +template +void testSelectMany(eoSelect & _select, std::string _name) +{ + unsigned i; + std::cout << "\n\n" << fitnessType + _name << std::endl; + std::cout << "===============\n"; + + eoDummyPop parents(parentsOrg); + eoDummyPop offspring(0); + + // do the selection + _select(parents, offspring); + + // cout << "Pop offspring \n" << offspring << endl; + + // compute stats + std::vector nb(parents.size(), 0); + for (i=0; i(offspring[i], parents); + if (trouve == parents.size()) // pas trouve + throw std::runtime_error("Pas trouve ds parents"); + nb[trouve]++; + } + // dump to file so you can plot using gnuplot - dir name is hardcoded! + std::string fName = "ResSelect/" + fitnessType + _name + ".select"; + std::ofstream os(fName.c_str()); + for (i=0; i " << ( (double)nb[i])/offspring.size() << std::endl; + os << i << " " << ( (double)nb[i])/offspring.size() << std::endl; + } + +} + +template +void testSelectOne(eoSelectOne & _select, eoHowMany & _offspringRate, + eoHowMany & _fertileRate, std::string _name) +{ + eoTruncatedSelectOne truncSelect(_select, _fertileRate); + eoSelectMany percSelect(truncSelect, _offspringRate); + testSelectMany(percSelect, _name); +} + + +//----------------------------------------------------------------------------- + +int the_main(int argc, char **argv) +{ + eoParser parser(argc, argv); + + // random seed + eoValueParam& seedParam = parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); + if (seedParam.value() == 0) + seedParam.value() = time(0); + rng.reseed(seedParam.value()); + + + // pSize global variable ! + eoValueParam pSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); + pSize = pSizeParam.value(); + + eoHowMany oRate = parser.createParam(eoHowMany(1.0), "offsrpringRate", "Offsrpring rate (% or absolute)",'O').value(); + + eoHowMany fRate = parser.createParam(eoHowMany(1.0), "fertileRate", "Fertility rate (% or absolute)",'F').value(); + + + double nicheSize = parser.createParam(0.1, "nicheSize", "Paramter Sigma for Sharing",'\0').value(); + + eoParamParamType & peakParam = parser.createParam(eoParamParamType("2(1,2)"), "peaks", "Description of the peaks: N(nb1,nb2,...,nbN)", 'p').value(); + + // the number of peaks: first item of the paramparam + unsigned peakNumber = atoi(peakParam.first.c_str()); + if (peakNumber < 2) + { + std::cerr << "WARNING, nb of peaks must be larger than 2, using 2" << std::endl; + peakNumber = 2; + } + + std::vector nbIndiPerPeak(peakNumber); + unsigned i, sum=0; + + // the second item is a vector containing all values + if (!peakParam.second.size()) // no other parameter : equal peaks + { + std::cerr << "WARNING, no nb of indis per peaks, using equal nbs" << std::endl; + for (i=0; i detSelect(oRate); + // testSelectMany(detSelect, "detSelect"); + + // Sharing using the perf2Worth construct + // need a distance for that + eoDummyDistance dist; + eoSharingSelect newSharingSelect(nicheSize, dist); + sprintf(fileName,"Niche_%g",nicheSize); + testSelectOne(newSharingSelect, oRate, fRate, fileName); + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << std::endl; + return 1; + } +} diff --git a/deprecated/eo/test/t-eoShiftMutation.cpp b/deprecated/eo/test/t-eoShiftMutation.cpp new file mode 100644 index 000000000..15c4e6b92 --- /dev/null +++ b/deprecated/eo/test/t-eoShiftMutation.cpp @@ -0,0 +1,79 @@ +//----------------------------------------------------------------------------- +// t-eoShiftMutation.cpp +//----------------------------------------------------------------------------- + +#include + +#include +#include +#include + +//----------------------------------------------------------------------------- + +typedef eoInt Chrom; + +//----------------------------------------------------------------------------- + + +double real_value(const Chrom & _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + sum += _chrom[i]; + return sum/_chrom.size(); +} + +// Return true if the given chromosome corresponds to a permutation +bool check_permutation(const Chrom& _chrom){ + unsigned size= _chrom.size(); + std::set verif; + for(unsigned i=0; i< size; i++){ + if(verif.insert(_chrom[i]).second==false){ + std::cout << " Error: Wrong permutation !" << std::endl; + std::string s; + s.append( " Wrong permutation in t-eoShiftMutation"); + throw std::runtime_error( s ); + return false; + } + } + return true; +} + + +int main() +{ + const unsigned POP_SIZE = 3, CHROM_SIZE = 8; + unsigned i; + + // a chromosome randomizer + eoInitPermutation random(CHROM_SIZE); + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( real_value ); + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + 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; + shift(pop[i]); + std::cout << " ... becomes : " << pop[i] << " after shift mutation" << std::endl; + check_permutation(pop[i]); + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoStateAndParser.cpp b/deprecated/eo/test/t-eoStateAndParser.cpp new file mode 100644 index 000000000..a851cb595 --- /dev/null +++ b/deprecated/eo/test/t-eoStateAndParser.cpp @@ -0,0 +1,139 @@ +//----------------------------------------------------------------------------- + +// to avoid long name warnings +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include // runtime_error + +//----------------------------------------------------------------------------- +// tt.cpp: +// +//----------------------------------------------------------------------------- + + +// general +#include // Random number generators +#include +#include +#include + +//----------------------------------------------------------------------------- + +// include package checkpointing +#include +// and provisions for Bounds reading +#include + +struct Dummy : public EO +{ + typedef double Type; +}; + + +//----------------------------------------------------------------------------- + +int the_main(int argc, char **argv) +{ // ok, we have a command line parser and a state + + typedef eoBit Chrom; + + eoParser parser(argc, argv); + + // Define Parameters + eoValueParam dimParam((unsigned int)(5), "dimension", "dimension"); + eoValueParam rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); + eoValueParam factor(0.99, "mutationFactor", "Decrease factor for mutation rate"); + eoValueParam seed(time(0), "seed", "Random number seed"); + // test if user entered or if default value used + if (parser.isItThere(seed)) + std::cout << "YES\n"; + else + std::cout << "NO\n"; + + eoValueParam load_name("", "Load","Load",'L'); + eoValueParam save_name("", "Save","Save",'S'); + + + // Register them + parser.processParam(dimParam, "Genetic Operators"); + parser.processParam(rate, "Genetic Operators"); + parser.processParam(factor, "Genetic Operators"); + parser.processParam(load_name, "Persistence"); + parser.processParam(save_name, "Persistence"); + parser.processParam(seed, "Rng seeding"); + + // a bound param (need dim) + eoValueParam boundParam(eoRealVectorBounds(dimParam.value(),eoDummyRealNoBounds), "bounds","bounds",'b'); + + parser.processParam(boundParam, "Genetic Operators"); + + std::cout << "Bounds: " << boundParam.value() << std::endl; + + eoState state; + state.registerObject(parser); + + + if (load_name.value() != "") + { // load the parser. This is only neccessary when the user wants to + // be able to change the parameters in the state file by hand. + state.load(load_name.value()); // load the parser + } + + // Create the algorithm here + + // Register the algorithm + state.registerObject(rng); + //state.registerObject(pop); + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + return 0; + } + + // Either load or initialize + if (load_name.value() != "") + { + state.load(load_name.value()); // load the rest + } + else + { + // else + + // initialize rng and population + + rng.reseed(seed.value()); + } + + // run the algorithm + + // 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); + } + + for (int i = 0; i < 100; ++i) + rng.rand(); + + std::cout << "a random number is " << rng.random(1024) << std::endl;; + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << std::endl; + } + +} diff --git a/deprecated/eo/test/t-eoSwapMutation.cpp b/deprecated/eo/test/t-eoSwapMutation.cpp new file mode 100644 index 000000000..3099d7075 --- /dev/null +++ b/deprecated/eo/test/t-eoSwapMutation.cpp @@ -0,0 +1,81 @@ +//----------------------------------------------------------------------------- +// t-eoSwapMutation.cpp +//----------------------------------------------------------------------------- + +#include + +#include +#include +#include + +//----------------------------------------------------------------------------- + +typedef eoInt Chrom; + +//----------------------------------------------------------------------------- + + +double real_value(const Chrom & _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + sum += _chrom[i]; + return sum/_chrom.size(); +} + +//----------------------------------------------------------------------------- +// Return true if the given chromosome corresponds to a permutation +bool check_permutation(const Chrom& _chrom){ + unsigned size= _chrom.size(); + std::set verif; + for(unsigned i=0; i< size; i++){ + if(verif.insert(_chrom[i]).second==false){ + std::cout << " Error: Wrong permutation !" << std::endl; + std::string s; + s.append( " Wrong permutation in t-eoShiftMutation"); + throw std::runtime_error( s ); + return false; + } + } + return true; +} + + +int main() +{ + const unsigned POP_SIZE = 8, CHROM_SIZE = 16; + unsigned i; + + // a chromosome randomizer + eoInitPermutation random(CHROM_SIZE); + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( real_value ); + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + 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; + swap(pop[i]); + std::cout << " ... becomes : " << pop[i] << " after swap mutation" << std::endl; + check_permutation(pop[i]); + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoSymreg.cpp b/deprecated/eo/test/t-eoSymreg.cpp new file mode 100644 index 000000000..d332789ba --- /dev/null +++ b/deprecated/eo/test/t-eoSymreg.cpp @@ -0,0 +1,299 @@ +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include + +using namespace gp_parse_tree; +using namespace std; + +//----------------------------------------------------------------------------- + +class SymregNode +{ +public : + + enum Operator {X = 'x', Plus = '+', Min = '-', Mult = '*', PDiv = '/'}; + + SymregNode() { init(); } + SymregNode(Operator _op) { op = _op; } + virtual ~SymregNode() {} + + // arity function, need this function! + int arity() const { return op == X? 0 : 2; } + + 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; + } + } + + /// 'Pretty' print to ostream function + template + void operator()(string& result, Children args) const + { + 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; + } + + Operator getOp() const { return op; } + +protected : + + void init() { op = X; } + +private : + + Operator op; // the type of node +}; + +/// initializor +static SymregNode init_sequence[5] = {SymregNode::X, SymregNode::Plus, SymregNode::Min, SymregNode::Mult, SymregNode::PDiv}; // needed for intialization + +// MSVC does not recognize the lt_arity in eoParseTreeDepthInit +// without this specialization ... +// 2 months later, it seems it does not accept this definition ... +// but dies accept the lt_arity in eoParseTreeDepthInit +// !!! +// #ifdef _MSC_VER +// template <> +// bool lt_arity(const SymregNode &node1, const SymregNode &node2) +// { +// return (node1.arity() < node2.arity()); +// } +// #endif + +//----------------------------------------------------------- +// saving, loading + +std::ostream& operator<<(std::ostream& os, const SymregNode& eot) +{ + os << static_cast(eot.getOp()); + return os; +} + +std::istream& operator>>(std::istream& is, SymregNode& eot) +{ + char type; + type = (char) is.get(); + eot = SymregNode(static_cast(type)); + return is; +} + + +//----------------------------------------------------------------------------- +/** Implementation of a function evaluation object. */ + +double targetFunction(double x) +{ + return x * x * x * x - x * x * x + x * x * x - x * x + x - 10; +} + +// parameters controlling the sampling of points +const double xbegin = -10.0f; +const double xend = 10.0f; +const double xstep = 1.3f; + +template struct RMS: public eoEvalFunc< eoParseTree > +{ +public : + + typedef eoParseTree EoType; + + typedef eoParseTree argument_type; + typedef double fitness_type; + + RMS() : eoEvalFunc() + { + int n = int( (xend - xbegin) / xstep); + + inputs.resize(n); + target.resize(n); + + int i = 0; + + for (double x = xbegin; x < xend && i < n; ++i, x+=xstep) + { + target[i] = targetFunction(x); + inputs[i] = x; + } + } + + ~RMS() {} + + void operator()( EoType & _eo ) + { + vector outputs; + outputs.resize(inputs.size()); + + 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 /= (double) target.size(); + fitness = sqrt(fitness); + + if (fitness > 1e+20) + fitness = 1e+20; + + _eo.fitness(fitness); + } + +private : + vector inputs; + vector target; +}; + +template +void print_best(eoPop& pop) +{ + std::cout << std::endl; + FitnessType best = pop[0].fitness(); + int index = 0; + + for (unsigned i = 1; i < pop.size(); ++i) + { + if (best < pop[i].fitness()) + { + best = pop[i].fitness(); + index = i; + } + } + + std::cout << "\t"; + + string str; + pop[index].apply(str); + + std::cout << str.c_str(); + std::cout << std::endl << "RMS Error = " << pop[index].fitness() << std::endl; +} + +int main() +{ + typedef eoMinimizingFitness FitnessType; + typedef SymregNode GpNode; + + typedef eoParseTree EoType; + typedef eoPop Pop; + + const int MaxSize = 100; + const int nGenerations = 10; // only a test, so few generations + + // Initializor sequence, contains the allowable nodes + vector init(init_sequence, init_sequence + 5); + + // Depth Initializor, defaults to grow method. + eoGpDepthInitializer initializer(10, init); + + // Root Mean Squared Error Measure + RMS eval; + + Pop pop(50, initializer); + + apply(eval, pop); + + eoSubtreeXOver xover(MaxSize); + eoBranchMutation mutation(initializer, MaxSize); + + // The operators are encapsulated into an eoTRansform object, + // that performs sequentially crossover and mutation + eoSGATransform transform(xover, 0.75, mutation, 0.25); + + // The robust tournament selection + eoDetTournamentSelect selectOne(2); // tSize in [2,POPSIZE] + // is now encapsulated in a eoSelectMany: 2 at a time -> SteadyState + eoSelectMany select(selectOne,2, eo_is_an_integer); + + // and the Steady-State replacement + eoSSGAWorseReplacement replace; + + // Terminators + eoGenContinue term(nGenerations); + + eoCheckPoint checkPoint(term); + + eoAverageStat avg; + eoBestFitnessStat best; + eoStdoutMonitor monitor; + + checkPoint.add(monitor); + checkPoint.add(avg); + checkPoint.add(best); + + monitor.add(avg); + monitor.add(best); + + // GP generation + eoEasyEA gp(checkPoint, eval, select, transform, replace); + + std::cout << "Initialization done" << std::endl; + + print_best(pop); + + try + { + gp(pop); + } + catch (std::exception& e) + { + std::cout << "exception: " << e.what() << std::endl;; + exit(EXIT_FAILURE); + } + + print_best(pop); +} + + + +// Local Variables: +// coding: iso-8859-1 +// mode: C++ +// c-file-offsets: ((c . 0)) +// c-file-style: "Stroustrup" +// fill-column: 80 +// End: diff --git a/deprecated/eo/test/t-eoSyncEasyPSO.cpp b/deprecated/eo/test/t-eoSyncEasyPSO.cpp new file mode 100644 index 000000000..68d9838bd --- /dev/null +++ b/deprecated/eo/test/t-eoSyncEasyPSO.cpp @@ -0,0 +1,104 @@ +//----------------------------------------------------------------------------- +// t-eoEasySyncPSO.cpp +//----------------------------------------------------------------------------- + +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include + +//----------------------------------------------------------------------------- +typedef eoMinimizingFitness FitT; +typedef eoRealParticle < FitT > Particle; +//----------------------------------------------------------------------------- + +// the objective function +double real_value (const Particle & _particle) +{ + double sum = 0; + for (unsigned i = 0; i < _particle.size ()-1; i++) + sum += pow(_particle[i],2); + return (sum); +} + + +int main() +{ + const unsigned int VEC_SIZE = 2; + const unsigned int POP_SIZE = 20; + const unsigned int NEIGHBORHOOD_SIZE= 5; + unsigned i; + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( real_value ); + + // position init + eoUniformGenerator < double >uGen (-3, 3); + eoInitFixedLength < Particle > random (VEC_SIZE, uGen); + + // velocity init + eoUniformGenerator < double >sGen (-2, 2); + eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); + + // local best init + eoFirstIsBestInit < Particle > localInit; + + // 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); + + // velocity + eoStandardVelocity velocity (topology,1,1.6,2,bnds); + + // flight + eoStandardFlight flight; + + // 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; + 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; + for (i = 0; i < pop.size(); ++i) + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + } + catch (std::exception& e) + { + std::cout << "exception: " << e.what() << std::endl;; + exit(EXIT_FAILURE); + } + + + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoTwoOptMutation.cpp b/deprecated/eo/test/t-eoTwoOptMutation.cpp new file mode 100644 index 000000000..60ef89a15 --- /dev/null +++ b/deprecated/eo/test/t-eoTwoOptMutation.cpp @@ -0,0 +1,80 @@ +//----------------------------------------------------------------------------- +// t-eoTwoOptMutation.cpp +//----------------------------------------------------------------------------- + +#include + +#include +#include +#include + +//----------------------------------------------------------------------------- + +typedef eoInt Chrom; + +//----------------------------------------------------------------------------- + + +double real_value(const Chrom & _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + sum += _chrom[i]; + return sum/_chrom.size(); +} + +//----------------------------------------------------------------------------- +// Return true if the given chromosome corresponds to a permutation +bool check_permutation(const Chrom& _chrom){ + unsigned size= _chrom.size(); + std::set verif; + for(unsigned i=0; i< size; i++){ + if(verif.insert(_chrom[i]).second==false){ + std::cout << " Error: Wrong permutation !" << std::endl; + std::string s; + s.append( " Wrong permutation in t-eoShiftMutation"); + throw std::runtime_error( s ); + return false; + } + } + return true; +} + + +int main() +{ + const unsigned POP_SIZE = 3, CHROM_SIZE = 8; + unsigned i; + + // a chromosome randomizer + eoInitPermutation random(CHROM_SIZE); + + // the population: + eoPop pop; + + // Evaluation + eoEvalFuncPtr eval( real_value ); + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + 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; + twoOpt(pop[i]); + std::cout << " ... becomes : " << pop[i] << " after twoOpt mutation" << std::endl; + check_permutation(pop[i]); + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoUniform.cpp b/deprecated/eo/test/t-eoUniform.cpp new file mode 100644 index 000000000..c4f188d48 --- /dev/null +++ b/deprecated/eo/test/t-eoUniform.cpp @@ -0,0 +1,22 @@ +//----------------------------------------------------------------------------- +// t-eouniform +//----------------------------------------------------------------------------- + +#include // std::cout +#include // ostrstream, istrstream +#include // eoBin + +//----------------------------------------------------------------------------- + +main() { + eoUniform u1(-2.5,3.5); + eoUniform u2(0.003, 0 ); + eoUniform u3( 10000U, 10000000U); + std::cout << "u1\t\tu2\t\tu3" << std::endl; + for ( unsigned i = 0; i < 100; i ++) { + std::cout << u1() << "\t" << u2() << "\t" << u3() << std::endl; + } + +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoVector.cpp b/deprecated/eo/test/t-eoVector.cpp new file mode 100644 index 000000000..768178c3f --- /dev/null +++ b/deprecated/eo/test/t-eoVector.cpp @@ -0,0 +1,74 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + t-eoVector.cpp + This program tests vector-like chromosomes + (c) GeNeura Team, 1999, 2000 + + Modified by Maarten Keijzer 2001 + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; 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 + +*/ +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include +#include // eoVector +#include +#include + +//----------------------------------------------------------------------------- + +typedef eoVector Chrom1; +typedef eoVector Chrom2; + +//----------------------------------------------------------------------------- + +int main() +{ + const unsigned SIZE = 4; + + // check if the appropriate ctor gets called + Chrom1 chrom(SIZE, 5); + + for (unsigned i = 0; i < chrom.size(); ++i) + { + assert(chrom[i] == 5); + } + + eoUniformGenerator uniform(-1,1); + eoInitFixedLength init(SIZE, uniform); + + init(chrom); + + std::cout << chrom << std::endl; + + Chrom2 chrom2(chrom); + + std::cout << chrom2 << std::endl; + +// eoInitVariableLength initvar( + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-eoVirus.cpp b/deprecated/eo/test/t-eoVirus.cpp new file mode 100644 index 000000000..8ecdf207e --- /dev/null +++ b/deprecated/eo/test/t-eoVirus.cpp @@ -0,0 +1,76 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + t-eoVirus.cpp + This program tests the the binary cromosomes and several genetic operators + (c) GeNeura Team, 1999 + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; 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 + +*/ +//----------------------------------------------------------------------------- + +#include // std::cout +#include // general EO +#include "MGE/VirusOp.h" +#include "MGE/eoVirus.h" +#include "MGE/eoInitVirus.h" +#include + +#include "binary_value.h" + +//----------------------------------------------------------------------------- + +typedef eoVirus Chrom; + +//----------------------------------------------------------------------------- + +int main() +{ + const unsigned SIZE = 8; + eoBooleanGenerator gen; + eo::rng.reseed( time( 0 ) ); + + Chrom chrom(SIZE), chrom2(SIZE); + chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); + std::cout << chrom << std::endl; + std::cout << chrom2 << std::endl; + + // Virus Mutation + VirusBitFlip vf; + unsigned i; + for ( i = 0; i < 10; i++ ) { + vf( chrom ); + std::cout << chrom << std::endl; + } + + // Chrom Mutation + std::cout << "Chrom mutation--------" << std::endl; + VirusMutation vm; + for ( i = 0; i < 10; i++ ) { + vm( chrom ); + std::cout << chrom << std::endl; + } + + // Chrom Transmision + std::cout << "Chrom transmission--------" << std::endl; + VirusTransmission vt; + vt( chrom2, chrom ); + std::cout << chrom2 << std::endl; + + return 0; + +} diff --git a/deprecated/eo/test/t-eobin.cpp b/deprecated/eo/test/t-eobin.cpp new file mode 100644 index 000000000..d857dd822 --- /dev/null +++ b/deprecated/eo/test/t-eobin.cpp @@ -0,0 +1,218 @@ +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + t-eobin.cpp + This program tests the the binary cromosomes and several genetic operators + (c) GeNeura Team, 1999 + + 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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; 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 + +*/ +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +#include // std::cout +#include + +#include // general EO +#include // bitstring representation & operators +#include +#include "binary_value.h" + +//----------------------------------------------------------------------------- + +typedef eoBit Chrom; + +//----------------------------------------------------------------------------- + +void main_function() +{ + const unsigned SIZE = 8; + unsigned i, j; + eoBooleanGenerator gen; + + Chrom chrom(SIZE), chrom2; + chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); + + std::cout << "chrom: " << chrom << std::endl; + chrom[0] = chrom[SIZE - 1] = true; chrom.fitness(binary_value(chrom)); + std::cout << "chrom: " << chrom << std::endl; + chrom[0] = chrom[SIZE - 1] = false; chrom.fitness(binary_value(chrom)); + std::cout << "chrom: " << chrom << std::endl; + chrom[0] = chrom[SIZE - 1] = true; chrom.fitness(binary_value(chrom)); + + std::cout << "chrom.className() = " << chrom.className() << std::endl; + + std::cout << "chrom: " << chrom << std::endl + << "chrom2: " << chrom2 << std::endl; + + std::ostringstream os; + os << chrom; + std::istringstream is(os.str()); + is >> chrom2; chrom.fitness(binary_value(chrom2)); + + std::cout << "\nTesting reading, writing\n"; + std::cout << "chrom: " << chrom << "\nchrom2: " << chrom2 << '\n'; + + std::fill(chrom.begin(), chrom.end(), false); + std::cout << "--------------------------------------------------" + << std::endl << "eoMonOp's aplied to .......... " << chrom << std::endl; + + eoInitFixedLength + random(chrom.size(), gen); + + random(chrom); chrom.fitness(binary_value(chrom)); + std::cout << "after eoBinRandom ............ " << chrom << std::endl; + + eoOneBitFlip bitflip; + bitflip(chrom); chrom.fitness(binary_value(chrom)); + std::cout << "after eoBitFlip .............. " << chrom << std::endl; + + eoBitMutation mutation(0.5); + mutation(chrom); chrom.fitness(binary_value(chrom)); + std::cout << "after eoBinMutation(0.5) ..... " << chrom << std::endl; + + eoBitInversion inversion; + inversion(chrom); chrom.fitness(binary_value(chrom)); + std::cout << "after eoBinInversion ......... " << chrom << std::endl; + + eoBitNext next; + next(chrom); chrom.fitness(binary_value(chrom)); + std::cout << "after eoBinNext .............. " << chrom << std::endl; + + eoBitPrev prev; + prev(chrom); chrom.fitness(binary_value(chrom)); + std::cout << "after eoBinPrev .............. " << chrom << std::endl; + + std::fill(chrom.begin(), chrom.end(), false); chrom.fitness(binary_value(chrom)); + std::fill(chrom2.begin(), chrom2.end(), true); chrom2.fitness(binary_value(chrom2)); + std::cout << "--------------------------------------------------" + << std::endl << "eoBinOp's aplied to ... " + << chrom << " " << chrom2 << std::endl; + + eo1PtBitXover xover; + std::fill(chrom.begin(), chrom.end(), false); + std::fill(chrom2.begin(), chrom2.end(), true); + xover(chrom, chrom2); + chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); + std::cout << "eoBinCrossover ........ " << chrom << " " << chrom2 << std::endl; + + for (i = 1; i < SIZE; i++) + { + eoNPtsBitXover nxover(i); + std::fill(chrom.begin(), chrom.end(), false); + std::fill(chrom2.begin(), chrom2.end(), true); + nxover(chrom, chrom2); + chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); + std::cout << "eoBinNxOver(" << i << ") ........ " + << chrom << " " << chrom2 << std::endl; + } + + for (i = 1; i < SIZE / 2; i++) + for (j = 1; j < SIZE / 2; j++) + { + eoBitGxOver gxover(i, j); + std::fill(chrom.begin(), chrom.end(), false); + std::fill(chrom2.begin(), chrom2.end(), true); + gxover(chrom, chrom2); + chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2)); + std::cout << "eoBinGxOver(" << i << ", " << j << ") ..... " + << chrom << " " << chrom2 << std::endl; + } + + // test SGA algorithm + eoGenContinue continuator1(50); + eoFitContinue continuator2(65535.f); + + eoCombinedContinue continuator(continuator1, continuator2); + + eoCheckPoint checkpoint(continuator); + + eoStdoutMonitor monitor; + + checkpoint.add(monitor); + + eoSecondMomentStats stats; + + monitor.add(stats); + checkpoint.add(stats); + + eoProportionalSelect select; + eoEvalFuncPtr eval(binary_value); + + eoSGA sga(select, xover, 0.8f, bitflip, 0.1f, eval, checkpoint); + + eoInitFixedLength init(16, gen); + eoPop pop(100, init); + + apply(eval, pop); + + sga(pop); + + pop.sort(); + + std::cout << "Population " << pop << std::endl; + + std::cout << "\nBest: " << pop[0].fitness() << '\n'; + + /* + + Commented this out, waiting for a definite decision what to do with the mOp's + + // Check multiOps + eoMultiMonOp mOp( &next ); + mOp.adOp( &bitflip ); + std::cout << "before multiMonOp............ " << chrom << std::endl; + mOp( chrom ); + std::cout << "after multiMonOp .............. " << chrom << std::endl; + + eoBinGxOver gxover(2, 4); + eoMultiBinOp mbOp( &gxover ); + mOp.adOp( &bitflip ); + std::cout << "before multiBinOp............ " << chrom << " " << chrom2 << std::endl; + mbOp( chrom, chrom2 ); + std::cout << "after multiBinOp .............. " << chrom << " " << chrom2 < +#endif + +int main() +{ +#ifdef _MSC_VER + // rng.reseed(42); + int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); + flag |= _CRTDBG_LEAK_CHECK_DF; + _CrtSetDbgFlag(flag); +// _CrtSetBreakAlloc(100); +#endif + + try + { + main_function(); + } + catch(std::exception& e) + { + std::cout << "Exception: " << e.what() << '\n'; + } + +} diff --git a/deprecated/eo/test/t-eofitness.cpp b/deprecated/eo/test/t-eofitness.cpp new file mode 100644 index 000000000..1cc55e65a --- /dev/null +++ b/deprecated/eo/test/t-eofitness.cpp @@ -0,0 +1,89 @@ +//----------------------------------------------------------------------------- +// t-eofitness.cpp +// (c) GeNeura Team 1998 +//----------------------------------------------------------------------------- + +#include // time +#include // srand, rand +#include // std::cout + +#include + +using namespace std; + +//----------------------------------------------------------------------------- + +template +int test_fitness(Fitness a, Fitness b) +{ +// srand(time(0)); + +// 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--) + { + std::cout << "------------------------------------------------------" << std::endl; + std::cout << "testing < "; + if (a < 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" < + +*/ + +//----------------------------------------------------------------------------- +// t-openmp.cpp +//----------------------------------------------------------------------------- + +#include +#include +#include + +#include +#include + +#include + +#include + +#include + +#include "real_value.h" + +//----------------------------------------------------------------------------- + +typedef eoReal< eoMinimizingFitness > EOT; + +//----------------------------------------------------------------------------- + +inline uint32_t get_rdtsc() { __asm__ ("xor %eax, %eax; cpuid; rdtsc"); } + +double variable_time_function(const std::vector&) +{ + eoRng myrng( get_rdtsc() ); + ::usleep( myrng.random( 10 ) ); + 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) +{ + eoParser 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(); + + 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(); + 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); } + + 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()) + { + parser.printHelp(std::cout); + exit(1); + } + + make_help(parser); + make_verbose(parser); + + rng.reseed( seedParam ); + + eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); + 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); + + std::ostringstream params; + 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 + { + nbtask = omp_get_num_threads(); + } + + eo::log << eo::logging << "Nb task: " << nbtask << std::endl; + + for ( size_t p = popMin; p <= popMax; p += popStep ) + { + for ( size_t d = dimMin; d <= dimMax; d += dimStep ) + { + eo::log << eo::logging << p << 'x' << d << std::endl; + + for ( size_t r = 0; r < nRun; ++r ) + { + eoInitFixedLength< EOT > init( d, gen ); + + // 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 + + if ( measureConstTime == 1 ) + { + speedupFile << std::endl; + efficiencyFile << std::endl; + dynamicityFile << std::endl; + } + + if ( measureVarTime == 1 ) + { + speedupFile_variable << std::endl; + efficiencyFile_variable << std::endl; + dynamicityFile_variable << std::endl; + } + + } // end of dimension + + } // end of population + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/test/t-openmp.py b/deprecated/eo/test/t-openmp.py new file mode 100755 index 000000000..0b0ea157b --- /dev/null +++ b/deprecated/eo/test/t-openmp.py @@ -0,0 +1,161 @@ +#!/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 + +LEVELS = {'debug': logging.DEBUG, + 'info': logging.INFO, + 'warning': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL} + +LOG_DEFAULT_FILENAME='notitle.log' + +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='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('-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', 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('-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() + + 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() + +if not options.onlyexecute: + import pylab + +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 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, + 0 if options.onlyVarTime else 1, + 0 if options.onlyConstTime else 1) + logging.info( cmd ) + if not options.onlyprint: + os.system( cmd ) + + if not options.onlyexecute: + 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'] ) + +def main(): + 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)) + + 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 + + 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 ) + + 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 ) + + 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 ) + + 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 ) + + 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__': + logging.debug('### plotting started ###') + + main() + + logging.debug('### plotting ended ###') diff --git a/deprecated/eo/test/t-selectOne.cpp b/deprecated/eo/test/t-selectOne.cpp new file mode 100644 index 000000000..0647d5d23 --- /dev/null +++ b/deprecated/eo/test/t-selectOne.cpp @@ -0,0 +1,88 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// t-selectOne.cpp +// This program test the breeder object +// (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 + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + +*/ +//----------------------------------------------------------------------------- + +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + +#include // eoBin, eoPop, eoBreeder +#include +#include + +#include +#include +#include + + +//----------------------------------------------------------------------------- + +typedef eoBin Chrom; + +#include "binary_value.h" + +//----------------------------------------------------------------------------- + +main() +{ + const unsigned POP_SIZE = 8, CHROM_SIZE = 4; + unsigned i; + + eoBinRandom random; + eoPop pop; + + // Create the population + for (i = 0; i < POP_SIZE; ++i) { + Chrom chrom(CHROM_SIZE); + random(chrom); + BinaryValue()(chrom); + pop.push_back(chrom); + } + + // print population + std::cout << "population:" << std::endl; + for (i = 0; i < pop.size(); ++i) + std::cout << pop[i] << " " << pop[i].fitness() << std::endl; + + // Declare 1-selectors + eoUniformSelect uSelect; + + Chrom aChrom; + aChrom = uSelect( pop ); + std::cout << "Uniform Select " << aChrom << " " << aChrom.fitness() << std::endl; + + eoStochTournament sSelect(0.7); + aChrom = sSelect( pop ); + std::cout << "Stochastic Tournament " << aChrom << " " << aChrom.fitness() << std::endl; + + eoDetTournament dSelect(3); + aChrom = dSelect( pop ); + std::cout << "Deterministic Tournament " << aChrom << " " << aChrom.fitness() << std::endl; + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/tutorial/CMakeLists.txt b/deprecated/eo/tutorial/CMakeLists.txt new file mode 100644 index 000000000..6462b5a58 --- /dev/null +++ b/deprecated/eo/tutorial/CMakeLists.txt @@ -0,0 +1,16 @@ +###################################################################################### +### 1) Where must cmake go now ? +###################################################################################### + +IF(ENABLE_EO_TUTORIAL) + + ADD_SUBDIRECTORY(Lesson1) + ADD_SUBDIRECTORY(Lesson2) + ADD_SUBDIRECTORY(Lesson3) + ADD_SUBDIRECTORY(Lesson4) + ADD_SUBDIRECTORY(Lesson5) + ADD_SUBDIRECTORY(Lesson6) + +ENDIF() + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson1/CMakeLists.txt b/deprecated/eo/tutorial/Lesson1/CMakeLists.txt new file mode 100644 index 000000000..bcad406f5 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson1/CMakeLists.txt @@ -0,0 +1,64 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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_DEPENDENCIES(FirstBitGA ga eo eoutils) +ADD_DEPENDENCIES(FirstRealGA ga eo eoutils) +ADD_DEPENDENCIES(exercise1.3 ga eo eoutils) + +###################################################################################### +### 4) Optionnal +###################################################################################### + +SET(FIRSTBITGA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(FirstBitGA PROPERTIES VERSION "${FIRSTBITGA_VERSION}") + +SET(FIRSTREALGA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(FirstRealGA PROPERTIES VERSION "${FIRSTREALGA_VERSION}") + +SET(EXERCICE13_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(exercise1.3 PROPERTIES VERSION "${EXERCICE13_VERSION}") + +###################################################################################### +### 5) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(FirstBitGA ga eo eoutils) +TARGET_LINK_LIBRARIES(FirstRealGA ga eo eoutils) +TARGET_LINK_LIBRARIES(exercise1.3 ga eo eoutils) + +###################################################################################### +### 6) Configure project installation paths +###################################################################################### + +INSTALL(TARGETS FirstBitGA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) +INSTALL(TARGETS FirstRealGA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) +INSTALL(TARGETS exercise1.3 RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson1/FirstBitGA.cpp b/deprecated/eo/tutorial/Lesson1/FirstBitGA.cpp new file mode 100644 index 000000000..cc187a81e --- /dev/null +++ b/deprecated/eo/tutorial/Lesson1/FirstBitGA.cpp @@ -0,0 +1,167 @@ +//----------------------------------------------------------------------------- +// FirstBitGA.cpp +//----------------------------------------------------------------------------- +//* +// An instance of a VERY simple Bitstring Genetic Algorithm +// +//----------------------------------------------------------------------------- + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include +#include + +// Use functions from namespace std +using namespace std; + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your individuals +typedef eoBit Indi; // A bitstring with fitness double + +// EVAL +//----------------------------------------------------------------------------- +// a simple fitness function that computes the number of ones of a bitstring +// @param _indi A biststring individual + +double binary_value(const Indi & _indi) +{ + double sum = 0; + for (unsigned i = 0; i < _indi.size(); i++) + sum += _indi[i]; + return sum; +} +// GENERAL +//----------------------------------------------------------------------------- +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 T_SIZE = 3; // size for tournament selection + const unsigned int VEC_SIZE = 16; // Number of bits in genotypes + const unsigned int POP_SIZE = 100; // Size of population + const unsigned int MAX_GEN = 400; // Maximum number of generation before STOP + const float CROSS_RATE = 0.8; // Crossover rate + const double P_MUT_PER_BIT = 0.01; // probability of bit-flip mutation + const float MUT_RATE = 1.0; // mutation rate + +// GENERAL + ////////////////////////// + // Random seed + ////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + eoEvalFuncPtr eval( binary_value ); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + + // declare the population + eoPop pop; + // fill it! + for (unsigned int igeno=0; igeno select(T_SIZE); // T_SIZE in [2,POP_SIZE] + +// REPLACE + // The simple GA evolution engine uses generational replacement + // so no replacement procedure is needed + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // 1-point crossover for bitstring + eo1PtBitXover xover; +// MUTATION + // standard bit-flip mutation for bitstring + eoBitMutation mutation(P_MUT_PER_BIT); + +// STOP +// CHECKPOINT + ////////////////////////////////////// + // termination condition + ///////////////////////////////////// + // stop after MAX_GEN generations + eoGenContinue continuator(MAX_GEN); + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + // standard Generational GA requires as parameters + // selection, evaluation, crossover and mutation, stopping criterion + + + eoSGA gga(select, xover, CROSS_RATE, mutation, MUT_RATE, + eval, continuator); + + // Apply algo to pop - that's it! + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + // A main that catches the exceptions + +int main(int argc, char **argv) +{ + + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson1/FirstRealGA.cpp b/deprecated/eo/tutorial/Lesson1/FirstRealGA.cpp new file mode 100644 index 000000000..074c5ae86 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson1/FirstRealGA.cpp @@ -0,0 +1,162 @@ +//----------------------------------------------------------------------------- +// FirstRealGA.cpp +//----------------------------------------------------------------------------- +//* +// An instance of a VERY simple Real-coded Genetic Algorithm +// +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include +#include + +// Use functions from namespace std +using namespace std; + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your individuals + typedef eoReal Indi; + +// EVAL +//----------------------------------------------------------------------------- +// a simple fitness function that computes the euclidian norm of a real vector +// @param _indi A real-valued individual + +double real_value(const Indi & _indi) +{ + double sum = 0; + for (unsigned i = 0; i < _indi.size(); i++) + sum += _indi[i]*_indi[i]; + return (-sum); // maximizing only +} +// GENERAL +//----------------------------------------------------------------------------- +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 VEC_SIZE = 8; // Number of object variables in genotypes + const unsigned int POP_SIZE = 20; // Size of population + const unsigned int T_SIZE = 3; // size for tournament selection + const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP + const float CROSS_RATE = 0.8; // Crossover rate + const double EPSILON = 0.01; // range for real uniform mutation + const float MUT_RATE = 0.5; // mutation rate + +// GENERAL + ////////////////////////// + // Random seed + ////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + eoEvalFuncPtr eval( real_value ); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + + // declare the population + eoPop pop; + // fill it! + for (unsigned int igeno=0; igeno select(T_SIZE); // T_SIZE in [2,POP_SIZE] + +// REPLACE + // eoSGA uses generational replacement by default + // so no replacement procedure has to be given + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // offspring(i) is a linear combination of parent(i) + eoSegmentCrossover xover; +// MUTATION + // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon] + eoUniformMutation mutation(EPSILON); + +// STOP +// CHECKPOINT + ////////////////////////////////////// + // termination condition + ///////////////////////////////////// + // stop after MAX_GEN generations + eoGenContinue continuator(MAX_GEN); + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + // standard Generational GA requires + // selection, evaluation, crossover and mutation, stopping criterion + + + eoSGA gga(select, xover, CROSS_RATE, mutation, MUT_RATE, + eval, continuator); + + // Apply algo to pop - that's it! + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson1/Makefile.simple b/deprecated/eo/tutorial/Lesson1/Makefile.simple new file mode 100644 index 000000000..cca13043b --- /dev/null +++ b/deprecated/eo/tutorial/Lesson1/Makefile.simple @@ -0,0 +1,25 @@ +# if you use this Makefile as a starting point for another application +# you might need to modify the following +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, +# 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.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp + +firstGA = FirstRealGA FirstBitGA + +ALL = $(firstGA) exercise1.3 + +lesson1 : $(firstGA) + +all : $(ALL) + +clean : + @/bin/rm $(ALL) *.o *~ diff --git a/deprecated/eo/tutorial/Lesson1/exercise1.3.cpp b/deprecated/eo/tutorial/Lesson1/exercise1.3.cpp new file mode 100644 index 000000000..89965d511 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson1/exercise1.3.cpp @@ -0,0 +1,162 @@ +#ifdef HAVE_CONFIG_H +#include +#endif + +//----------------------------------------------------------------------------- +// FirstBitGA.cpp +//----------------------------------------------------------------------------- +//* +// An instance of a VERY simple Bitstring Genetic Algorithm +// +//----------------------------------------------------------------------------- +// standard includes +#include +#include + +// the general include for eo +#include + +//----------------------------------------------------------------------------- +// Include the corresponding file +#include // bitstring representation & operators +// define your individuals +typedef eoBit Indi; // A bitstring with fitness double + +using namespace std; + +//----------------------------------------------------------------------------- +/** a simple fitness function that computes the number of ones of a bitstring + @param _indi A biststring individual +*/ + +double binary_value(const Indi & _indi) +{ + double sum = 0; + for (unsigned i = 0; i < _indi.size(); i++) + sum += _indi[i]; + return sum; +} + +//----------------------------------------------------------------------------- + +void main_function(int argc, char **argv) +{ + const unsigned int SEED = 42; // seed for random number generator + const unsigned int VEC_SIZE = 8; // Number of bits in genotypes + const unsigned int POP_SIZE = 20; // Size of population + const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP + const float CROSS_RATE = 0.8; // Crossover rate + const double P_MUT_PER_BIT = 0.01; // probability of bit-flip mutation + const float MUT_RATE = 1.0; // mutation rate + + ////////////////////////// + // Random seed + ////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + eoEvalFuncPtr eval( binary_value ); + + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + + // declare the population + eoPop pop; + // fill it! + for (unsigned int igeno=0; igeno select; + + // could also use stochastic binary tournament selection + // + // const double RATE = 0.75; + // eoStochTournamentSelect select(RATE); // RATE in ]0.5,1] + // The robust tournament selection + const unsigned int T_SIZE = 3; // size for tournament selection + eoDetTournamentSelect select(T_SIZE); // T_SIZE in [2,POP_SIZE] + + // and of course the random selection + // eoRandomSelect select; + + // The simple GA evolution engine uses generational replacement + // so no replacement procedure is needed + + ////////////////////////////////////// + // termination condition + ///////////////////////////////////// + // stop after MAX_GEN generations + eoGenContinue continuator(MAX_GEN); + + + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// + // standard bit-flip mutation for bitstring + eoBitMutation mutation(P_MUT_PER_BIT); + // 1-point mutation for bitstring + eo1PtBitXover xover; + + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + // standard Generational GA requires as parameters + // selection, evaluation, crossover and mutation, stopping criterion + + + eoSGA gga(select, xover, CROSS_RATE, mutation, MUT_RATE, + eval, continuator); + + // Apply algo to pop - that's it! + gga(pop); + + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson2/CMakeLists.txt b/deprecated/eo/tutorial/Lesson2/CMakeLists.txt new file mode 100644 index 000000000..1b7c04999 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/CMakeLists.txt @@ -0,0 +1,60 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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) + +###################################################################################### +### 4) Optionnal +###################################################################################### + +SET(FIRSTBITEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(FirstBitEA PROPERTIES VERSION "${FIRSTBITEA_VERSION}") + +SET(FIRSTREALEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(FirstRealEA PROPERTIES VERSION "${FIRSTREALEA_VERSION}") + +SET(EXERCICE23_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(exercise2.3 PROPERTIES VERSION "${EXERCICE23_VERSION}") + +###################################################################################### +### 5) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(FirstBitEA ga eo eoutils) +TARGET_LINK_LIBRARIES(FirstRealEA ga eo eoutils) +TARGET_LINK_LIBRARIES(exercise2.3 ga eo eoutils) + +###################################################################################### +### 6) Configure project installation paths +###################################################################################### + +INSTALL(TARGETS FirstBitEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) +INSTALL(TARGETS FirstRealEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) +INSTALL(TARGETS exercise2.3 RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson2/FirstBitEA.cpp b/deprecated/eo/tutorial/Lesson2/FirstBitEA.cpp new file mode 100644 index 000000000..fd508a55c --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/FirstBitEA.cpp @@ -0,0 +1,193 @@ +//----------------------------------------------------------------------------- +// FirstBitEA.cpp +//----------------------------------------------------------------------------- +//* +// Still an instance of a VERY simple Bitstring Genetic Algorithm +// (see FirstBitGA.cpp) but now with Breeder - and Combined Ops +// +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +// standard includes +#include // runtime_error +#include // cout + +// the general include for eo +#include +#include + +// Use functions from namespace std +using namespace std; + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your individuals +typedef eoBit Indi; // A bitstring with fitness double + +// EVALFUNC +//----------------------------------------------------------------------------- +// a simple fitness function that computes the number of ones of a bitstring +// Now in a separate file, and declared as binary_value(const vector &) + +#include "binary_value.h" + +// GENERAL +//----------------------------------------------------------------------------- + +void main_function(int argc, char **argv) +{ +// PARAMETRES + const unsigned int SEED = 42; // seed for random number generator + const unsigned int T_SIZE = 3; // size for tournament selection + const unsigned int VEC_SIZE = 8; // Number of bits in genotypes + const unsigned int POP_SIZE = 20; // Size of population + + const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP + const unsigned int MIN_GEN = 10; // Minimum number of generation before ... + const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent + + const double P_CROSS = 0.8; // Crossover probability + const double P_MUT = 1.0; // mutation probability + + const double P_MUT_PER_BIT = 0.01; // internal probability for bit-flip mutation + // some parameters for chosing among different operators + const double onePointRate = 0.5; // rate for 1-pt Xover + const double twoPointsRate = 0.5; // rate for 2-pt Xover + const double URate = 0.5; // rate for Uniform Xover + const double bitFlipRate = 0.5; // rate for bit-flip mutation + const double oneBitRate = 0.5; // rate for one-bit mutation + +// GENERAL + ////////////////////////// + // Random seed + ////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + // you need to give the full description of the function + eoEvalFuncPtr& > eval( binary_value ); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + + // based on boolean_generator class (see utils/eoRndGenerators.h) + eoUniformGenerator uGen; + eoInitFixedLength random(VEC_SIZE, uGen); + // Initialization of the population + eoPop pop(POP_SIZE, random); + + // and evaluate it in one loop + apply(eval, pop); // STL syntax + +// OUTPUT + // sort pop before printing it! + pop.sort(); + // Print (sorted) intial population (raw printout) + cout << "Initial Population" << endl; + cout << pop; + +// ENGINE + ///////////////////////////////////// + // selection and replacement + //////////////////////////////////// +// SELECT + // The robust tournament selection + eoDetTournamentSelect selectOne(T_SIZE); // T_SIZE in [2,POP_SIZE] + // is now encapsulated in a eoSelectPerc (entage) + eoSelectPerc select(selectOne);// by default rate==1 + +// REPLACE + // And we now have the full slection/replacement - though with + // no replacement (== generational replacement) at the moment :-) + eoGenerationalReplacement replace; + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // 1-point crossover for bitstring + eo1PtBitXover xover1; + // uniform crossover for bitstring + eoUBitXover xoverU; + // 2-pots xover + eoNPtsBitXover xover2(2); + // Combine them with relative rates + eoPropCombinedQuadOp xover(xover1, onePointRate); + xover.add(xoverU, URate); + xover.add(xover2, twoPointsRate, true); + +// MUTATION + // standard bit-flip mutation for bitstring + eoBitMutation mutationBitFlip(P_MUT_PER_BIT); + // mutate exactly 1 bit per individual + eoDetBitFlip mutationOneBit; + // Combine them with relative rates + eoPropCombinedMonOp mutation(mutationBitFlip, bitFlipRate); + mutation.add(mutationOneBit, oneBitRate, true); + + // The operators are encapsulated into an eoTRansform object + eoSGATransform transform(xover, P_CROSS, mutation, P_MUT); + +// STOP +// CHECKPOINT + ////////////////////////////////////// + // termination conditions: use more than one + ///////////////////////////////////// + // stop after MAX_GEN generations + eoGenContinue genCont(MAX_GEN); + // do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement + eoSteadyFitContinue steadyCont(MIN_GEN, STEADY_GEN); + // stop when fitness reaches a target (here VEC_SIZE) + eoFitContinue fitCont(VEC_SIZE); + // do stop when one of the above says so + eoCombinedContinue continuator(genCont); + continuator.add(steadyCont); + continuator.add(fitCont); + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + + // Easy EA requires + // selection, transformation, eval, replacement, and stopping criterion + eoEasyEA gga(continuator, eval, select, transform, replace); + + // Apply algo to pop - that's it! + cout << "\n Here we go\n\n"; + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson2/FirstRealEA.cpp b/deprecated/eo/tutorial/Lesson2/FirstRealEA.cpp new file mode 100644 index 000000000..6c259b3bf --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/FirstRealEA.cpp @@ -0,0 +1,192 @@ +//----------------------------------------------------------------------------- +// FirstRealEA.cpp +//----------------------------------------------------------------------------- +//* +// Still an instance of a VERY simple Real-coded Genetic Algorithm +// (see FirstBitGA.cpp) but now with Breeder - and Combined Ops +// +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +// standard includes +#include // runtime_error +#include // cout + +// the general include for eo +#include +#include + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your individuals +typedef eoReal Indi; + +// Use functions from namespace std +using namespace std; + +// EVALFUNC +//----------------------------------------------------------------------------- +// a simple fitness function that computes the euclidian norm of a real vector +// Now in a separate file, and declared as binary_value(const vector &) + +#include "real_value.h" + +// GENERAL +//----------------------------------------------------------------------------- + +void main_function(int argc, char **argv) +{ +// PARAMETRES + const unsigned int SEED = 42; // seed for random number generator + const unsigned int T_SIZE = 3; // size for tournament selection + const unsigned int VEC_SIZE = 8; // Number of object variables in genotypes + const unsigned int POP_SIZE = 20; // Size of population + + const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP + const unsigned int MIN_GEN = 10; // Minimum number of generation before ... + const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent + + const float P_CROSS = 0.8; // Crossover probability + 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 + // 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 + const double uniformMutRate = 0.5; // relative weight for uniform mutation + const double detMutRate = 0.5; // relative weight for det-uniform mutation + const double normalMutRate = 0.5; // relative weight for normal mutation + +// GENERAL + ////////////////////////// + // Random seed + ////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + // you need to give the full description of the function + eoEvalFuncPtr& > eval( real_value ); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + // based on a uniform generator + eoUniformGenerator uGen(-1.0, 1.0); + eoInitFixedLength random(VEC_SIZE, uGen); + // Initialization of the population + eoPop pop(POP_SIZE, random); + + // and evaluate it in one loop + apply(eval, pop); // STL syntax + +// OUTPUT + // sort pop before printing it! + pop.sort(); + // Print (sorted) intial population (raw printout) + cout << "Initial Population" << endl; + cout << pop; + +// ENGINE + ///////////////////////////////////// + // selection and replacement + //////////////////////////////////// +// SELECT + // The robust tournament selection + eoDetTournamentSelect selectOne(T_SIZE); + // is now encapsulated in a eoSelectPerc (entage) + eoSelectPerc select(selectOne);// by default rate==1 + +// REPLACE + // And we now have the full slection/replacement - though with + // no replacement (== generational replacement) at the moment :-) + eoGenerationalReplacement replace; + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // uniform chooce on segment made by the parents + eoSegmentCrossover xoverS; + // uniform choice in hypercube built by the parents + eoHypercubeCrossover xoverA; + // Combine them with relative weights + eoPropCombinedQuadOp xover(xoverS, segmentRate); + xover.add(xoverA, hypercubeRate, true); + +// MUTATION + // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon] + eoUniformMutation mutationU(EPSILON); + // k (=1) coordinates of parents are uniformly modified + eoDetUniformMutation mutationD(EPSILON); + // all coordinates of parents are normally modified (stDev SIGMA) + eoNormalMutation mutationN(SIGMA); + // Combine them with relative weights + eoPropCombinedMonOp mutation(mutationU, uniformMutRate); + mutation.add(mutationD, detMutRate); + mutation.add(mutationN, normalMutRate, true); + +// STOP +// CHECKPOINT + ////////////////////////////////////// + // termination conditions: use more than one + ///////////////////////////////////// + // stop after MAX_GEN generations + eoGenContinue genCont(MAX_GEN); + // do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement + eoSteadyFitContinue steadyCont(MIN_GEN, STEADY_GEN); + // stop when fitness reaches a target (here VEC_SIZE) + eoFitContinue fitCont(0); + // do stop when one of the above says so + eoCombinedContinue continuator(genCont); + continuator.add(steadyCont); + continuator.add(fitCont); + + // The operators are encapsulated into an eoTRansform object + eoSGATransform transform(xover, P_CROSS, mutation, P_MUT); + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + + // Easy EA requires + // selection, transformation, eval, replacement, and stopping criterion + eoEasyEA gga(continuator, eval, select, transform, replace); + + // Apply algo to pop - that's it! + cout << "\n Here we go\n\n"; + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson2/Makefile.simple b/deprecated/eo/tutorial/Lesson2/Makefile.simple new file mode 100644 index 000000000..d5cba2250 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/Makefile.simple @@ -0,0 +1,34 @@ +### This Makefile is part of the tutorial of the EO library +# 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 + +# if you use this Makefile as a starting point for another application +# you might need to modify the following +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, +# 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.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp + +firstEA = FirstRealEA FirstBitEA + +ALL = $(firstEA) exercise2.3 + +lesson2 : $(firstEA) + +all : $(ALL) + +clean : + @/bin/rm $(ALL) *.o *~ + +FirstRealEA : real_value.h + +FirstBitEA : binary_value.h diff --git a/deprecated/eo/tutorial/Lesson2/binary_value.h b/deprecated/eo/tutorial/Lesson2/binary_value.h new file mode 100644 index 000000000..66d2823ec --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/binary_value.h @@ -0,0 +1,16 @@ +#include + +//----------------------------------------------------------------------------- + +/** Just a simple function that takes binary value of a chromosome and sets + the fitnes. + @param _chrom A binary chromosome +*/ +// INIT +double binary_value(const std::vector& _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + sum += _chrom[i]; + return sum; +} diff --git a/deprecated/eo/tutorial/Lesson2/exercise2.3.cpp b/deprecated/eo/tutorial/Lesson2/exercise2.3.cpp new file mode 100644 index 000000000..c1b51aa00 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/exercise2.3.cpp @@ -0,0 +1,197 @@ +//----------------------------------------------------------------------------- +// FirstBitEA.cpp +//----------------------------------------------------------------------------- +//* +// Still an instance of a VERY simple Bitstring Genetic Algorithm +// (see FirstBitGA.cpp) but now with Breeder - and Combined Ops +// +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +// standard includes +#include // runtime_error +#include // cout + +// the general include for eo +#include + +// REPRESENTATION +//----------------------------------------------------------------------------- +// Include the corresponding file +#include // bitstring representation & operators +// define your individuals +typedef eoBit Indi; // A bitstring with fitness double + +// EVAL +//----------------------------------------------------------------------------- +// a simple fitness function that computes the number of ones of a bitstring +// Now in a separate file, and declared as binary_value(const vector &) + +#include "binary_value.h" + +// GENERAL +//----------------------------------------------------------------------------- + +using namespace std; + +void main_function(int argc, char **argv) +{ +// PARAMETRES + const unsigned int SEED = 42; // seed for random number generator + const unsigned int T_SIZE = 3; // size for tournament selection + const unsigned int VEC_SIZE = 20; // Number of bits in genotypes + const unsigned int POP_SIZE = 20; // Size of population + + const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP + const unsigned int MIN_GEN = 10; // Minimum number of generation before ... + const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent + + const double P_CROSS = 0.8; // Crossover probability + const double P_MUT = 1.0; // mutation probability + + const double P_MUT_PER_BIT = 0.01; // internal probability for bit-flip mutation + // some parameters for chosing among different operators + const double onePointRate = 0.5; // rate for 1-pt Xover + const double twoPointsRate = 0.5; // rate for 2-pt Xover + const double URate = 0.5; // rate for Uniform Xover + const double bitFlipRate = 0.5; // rate for bit-flip mutation + const double oneBitRate = 0.5; // rate for one-bit mutation + +// GENERAL + ////////////////////////// + // Random seed + ////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + // you need to give the full description of the function + eoEvalFuncPtr& > eval( binary_value ); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + + // based on boolean_generator class (see utils/rnd_generator.h) + eoUniformGenerator uGen; + eoInitFixedLength random(VEC_SIZE, uGen); + // Initialization of the population + eoPop pop(POP_SIZE, random); + + // and evaluate it in one loop + apply(eval, pop); // STL syntax + +// OUTPUT + // sort pop before printing it! + pop.sort(); + // Print (sorted) intial population (raw printout) + cout << "Initial Population" << endl; + cout << pop; + +// ENGINE + ///////////////////////////////////// + // selection and replacement + //////////////////////////////////// +// SELECT + // The robust tournament selection + eoDetTournamentSelect selectOne(T_SIZE); // T_SIZE in [2,POP_SIZE] + // solution solution solution solution solution solution solution + // modify the nb offspring / rate in the constructor. 2 ways: + // second arg treated as integer + eoSelectMany select(selectOne,2, eo_is_an_integer); + // second arg treated as a rate (default behavior) + // eoSelectMany select(selectOne,0.1); + +// REPLACE + // solution solution solution solution solution solution solution + // eoCommaReplacement keeps the best among offspring + // eoPlusReplacement keeps the best among parents + offspring + // eoCommaReplacement replace; + eoPlusReplacement replace; + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // 1-point crossover for bitstring + eo1PtBitXover xover1; + // uniform crossover for bitstring + eoUBitXover xoverU; + // 2-pots xover + eoNPtsBitXover xover2(2); + // Combine them with relative rates + eoPropCombinedQuadOp xover(xover1, onePointRate); + xover.add(xoverU, URate); + xover.add(xover2, twoPointsRate, true); + +// MUTATION + // standard bit-flip mutation for bitstring + eoBitMutation mutationBitFlip(P_MUT_PER_BIT); + // mutate exactly 1 bit per individual + eoDetBitFlip mutationOneBit; + // Combine them with relative rates + eoPropCombinedMonOp mutation(mutationBitFlip, bitFlipRate); + mutation.add(mutationOneBit, oneBitRate, true); + + // The operators are encapsulated into an eoTRansform object + eoSGATransform transform(xover, P_CROSS, mutation, P_MUT); + +// STOP +// CHECKPOINT + ////////////////////////////////////// + // termination conditions: use more than one + ///////////////////////////////////// + // stop after MAX_GEN generations + eoGenContinue genCont(MAX_GEN); + // do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement + eoSteadyFitContinue steadyCont(MIN_GEN, STEADY_GEN); + // stop when fitness reaches a target (here VEC_SIZE) + eoFitContinue fitCont(VEC_SIZE); + // do stop when one of the above says so + eoCombinedContinue continuator(genCont); + continuator.add(steadyCont); + continuator.add(fitCont); + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + + // Easy EA requires + // selection, transformation, eval, replacement, and stopping criterion + eoEasyEA gga(continuator, eval, select, transform, replace); + + // Apply algo to pop - that's it! + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson2/real_value.h b/deprecated/eo/tutorial/Lesson2/real_value.h new file mode 100644 index 000000000..866e2941a --- /dev/null +++ b/deprecated/eo/tutorial/Lesson2/real_value.h @@ -0,0 +1,17 @@ +#include +//----------------------------------------------------------------------------- +/** 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 +*/ + +// INIT +double real_value(const std::vector& _ind) +{ + double sum = 0; + for (unsigned i = 0; i < _ind.size(); i++) + { + sum += _ind[i] * _ind[i]; + } + return -sum; +} diff --git a/deprecated/eo/tutorial/Lesson3/CMakeLists.txt b/deprecated/eo/tutorial/Lesson3/CMakeLists.txt new file mode 100644 index 000000000..e999e616a --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/CMakeLists.txt @@ -0,0 +1,64 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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_DEPENDENCIES(SecondBitEA ga eoutils eo) +ADD_DEPENDENCIES(SecondRealEA ga eoutils eo) +ADD_DEPENDENCIES(exercise3.1 ga eoutils eo) + +###################################################################################### +### 4) Optionnal +###################################################################################### + +SET(SECONDBITEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(SecondBitEA PROPERTIES VERSION "${SECONDBITEA_VERSION}") + +SET(SECONDREALEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(SecondRealEA PROPERTIES VERSION "${SECONDREALEA_VERSION}") + +SET(EXERCICE31_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(exercise3.1 PROPERTIES VERSION "${EXERCICE31_VERSION}") + +###################################################################################### +### 5) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(SecondBitEA ga eoutils eo) +TARGET_LINK_LIBRARIES(SecondRealEA ga eoutils eo) +TARGET_LINK_LIBRARIES(exercise3.1 ga eoutils eo) + +###################################################################################### +### 6) Configure project installation paths +###################################################################################### + +INSTALL(TARGETS SecondBitEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) +INSTALL(TARGETS SecondRealEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) +INSTALL(TARGETS exercise3.1 RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson3/Makefile.simple b/deprecated/eo/tutorial/Lesson3/Makefile.simple new file mode 100644 index 000000000..3e63424da --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/Makefile.simple @@ -0,0 +1,33 @@ +### This Makefile is part of the tutorial of the EO library +# 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 + +# if you use this Makefile as a starting point for another application +# you might need to modify the following +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, +# 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.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp + +secondEA = SecondBitEA SecondRealEA + +ALL = $(secondEA) exercise3.1 + +lesson3 : $(secondEA) + +all : $(ALL) + +SecondBitEA : binary_value.h +SecondRealEA : real_value.h + +clean : + @/bin/rm $(ALL) *.o *.sav *.xg *.status *~ diff --git a/deprecated/eo/tutorial/Lesson3/SecondBitEA.cpp b/deprecated/eo/tutorial/Lesson3/SecondBitEA.cpp new file mode 100644 index 000000000..92e181284 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/SecondBitEA.cpp @@ -0,0 +1,348 @@ +//----------------------------------------------------------------------------- +// SecondGA.cpp +//----------------------------------------------------------------------------- +//* +// Same code than FirstBitEA as far as Evolutionary Computation is concerned +// but now you learn to enter the parameters in a more flexible way +// and to twidle the output to your preferences! +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +// standard includes +#include +#include // cout +#include // runtime_error + +// the general include for eo +#include +#include + +// Use functions from namespace std +using namespace std; + +// EVAL +#include "binary_value.h" + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your genotype and fitness types +typedef eoBit Indi; + +// the main_function: nothing changed(!), except variable initialization +void main_function(int argc, char **argv) +{ +// PARAMETRES +//----------------------------------------------------------------------------- +// instead of having all values of useful parameters as constants, read them: +// either on the command line (--option=value or -o=value) +// or in a parameter file (same syntax, order independent, +// # = usual comment character +// or in the environment (TODO) + + // First define a parser from the command-line arguments + eoParser parser(argc, argv); + + // For each parameter, define Parameter, read it through the parser, + // and assign the value to the variable + + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + parser.processParam( seedParam ); + unsigned seed = seedParam.value(); + + // description of genotype + eoValueParam vecSizeParam(8, "vecSize", "Genotype size",'V'); + parser.processParam( vecSizeParam, "Representation" ); + unsigned vecSize = vecSizeParam.value(); + + // parameters for evolution engine + eoValueParam popSizeParam(10, "popSize", "Population size",'P'); + parser.processParam( popSizeParam, "Evolution engine" ); + unsigned popSize = popSizeParam.value(); + + eoValueParam tSizeParam(10, "tSize", "Tournament size",'T'); + parser.processParam( tSizeParam, "Evolution Engine" ); + unsigned tSize = tSizeParam.value(); + + // init and stop + eoValueParam loadNameParam("", "Load","A save file to restart from",'L'); + parser.processParam( loadNameParam, "Persistence" ); + string loadName = loadNameParam.value(); + + eoValueParam maxGenParam(100, "maxGen", "Maximum number of generations",'G'); + parser.processParam( maxGenParam, "Stopping criterion" ); + unsigned maxGen = maxGenParam.value(); + + eoValueParam minGenParam(100, "minGen", "Minimum number of generations",'g'); + parser.processParam( minGenParam, "Stopping criterion" ); + unsigned minGen = minGenParam.value(); + + eoValueParam steadyGenParam(100, "steadyGen", "Number of generations with no improvement",'s'); + parser.processParam( steadyGenParam, "Stopping criterion" ); + unsigned steadyGen = steadyGenParam.value(); + + // operators probabilities at the algorithm level + eoValueParam pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); + parser.processParam( pCrossParam, "Genetic Operators" ); + double pCross = pCrossParam.value(); + + eoValueParam pMutParam(0.1, "pMut", "Probability of Mutation", 'M'); + parser.processParam( pMutParam, "Genetic Operators" ); + double pMut = pMutParam.value(); + + // relative rates for crossovers + eoValueParam onePointRateParam(1, "onePointRate", "Relative rate for one point crossover", '1'); + parser.processParam( onePointRateParam, "Genetic Operators" ); + double onePointRate = onePointRateParam.value(); + + eoValueParam twoPointsRateParam(1, "twoPointRate", "Relative rate for two point crossover", '2'); + parser.processParam( twoPointsRateParam, "Genetic Operators" ); + double twoPointsRate = twoPointsRateParam.value(); + + eoValueParam uRateParam(2, "uRate", "Relative rate for uniform crossover", 'U'); + parser.processParam( uRateParam, "Genetic Operators" ); + double URate = uRateParam.value(); + + // relative rates and private parameters for mutations; + eoValueParam pMutPerBitParam(0.01, "pMutPerBit", "Probability of flipping 1 bit in bit-flip mutation", 'b'); + parser.processParam( pMutPerBitParam, "Genetic Operators" ); + double pMutPerBit = pMutPerBitParam.value(); + + eoValueParam bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B'); + parser.processParam( bitFlipRateParam, "Genetic Operators" ); + double bitFlipRate = bitFlipRateParam.value(); + + eoValueParam oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); + parser.processParam( oneBitRateParam, "Genetic Operators" ); + double oneBitRate = oneBitRateParam.value(); + + // the name of the "status" file where all actual parameter values will be saved + string str_status = parser.ProgramName() + ".status"; // default value + eoValueParam statusParam(str_status.c_str(), "status","Status file",'S'); + parser.processParam( statusParam, "Persistence" ); + + // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED + // i.e. in case you need parameters somewhere else, postpone these + if (parser.userNeedsHelp()) + { + parser.printHelp(cout); + exit(1); + } + if (statusParam.value() != "") + { + ofstream os(statusParam.value().c_str()); + os << parser; // and you can use that file as parameter file + } + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object ... + eoEvalFuncPtr& > plainEval( binary_value ); + // ... to an object that counts the nb of actual evaluations + eoEvalFuncCounter eval(plainEval); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + // Either load or initialize + // create an empty pop + eoPop pop; + // create a state for reading + eoState inState; // a state for loading - WITHOUT the parser + // register the rng and the pop in the state, so they can be loaded, + // and the present run will be the exact conitnuation of the saved run + // eventually with different parameters + inState.registerObject(rng); + inState.registerObject(pop); + + if (loadName != "") + { + inState.load(loadName); // load the pop and the rng + // the fitness is read in the file: + // do only evaluate the pop if the fitness has changed + } + else + { + rng.reseed(seed); + // a Indi random initializer + // based on boolean_generator class (see utils/rnd_generator.h) + eoUniformGenerator uGen; + eoInitFixedLength random(vecSize, uGen); + + // Init pop from the randomizer: need to use the append function + pop.append(popSize, random); + // and evaluate pop (STL syntax) + apply(eval, pop); + } // end of initializatio of the population + +// OUTPUT + // sort pop for pretty printout + pop.sort(); + // Print (sorted) intial population (raw printout) + cout << "Initial Population" << endl << pop << endl; + +// ENGINE + ///////////////////////////////////// + // selection and replacement + //////////////////////////////////// +// SELECT + // The robust tournament selection + eoDetTournamentSelect selectOne(tSize); // tSize in [2,POPSIZE] + // is now encapsulated in a eoSelectPerc (stands for Percentage) + eoSelectPerc select(selectOne); + +// REPLACE + // And we now have the full slection/replacement - though with + // the same generational replacement at the moment :-) + eoGenerationalReplacement replace; + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // 1-point crossover for bitstring + eo1PtBitXover xover1; + // uniform crossover for bitstring + eoUBitXover xoverU; + // 2-pots xover + eoNPtsBitXover xover2(2); + // Combine them with relative rates + eoPropCombinedQuadOp xover(xover1, onePointRate); + xover.add(xoverU, URate); + xover.add(xover2, twoPointsRate, true); + +// MUTATION + // standard bit-flip mutation for bitstring + eoBitMutation mutationBitFlip(pMutPerBit); + // mutate exactly 1 bit per individual + eoDetBitFlip mutationOneBit; + // Combine them with relative rates + eoPropCombinedMonOp mutation(mutationBitFlip, bitFlipRate); + mutation.add(mutationOneBit, oneBitRate, true); + + // The operators are encapsulated into an eoTRansform object + eoSGATransform transform(xover, pCross, mutation, pMut); + +// STOP + ////////////////////////////////////// + // termination condition see FirstBitEA.cpp + ///////////////////////////////////// + eoGenContinue genCont(maxGen); + eoSteadyFitContinue steadyCont(minGen, steadyGen); + eoFitContinue fitCont(vecSize); + eoCombinedContinue continuator(genCont); + continuator.add(steadyCont); + continuator.add(fitCont); + + +// CHECKPOINT + // but now you want to make many different things every generation + // (e.g. statistics, plots, ...). + // the class eoCheckPoint is dedicated to just that: + + // Declare a checkpoint (from a continuator: an eoCheckPoint + // IS AN eoContinue and will be called in the loop of all algorithms) + eoCheckPoint checkpoint(continuator); + + // Create a counter parameter + eoValueParam generationCounter(0, "Gen."); + + // Create an incrementor (sub-class of eoUpdater). Note that the + // parameter's value is passed by reference, + // so every time the incrementer is updated (every generation), + // the data in generationCounter will change. + eoIncrementor increment(generationCounter.value()); + + // Add it to the checkpoint, + // so the counter is updated (here, incremented) every generation + checkpoint.add(increment); + + // now some statistics on the population: + // Best fitness in population + eoBestFitnessStat bestStat; + // Second moment stats: average and stdev + eoSecondMomentStats SecondStat; + + // Add them to the checkpoint to get them called at the appropriate time + checkpoint.add(bestStat); + checkpoint.add(SecondStat); + + // The Stdout monitor will print parameters to the screen ... + eoStdoutMonitor monitor(false); + + // 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); + monitor.add(eval); // because now eval is an eoEvalFuncCounter! + monitor.add(bestStat); + monitor.add(SecondStat); + + // A file monitor: will print parameters to ... a File, yes, you got it! + eoFileMonitor fileMonitor("stats.xg", " "); + + // the checkpoint mechanism can handle multiple monitors + checkpoint.add(fileMonitor); + + // the fileMonitor can monitor parameters, too, but you must tell it! + fileMonitor.add(generationCounter); + fileMonitor.add(bestStat); + fileMonitor.add(SecondStat); + + // Last type of item the eoCheckpoint can handle: state savers: + eoState outState; + // Register the algorithm into the state (so it has something to save!!) + outState.registerObject(parser); + outState.registerObject(pop); + outState.registerObject(rng); + + // and feed the state to state savers + // save state every 100th generation + eoCountedStateSaver stateSaver1(20, outState, "generation"); + // save state every 1 seconds + eoTimedStateSaver stateSaver2(1, outState, "time"); + + // Don't forget to add the two savers to the checkpoint + checkpoint.add(stateSaver1); + checkpoint.add(stateSaver2); + // and that's it for the (control and) output + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + + // Easy EA requires + // stopping criterion, eval, selection, transformation, replacement + eoEasyEA gga(checkpoint, eval, select, transform, replace); + + // Apply algo to pop - that's it! + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson3/SecondRealEA.cpp b/deprecated/eo/tutorial/Lesson3/SecondRealEA.cpp new file mode 100644 index 000000000..b5ca0c800 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/SecondRealEA.cpp @@ -0,0 +1,329 @@ +//----------------------------------------------------------------------------- +// SecondRealEA.cpp +//----------------------------------------------------------------------------- +//* +// Same code than FirstBitEA as far as Evolutionary Computation is concerned +// but now you learn to enter the parameters in a more flexible way +// (also slightly different than in SecondBitEA.cpp) +// and to twidle the output to your preferences (as in SecondBitEA.cpp) +// +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +// standard includes +#include +#include // cout +#include // runtime_error + +// the general include for eo +#include +#include + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your individuals +typedef eoReal Indi; + +// Use functions from namespace std +using namespace std; + +// EVALFUNC +//----------------------------------------------------------------------------- +// a simple fitness function that computes the euclidian norm of a real vector +// Now in a separate file, and declared as binary_value(const vector &) + +#include "real_value.h" + +// GENERAL +//----------------------------------------------------------------------------- + +void main_function(int argc, char **argv) +{ +// PARAMETRES +//----------------------------------------------------------------------------- +// instead of having all values of useful parameters as constants, read them: +// either on the command line (--option=value or -o=value) +// or in a parameter file (same syntax, order independent, +// # = usual comment character +// or in the environment (TODO) + + // First define a parser from the command-line arguments + eoParser parser(argc, argv); + + // For each parameter, you can in on single line + // define the parameter, read it through the parser, and assign it + + unsigned seed = parser.createParam(unsigned(time(0)), "seed", "Random number seed", 'S').value(); // will be in default section General + + // description of genotype + unsigned vecSize = parser.createParam(unsigned(8), "vecSize", "Genotype size",'V', "Representation" ).value(); + + // parameters for evolution engine + unsigned popSize = parser.createParam(unsigned(10), "popSize", "Population size",'P', "Evolution engine" ).value(); + + unsigned tSize = parser.createParam(unsigned(2), "tSize", "Tournament size",'T', "Evolution Engine" ).value(); + + // init and stop + string loadName = parser.createParam(string(""), "Load","A save file to restart from",'L', "Persistence" ).value(); + + unsigned maxGen = parser.createParam(unsigned(100), "maxGen", "Maximum number of generations",'G', "Stopping criterion" ).value(); + + unsigned minGen = parser.createParam(unsigned(100), "minGen", "Minimum number of generations",'g', "Stopping criterion" ).value(); + + unsigned steadyGen = parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion" ).value(); + + // operators probabilities at the algorithm level + double pCross = parser.createParam(double(0.6), "pCross", "Probability of Crossover", 'C', "Genetic Operators" ).value(); + + double pMut = parser.createParam(double(0.1), "pMut", "Probability of Mutation", 'M', "Genetic Operators" ).value(); + + // relative rates for crossovers + double hypercubeRate = parser.createParam(double(1), "hypercubeRate", "Relative rate for hypercube crossover", '\0', "Genetic Operators" ).value(); + + double segmentRate = parser.createParam(double(1), "segmentRate", "Relative rate for segment crossover", '\0', "Genetic Operators" ).value(); + + // internal parameters for the mutations + double EPSILON = parser.createParam(double(0.01), "EPSILON", "Width for uniform mutation", '\0', "Genetic Operators" ).value(); + + double SIGMA = parser.createParam(double(0.3), "SIGMA", "Sigma for normal mutation", '\0', "Genetic Operators" ).value(); + + // relative rates for mutations + double uniformMutRate = parser.createParam(double(1), "uniformMutRate", "Relative rate for uniform mutation", '\0', "Genetic Operators" ).value(); + + double detMutRate = parser.createParam(double(1), "detMutRate", "Relative rate for det-uniform mutation", '\0', "Genetic Operators" ).value(); + + double normalMutRate = parser.createParam(double(1), "normalMutRate", "Relative rate for normal mutation", '\0', "Genetic Operators" ).value(); + + // the name of the "status" file where all actual parameter values will be saved + string str_status = parser.ProgramName() + ".status"; // default value + string statusName = parser.createParam(str_status, "status","Status file",'S', "Persistence" ).value(); + + // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED + // i.e. in case you need parameters somewhere else, postpone these + if (parser.userNeedsHelp()) + { + parser.printHelp(cout); + exit(1); + } + if (statusName != "") + { + ofstream os(statusName.c_str()); + os << parser; // and you can use that file as parameter file + } + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object + // you need to give the full description of the function + eoEvalFuncPtr& > plainEval( real_value ); + // ... to an object that counts the nb of actual evaluations + eoEvalFuncCounter eval(plainEval); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + // Either load or initialize + // create an empty pop + eoPop pop; + // create a state for reading + eoState inState; // a state for loading - WITHOUT the parser + // register the rng and the pop in the state, so they can be loaded, + // and the present run will be the exact conitnuation of the saved run + // eventually with different parameters + inState.registerObject(rng); + inState.registerObject(pop); + + if (loadName != "") + { + inState.load(loadName); // load the pop and the rng + // the fitness is read in the file: + // do only evaluate the pop if the fitness has changed + } + else + { + rng.reseed(seed); + // a Indi random initializer + // based on boolean_generator class (see utils/rnd_generator.h) + eoUniformGenerator uGen(-1.0, 1.0); + eoInitFixedLength random(vecSize, uGen); + + // Init pop from the randomizer: need to use the append function + pop.append(popSize, random); + // and evaluate pop (STL syntax) + apply(eval, pop); + } // end of initializatio of the population + +// OUTPUT + // sort pop before printing it! + pop.sort(); + // Print (sorted) intial population (raw printout) + cout << "Initial Population" << endl; + cout << pop; + +// ENGINE + ///////////////////////////////////// + // selection and replacement + //////////////////////////////////// +// SELECT + // The robust tournament selection + eoDetTournamentSelect selectOne(tSize); + // is now encapsulated in a eoSelectPerc (entage) + eoSelectPerc select(selectOne);// by default rate==1 + +// REPLACE + // And we now have the full slection/replacement - though with + // no replacement (== generational replacement) at the moment :-) + eoGenerationalReplacement replace; + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // uniform chooce on segment made by the parents + eoSegmentCrossover xoverS; + // uniform choice in hypercube built by the parents + eoHypercubeCrossover xoverA; + // Combine them with relative weights + eoPropCombinedQuadOp xover(xoverS, segmentRate); + xover.add(xoverA, hypercubeRate, true); + +// MUTATION + // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon] + eoUniformMutation mutationU(EPSILON); + // k (=1) coordinates of parents are uniformly modified + eoDetUniformMutation mutationD(EPSILON); + // all coordinates of parents are normally modified (stDev SIGMA) + eoNormalMutation mutationN(SIGMA); + // Combine them with relative weights + eoPropCombinedMonOp mutation(mutationU, uniformMutRate); + mutation.add(mutationD, detMutRate); + mutation.add(mutationN, normalMutRate, true); + + // The operators are encapsulated into an eoTRansform object + eoSGATransform transform(xover, pCross, mutation, pMut); + +// STOP + ////////////////////////////////////// + // termination condition see FirstBitEA.cpp + ///////////////////////////////////// + eoGenContinue genCont(maxGen); + eoSteadyFitContinue steadyCont(minGen, steadyGen); + eoFitContinue fitCont(0); + eoCombinedContinue continuator(genCont); + continuator.add(steadyCont); + continuator.add(fitCont); + + +// CHECKPOINT + // but now you want to make many different things every generation + // (e.g. statistics, plots, ...). + // the class eoCheckPoint is dedicated to just that: + + // Declare a checkpoint (from a continuator: an eoCheckPoint + // IS AN eoContinue and will be called in the loop of all algorithms) + eoCheckPoint checkpoint(continuator); + + // Create a counter parameter + eoValueParam generationCounter(0, "Gen."); + + // Create an incrementor (sub-class of eoUpdater). Note that the + // parameter's value is passed by reference, + // so every time the incrementer is updated (every generation), + // the data in generationCounter will change. + eoIncrementor increment(generationCounter.value()); + + // Add it to the checkpoint, + // so the counter is updated (here, incremented) every generation + checkpoint.add(increment); + + // now some statistics on the population: + // Best fitness in population + eoBestFitnessStat bestStat; + // Second moment stats: average and stdev + eoSecondMomentStats SecondStat; + + // Add them to the checkpoint to get them called at the appropriate time + checkpoint.add(bestStat); + checkpoint.add(SecondStat); + + // The Stdout monitor will print parameters to the screen ... + eoStdoutMonitor monitor(false); + + // 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); + monitor.add(eval); // because now eval is an eoEvalFuncCounter! + monitor.add(bestStat); + monitor.add(SecondStat); + + // A file monitor: will print parameters to ... a File, yes, you got it! + eoFileMonitor fileMonitor("stats.xg", " "); + + // the checkpoint mechanism can handle multiple monitors + checkpoint.add(fileMonitor); + + // the fileMonitor can monitor parameters, too, but you must tell it! + fileMonitor.add(generationCounter); + fileMonitor.add(bestStat); + fileMonitor.add(SecondStat); + + // Last type of item the eoCheckpoint can handle: state savers: + eoState outState; + // Register the algorithm into the state (so it has something to save!!) + outState.registerObject(parser); + outState.registerObject(pop); + outState.registerObject(rng); + + // and feed the state to state savers + // save state every 100th generation + eoCountedStateSaver stateSaver1(20, outState, "generation"); + // save state every 1 seconds + eoTimedStateSaver stateSaver2(1, outState, "time"); + + // Don't forget to add the two savers to the checkpoint + checkpoint.add(stateSaver1); + checkpoint.add(stateSaver2); + // and that's it for the (control and) output + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + + // Easy EA requires + // stopping criterion, eval, selection, transformation, replacement + eoEasyEA gga(checkpoint, eval, select, transform, replace); + + // Apply algo to pop - that's it! + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson3/binary_value.h b/deprecated/eo/tutorial/Lesson3/binary_value.h new file mode 100644 index 000000000..66d2823ec --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/binary_value.h @@ -0,0 +1,16 @@ +#include + +//----------------------------------------------------------------------------- + +/** Just a simple function that takes binary value of a chromosome and sets + the fitnes. + @param _chrom A binary chromosome +*/ +// INIT +double binary_value(const std::vector& _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + sum += _chrom[i]; + return sum; +} diff --git a/deprecated/eo/tutorial/Lesson3/exercise3.1.cpp b/deprecated/eo/tutorial/Lesson3/exercise3.1.cpp new file mode 100644 index 000000000..f21e5930e --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/exercise3.1.cpp @@ -0,0 +1,404 @@ +//----------------------------------------------------------------------------- +// SecondBitGA.cpp +//----------------------------------------------------------------------------- +//* +// Same code than FirstBitEA as far as Evolutionary Computation is concerned +// but now you learn to enter the parameters in a more flexible way +// and to twidle the output to your preferences! +//----------------------------------------------------------------------------- +#ifdef HAVE_CONFIG_H +#include +#endif + +// standard includes +#include +#include // cout +#include // runtime_error + +// the general include for eo +#include + +// EVAL +#include "binary_value.h" + +// REPRESENTATION +//----------------------------------------------------------------------------- +// Include the corresponding file +#include // bitstring representation & operators +// define your genotype and fitness types +typedef eoBit Indi; + +using namespace std; + +// the main_function: nothing changed(!), except variable initialization +void main_function(int argc, char **argv) +{ +// PARAMETRES +//----------------------------------------------------------------------------- +// instead of having all values of useful parameters as constants, read them: +// either on the command line (--option=value or -o=value) +// or in a parameter file (same syntax, order independent, +// # = usual comment character +// or in the environment (TODO) + + // First define a parser from the command-line arguments + eoParser parser(argc, argv); + + // For each parameter, define Parameter, read it through the parser, + // and assign the value to the variable + + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + parser.processParam( seedParam ); + unsigned seed = seedParam.value(); + + // description of genotype + eoValueParam vecSizeParam(100, "vecSize", "Genotype size",'V'); + parser.processParam( vecSizeParam, "Representation" ); + unsigned vecSize = vecSizeParam.value(); + + // parameters for evolution engine + eoValueParam popSizeParam(100, "popSize", "Population size",'P'); + parser.processParam( popSizeParam, "Evolution engine" ); + unsigned popSize = popSizeParam.value(); + + eoValueParam tSizeParam(10, "tSize", "Tournament size",'T'); + parser.processParam( tSizeParam, "Evolution Engine" ); + unsigned tSize = tSizeParam.value(); + + // init and stop + eoValueParam loadNameParam("", "Load","A save file to restart from",'L'); + parser.processParam( loadNameParam, "Persistence" ); + string loadName = loadNameParam.value(); + + eoValueParam maxGenParam(500, "maxGen", "Maximum number of generations",'G'); + parser.processParam( maxGenParam, "Stopping criterion" ); + unsigned maxGen = maxGenParam.value(); + + eoValueParam minGenParam(500, "minGen", "Minimum number of generations",'g'); + parser.processParam( minGenParam, "Stopping criterion" ); + unsigned minGen = minGenParam.value(); + + eoValueParam steadyGenParam(100, "steadyGen", "Number of generations with no improvement",'s'); + parser.processParam( steadyGenParam, "Stopping criterion" ); + unsigned steadyGen = steadyGenParam.value(); + + // operators probabilities at the algorithm level + eoValueParam pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); + parser.processParam( pCrossParam, "Genetic Operators" ); + double pCross = pCrossParam.value(); + + eoValueParam pMutParam(0.1, "pMut", "Probability of Mutation", 'M'); + parser.processParam( pMutParam, "Genetic Operators" ); + double pMut = pMutParam.value(); + + // relative rates for crossovers + eoValueParam onePointRateParam(1, "onePointRate", "Relative rate for one point crossover", '1'); + parser.processParam( onePointRateParam, "Genetic Operators" ); + double onePointRate = onePointRateParam.value(); + + eoValueParam twoPointsRateParam(1, "twoPointRate", "Relative rate for two point crossover", '2'); + parser.processParam( twoPointsRateParam, "Genetic Operators" ); + double twoPointsRate = twoPointsRateParam.value(); + + eoValueParam uRateParam(2, "uRate", "Relative rate for uniform crossover", 'U'); + parser.processParam( uRateParam, "Genetic Operators" ); + double URate = uRateParam.value(); + + // relative rates and private parameters for mutations; + eoValueParam pMutPerBitParam(0.01, "pMutPerBit", "Probability of flipping 1 bit in bit-flip mutation", 'b'); + parser.processParam( pMutPerBitParam, "Genetic Operators" ); + double pMutPerBit = pMutPerBitParam.value(); + + eoValueParam bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B'); + parser.processParam( bitFlipRateParam, "Genetic Operators" ); + double bitFlipRate = bitFlipRateParam.value(); + + eoValueParam oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); + parser.processParam( oneBitRateParam, "Genetic Operators" ); + double oneBitRate = oneBitRateParam.value(); + + // the name of the "status" file where all actual parameter values will be saved + string str_status = parser.ProgramName() + ".status"; // default value + eoValueParam statusParam(str_status.c_str(), "status","Status file",'S'); + parser.processParam( statusParam, "Persistence" ); + + // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED + // i.e. in case you need parameters somewhere else, postpone these + if (parser.userNeedsHelp()) + { + parser.printHelp(cout); + exit(1); + } + if (statusParam.value() != "") + { + ofstream os(statusParam.value().c_str()); + os << parser; // and you can use that file as parameter file + } + +// EVAL + ///////////////////////////// + // Fitness function + //////////////////////////// + // Evaluation: from a plain C++ fn to an EvalFunc Object ... + eoEvalFuncPtr& > plainEval( binary_value ); + // ... to an object that counts the nb of actual evaluations + eoEvalFuncCounter eval(plainEval); + +// INIT + //////////////////////////////// + // Initilisation of population + //////////////////////////////// + // Either load or initialize + // create an empty pop + eoPop pop; + // create a state for reading + eoState inState; // a state for loading - WITHOUT the parser + // register the rng and the pop in the state, so they can be loaded, + // and the present run will be the exact conitnuation of the saved run + // eventually with different parameters + inState.registerObject(rng); + inState.registerObject(pop); + + if (loadName != "") + { + inState.load(loadName); // load the pop and the rng + // the fitness is read in the file: + // do only evaluate the pop if the fitness has changed + } + else + { + rng.reseed(seed); + // a Indi random initializer + // based on boolean_generator class (see utils/rnd_generator.h) + eoUniformGenerator uGen; + eoInitFixedLength random(vecSize, uGen); + + // Init pop from the randomizer: need to use the append function + pop.append(popSize, random); + // and evaluate pop (STL syntax) + apply(eval, pop); + } // end of initializatio of the population + +// OUTPUT + // sort pop for pretty printout + // pop.sort(); + // Print (sorted) intial population (raw printout) + cout << "Initial Population" << endl << pop ; + cout << "and best is " << pop.best_element() << "\n\n"; + cout << "and worse is " << pop.worse_element() << "\n\n"; +// ENGINE + ///////////////////////////////////// + // selection and replacement + //////////////////////////////////// +// SELECT + // The robust tournament selection + eoDetTournamentSelect selectOne(tSize); // tSize in [2,POPSIZE] + // is now encapsulated in a eoSelectPerc (entage) + eoSelectPerc select(selectOne);// by default rate==1 + +// REPLACE + // And we now have the full slection/replacement - though with + // generational replacement at the moment :-) + eoGenerationalReplacement replace; + // want to add (weak) elitism? easy! + // rename the eoGenerationalReplacement replace_main, + // then encapsulate it in the elitist replacement + // eoWeakElitistReplacement replace(replace_main); + +// OPERATORS + ////////////////////////////////////// + // The variation operators + ////////////////////////////////////// +// CROSSOVER + // 1-point crossover for bitstring + eo1PtBitXover xover1; + // uniform crossover for bitstring + eoUBitXover xoverU; + // 2-pots xover + eoNPtsBitXover xover2(2); + // Combine them with relative rates + eoPropCombinedQuadOp xover(xover1, onePointRate); + xover.add(xoverU, URate); + xover.add(xover2, twoPointsRate, true); + +// MUTATION + // standard bit-flip mutation for bitstring + eoBitMutation mutationBitFlip(pMutPerBit); + // mutate exactly 1 bit per individual + eoDetBitFlip mutationOneBit; + // Combine them with relative rates + eoPropCombinedMonOp mutation(mutationBitFlip, bitFlipRate); + mutation.add(mutationOneBit, oneBitRate, true); + + // The operators are encapsulated into an eoTRansform object + eoSGATransform transform(xover, pCross, mutation, pMut); + +// STOP + ////////////////////////////////////// + // termination condition see FirstBitEA.cpp + ///////////////////////////////////// + eoGenContinue genCont(maxGen); + eoSteadyFitContinue steadyCont(minGen, steadyGen); + // eoFitContinue fitCont(vecSize); // remove if minimizing :-) + eoCombinedContinue continuator(genCont); + continuator.add(steadyCont); + // continuator.add(fitCont); + // Ctrl C signal handling: don't know if that works in MSC ... +#ifndef _MSC_VER + eoCtrlCContinue ctrlC; + continuator.add(ctrlC); +#endif + +// CHECKPOINT + // but now you want to make many different things every generation + // (e.g. statistics, plots, ...). + // the class eoCheckPoint is dedicated to just that: + + // Declare a checkpoint (from a continuator: an eoCheckPoint + // IS AN eoContinue and will be called in the loop of all algorithms) + eoCheckPoint checkpoint(continuator); + + // Create a counter parameter + eoValueParam generationCounter(0, "Gen."); + + // Create an incrementor (sub-class of eoUpdater). Note that the + // parameter's value is passed by reference, + // so every time the incrementer is updated (every generation), + // the data in generationCounter will change. + eoIncrementor increment(generationCounter.value()); + + // Add it to the checkpoint, + // so the counter is updated (here, incremented) every generation + checkpoint.add(increment); + + // now some statistics on the population: + // Best fitness in population + eoBestFitnessStat bestStat; + eoAverageStat averageStat; + // Second moment stats: average and stdev + eoSecondMomentStats SecondStat; + // the Fitness Distance Correlation + // need first an object to compute the distances + eoQuadDistance dist; // Hamming distance + eoFDCStat fdcStat(dist); + + // Add them to the checkpoint to get them called at the appropriate time + checkpoint.add(bestStat); + checkpoint.add(averageStat); + checkpoint.add(SecondStat); + checkpoint.add(fdcStat); + + // The Stdout monitor will print parameters to the screen ... + eoStdoutMonitor monitor(false); + + // 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); + monitor.add(eval); // because now eval is an eoEvalFuncCounter! + monitor.add(bestStat); + monitor.add(SecondStat); + monitor.add(fdcStat); + + // test de eoPopStat and/or eoSortedPopStat. + // Dumps the whole pop every 10 gen. + // eoSortedPopStat popStat(10, "Dump of whole population"); +// eoPopStat popStat(10, "Dump of whole population"); +// checkpoint.add(popStat); +// monitor.add(popStat); + + // A file monitor: will print parameters to ... a File, yes, you got it! + eoFileMonitor fileMonitor("stats.xg", " "); + + // the checkpoint mechanism can handle monitors + checkpoint.add(fileMonitor); + + // the fileMonitor can monitor parameters, too, but you must tell it! + fileMonitor.add(generationCounter); + fileMonitor.add(bestStat); + fileMonitor.add(SecondStat); + +#ifndef _MSC_VER + // and an eoGnuplot1DMonitor will 1-print to a file, and 2- plot on screen + eoGnuplot1DMonitor gnuMonitor("best_average.xg",minimizing_fitness()); + // the checkpoint mechanism can handle multiple monitors + checkpoint.add(gnuMonitor); + // the gnuMonitor can monitor parameters, too, but you must tell it! + gnuMonitor.add(eval); + gnuMonitor.add(bestStat); + gnuMonitor.add(averageStat); + + // send a scaling command to gnuplot + gnuMonitor.gnuplotCommand("set yrange [0:500]"); + + // a specific plot monitor for FDC + // first into a file (it adds everything ti itself + eoFDCFileSnapshot fdcFileSnapshot(fdcStat); + // then to a Gnuplot monitor + eoGnuplot1DSnapshot fdcGnuplot(fdcFileSnapshot); + // and of coruse add them to the checkPoint + checkpoint.add(fdcFileSnapshot); + checkpoint.add(fdcGnuplot); + + // want to see how the fitness is spread? + eoScalarFitnessStat fitStat; + checkpoint.add(fitStat); + // a gnuplot-based monitor for snapshots: needs a dir name + // where to store the files + eoGnuplot1DSnapshot fitSnapshot("Fitnesses"); + // add any stat that is a vector to it + fitSnapshot.add(fitStat); + // and of course add it to the checkpoint + checkpoint.add(fitSnapshot); +#endif + // Last type of item the eoCheckpoint can handle: state savers: + eoState outState; + // Register the algorithm into the state (so it has something to save!!) + outState.registerObject(rng); + outState.registerObject(pop); + + // and feed the state to state savers + // save state every 100th generation + eoCountedStateSaver stateSaver1(100, outState, "generation"); + // save state every 1 seconds + eoTimedStateSaver stateSaver2(1, outState, "time"); + + // Don't forget to add the two savers to the checkpoint + checkpoint.add(stateSaver1); + checkpoint.add(stateSaver2); + // and that's it for the (control and) output + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + + // Easy EA requires + // selection, transformation, eval, replacement, and stopping criterion + eoEasyEA gga(checkpoint, eval, select, transform, replace); + + // Apply algo to pop - that's it! + gga(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL Population\n" << pop << endl; +// GENERAL +} + +// A main that catches the exceptions +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} diff --git a/deprecated/eo/tutorial/Lesson3/real_value.h b/deprecated/eo/tutorial/Lesson3/real_value.h new file mode 100644 index 000000000..525bf393f --- /dev/null +++ b/deprecated/eo/tutorial/Lesson3/real_value.h @@ -0,0 +1,17 @@ +#include +//----------------------------------------------------------------------------- +/** 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 +*/ + +// INIT +double real_value(const std::vector& _ind) +{ + double sum = 0; + for (unsigned i = 0; i < _ind.size(); i++) + { + sum += _ind[i] * _ind[i]; + } + return sum; +} diff --git a/deprecated/eo/tutorial/Lesson4/BitEA.cpp b/deprecated/eo/tutorial/Lesson4/BitEA.cpp new file mode 100644 index 000000000..97a6cc435 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/BitEA.cpp @@ -0,0 +1,95 @@ +#include + +#include +#include + +// EVAL +#include "binary_value.h" + +// GENERAL +using namespace std; + +int main(int argc, char* argv[]) +{ + + try + { +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your genotype and fitness types + typedef eoBit EOT; + +// PARAMETRES + eoParser parser(argc, argv); // for user-parameter reading + +// GENERAL + eoState state; // keeps all things allocated + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + +// EVAL + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr mainEval( binary_value ); + eoEvalFuncCounter eval(mainEval); + +// REPRESENTATION + // the genotype - through a genotype initializer + eoInit& init = make_genotype(parser, state, EOT()); + + // if you want to do sharing, you'll need a distance. + // here Hamming distance + eoHammingDistance dist; + +// OPERATORS + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + +// GENERAL + //// Now the representation-independent things + ////////////////////////////////////////////// + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + +// STOP + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); +// GENERATION + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op, &dist); + + ///// End of construction of the algorith + ///////////////////////////////////////// +// PARAMETRES + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// +// EVAL + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); +// STOP + // print it out (sort witout modifying) + cout << "Initial Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + +// GENERATION + run_ea(ga, pop); // run the ga +// STOP + // print it out (sort witout modifying) + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; +// GENERAL + } + catch(exception& e) + { + cout << e.what() << endl; + } +} diff --git a/deprecated/eo/tutorial/Lesson4/CMakeLists.txt b/deprecated/eo/tutorial/Lesson4/CMakeLists.txt new file mode 100644 index 000000000..8048bdccc --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/CMakeLists.txt @@ -0,0 +1,98 @@ +###################################################################################### +### 0) Copy the ESEA.param and RealEA.param files in the build directory for an easy use. +###################################################################################### + +EXECUTE_PROCESS( + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param + ${EO_BINARY_DIR}/tutorial/Lesson4/ESEA.param + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param + ${EO_BINARY_DIR}/tutorial/Lesson4/RealEA.param +) + +############## +# OLD_TARGETS +############## +#ADD_CUSTOM_TARGET(param DEPENDS ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param) +#ADD_CUSTOM_COMMAND( +# TARGET param +# POST_BUILD +# COMMAND ${CMAKE_COMMAND} +# ARGS -E copy_if_different +# ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param +# ${EO_BINARY_DIR}/tutorial/Lesson4) +#ADD_CUSTOM_TARGET(param DEPENDS ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param) +#ADD_CUSTOM_COMMAND( +# TARGET param +# POST_BUILD +# COMMAND ${CMAKE_COMMAND} +# ARGS -E copy_if_different +# ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param +# ${EO_BINARY_DIR}/tutorial/Lesson4) + +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/es) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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_DEPENDENCIES(BitEA es ga eo eoutils) +#ADD_DEPENDENCIES(RealEA es ga eo eoutils) +#ADD_DEPENDENCIES(ESEA es ga eo eoutils) + +###################################################################################### +### 4) Optionnal +###################################################################################### + +SET(BITEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(BitEA PROPERTIES VERSION "${BITEA_VERSION}") + +SET(REALEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(RealEA PROPERTIES VERSION "${REALEA_VERSION}") + +SET(ESEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(ESEA PROPERTIES VERSION "${ESEA_VERSION}") + +###################################################################################### +### 5) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(BitEA es ga eo eoutils) +TARGET_LINK_LIBRARIES(RealEA es ga eo eoutils) +TARGET_LINK_LIBRARIES(ESEA es ga eo eoutils) + +###################################################################################### +### 6) Configure project installation paths +###################################################################################### + +INSTALL(TARGETS BitEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) +INSTALL(TARGETS RealEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) +INSTALL(TARGETS ESEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson4/ESEA.cpp b/deprecated/eo/tutorial/Lesson4/ESEA.cpp new file mode 100644 index 000000000..6a2b51a23 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/ESEA.cpp @@ -0,0 +1,137 @@ +// Program to test several EO-ES features + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include +#include +#include +#include + +using namespace std; + +#include + +// representation specific +#include + +#include "real_value.h" // the sphere fitness + +// Now the main +/////////////// +typedef eoMinimizingFitness FitT; + +template +void runAlgorithm(EOT, eoParser& _parser, eoState& _state); + +int main_function(int argc, char *argv[]) +{ + // Create the command-line parser + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + + eoValueParam& simpleParam = parser.createParam(true, "Isotropic", "Isotropic self-adaptive mutation", 'i', "ES mutation"); + eoValueParam& stdevsParam = parser.createParam(false, "Stdev", "One self-adaptive stDev per variable", 's', "ES mutation"); + eoValueParam& corrParam = parser.createParam(false, "Correl", "Use correlated mutations", 'c', "ES mutation"); + + // Run the appropriate algorithm + if (simpleParam.value() == false) + { + cout << "Using eoReal" << endl; + runAlgorithm(eoReal(), parser, state); + } + else if (stdevsParam.value() == false) + { + cout << "Using eoEsSimple" << endl; + runAlgorithm(eoEsSimple(), parser, state); + } + else if (corrParam.value() == false) + { + cout << "Using eoEsStdev" << endl; + runAlgorithm(eoEsStdev(), parser, state); + } + else + { + cout << "Using eoEsFull" << endl; + runAlgorithm(eoEsFull(), parser, state); + } + + return 0; +} + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} + +/** The templatized main (sort of) + * quite similar to the main of other genotypes + * (e.g. t-eoReal and t-eoGA in test dir) + */ +template +void runAlgorithm(EOT, eoParser& _parser, eoState& _state) +{ + typedef typename EOT::Fitness FitT; + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + mainEval( real_value ); + eoEvalFuncCounter eval(mainEval); + + // the genotype - through a genotype initializer + eoRealInitBounded& init = make_genotype(_parser, _state, EOT()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(_parser, _state, init); + + //// Now the representation-independent things + ////////////////////////////////////////////// + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(_parser, _state, init); + apply(eval, pop); + + // stopping criteria + eoContinue & term = make_continue(_parser, _state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(_parser, _state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(_parser, _state, eval, checkpoint, op); + + ///// End of construction of the algorith + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(_parser); + + //// GO + /////// + cout << "Initial Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; +} diff --git a/deprecated/eo/tutorial/Lesson4/ESEA.param b/deprecated/eo/tutorial/Lesson4/ESEA.param new file mode 100644 index 000000000..b5dc6d016 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/ESEA.param @@ -0,0 +1,61 @@ +###### General ###### +# --help=0 # -h : Prints this message +# --stopOnUnknownParam=1 # Stop if unkown param entered +# --seed=1104133126 # -S : Random number seed + +###### ES mutation ###### +# --Isotropic=1 # -i : Isotropic self-adaptive mutation +# --Stdev=0 # -s : One self-adaptive stDev per variable +# --Correl=0 # -c : Use correlated mutations + +###### Evolution Engine ###### +--popSize=1 # -P : Population Size +--selection=Sequential # -S : Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered) +--nbOffspring=700% # -O : Nb of offspring (percentage or absolute) +--replacement=Comma # -R : Replacement: Comma, Plus or EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t) +--weakElitism=0 # -w : Old best parent replaces new worst offspring *if necessary* + +###### Genotype Initialization ###### +# --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) + +###### Output ###### +# --useEval=1 # Use nb of eval. as counter (vs nb of gen.) +# --useTime=1 # Display time (s) every generation +# --printBestStat=1 # Print Best/avg/stdev every gen. +# --printPop=0 # Print sorted pop. every gen. + +###### Output - Disk ###### +# --resDir=Res # Directory to store DISK outputs +# --eraseDir=1 # erase files in dirName if any +# --fileBestStat=0 # Output bes/avg/std to file + +###### Output - Graphical ###### +# --plotBestStat=0 # Plot Best/avg Stat +# --plotHisto=0 # Plot histogram of fitnesses + +###### Persistence ###### +# --Load= # -L : A save file to restart from +# --recomputeFitness=0 # -r : Recompute the fitness after re-loading the pop.? +# --saveFrequency=0 # Save every F generation (0 = only final state, absent = never) +# --saveTimeInterval=0 # Save every T seconds (0 or absent = never) +# --status=t-eoESAll.status # Status file + +###### Stopping criterion ###### +# --maxGen=100 # -G : Maximum number of generations () = none) +# --steadyGen=100 # -s : Number of generations with no improvement +# --minGen=0 # -g : Minimum number of generations +# --maxEval=0 # -E : Maximum number of evaluations (0 = none) +# --targetFitness=0 # -T : Stop when fitness reaches +# --CtrlC=0 # -C : Terminate current generation upon Ctrl C + +###### Variation Operators ###### +# --objectBounds=10[-inf,+inf] # -B : Bounds for variables +# --operator=SGA # -o : Description of the operator (SGA only now) +# --pCross=1 # -C : Probability of Crossover +# --pMut=1 # -M : Probability of Mutation +# --crossType=global # -C : Type of ES recombination (global or standard) +# --crossObj=discrete # -O : Recombination of object variables (discrete, intermediate or none) +# --crossStdev=intermediate # -S : Recombination of mutation strategy parameters (intermediate, discrete or none) +# --TauLoc=1 # -l : Local Tau (before normalization) diff --git a/deprecated/eo/tutorial/Lesson4/Makefile.simple b/deprecated/eo/tutorial/Lesson4/Makefile.simple new file mode 100644 index 000000000..72c02565e --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/Makefile.simple @@ -0,0 +1,33 @@ +### This Makefile is part of the tutorial of the EO library +# 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 + +# if you use this Makefile as a starting point for another application +# you might need to modify the following +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, +# 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.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c $*.cpp + +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 + +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 : + @/bin/rm $(ALL) *.o *.sav *.xg *.status *~ diff --git a/deprecated/eo/tutorial/Lesson4/RealEA.cpp b/deprecated/eo/tutorial/Lesson4/RealEA.cpp new file mode 100644 index 000000000..1775b12b7 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/RealEA.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include "real_value.h" +#include + +using namespace std; + +int main(int argc, char* argv[]) +{ + + try + { + typedef eoReal EOT; + + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + ///// FIRST, problem or representation dependent stuff + ////////////////////////////////////////////////////// + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + mainEval( real_value ); + eoEvalFuncCounter eval(mainEval); + + // the genotype - through a genotype initializer + eoRealInitBounded& init = make_genotype(parser, state, EOT()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + //// Now the representation-independent things + ////////////////////////////////////////////// + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ea = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorith + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // print it out + cout << "Initial Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + run_ea(ea, pop); // run the ea + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + } + catch(exception& e) + { + cout << e.what() << endl; + } +} diff --git a/deprecated/eo/tutorial/Lesson4/RealEA.param b/deprecated/eo/tutorial/Lesson4/RealEA.param new file mode 100644 index 000000000..d1f8cfc4e --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/RealEA.param @@ -0,0 +1,56 @@ +###### General ###### +# --help=0 # -h : Prints this message +# --stopOnUnknownParam=1 # Stop if unkown param entered +# --seed=1104133126 # -S : Random number seed + +###### Evolution Engine ###### +--popSize=10 # -P : Population Size +--selection=Sequential # -S : Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered) +--nbOffspring=700% # -O : Nb of offspring (percentage or absolute) +--replacement=Plus # -R : Replacement: Comma, Plus or EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t) +--weakElitism=0 # -w : Old best parent replaces new worst offspring *if necessary* + +###### Genotype Initialization ###### +# --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) + +###### Output ###### +# --useEval=1 # Use nb of eval. as counter (vs nb of gen.) +# --useTime=1 # Display time (s) every generation +# --printBestStat=1 # Print Best/avg/stdev every gen. +# --printPop=0 # Print sorted pop. every gen. + +###### Output - Disk ###### +# --resDir=Res # Directory to store DISK outputs +# --eraseDir=1 # erase files in dirName if any +# --fileBestStat=0 # Output bes/avg/std to file + +###### Output - Graphical ###### +# --plotBestStat=0 # Plot Best/avg Stat +# --plotHisto=0 # Plot histogram of fitnesses + +###### Persistence ###### +# --Load= # -L : A save file to restart from +# --recomputeFitness=0 # -r : Recompute the fitness after re-loading the pop.? +# --saveFrequency=0 # Save every F generation (0 = only final state, absent = never) +# --saveTimeInterval=0 # Save every T seconds (0 or absent = never) +# --status=t-eoESAll.status # Status file + +###### Stopping criterion ###### +# --maxGen=100 # -G : Maximum number of generations () = none) +# --steadyGen=100 # -s : Number of generations with no improvement +# --minGen=0 # -g : Minimum number of generations +# --maxEval=0 # -E : Maximum number of evaluations (0 = none) +# --targetFitness=0 # -T : Stop when fitness reaches +# --CtrlC=0 # -C : Terminate current generation upon Ctrl C + +###### Variation Operators ###### +# --objectBounds=10[-inf,+inf] # -B : Bounds for variables +# --operator=SGA # -o : Description of the operator (SGA only now) +# --pCross=1 # -C : Probability of Crossover +# --pMut=1 # -M : Probability of Mutation +# --crossType=global # -C : Type of ES recombination (global or standard) +# --crossObj=discrete # -O : Recombination of object variables (discrete, intermediate or none) +# --crossStdev=intermediate # -S : Recombination of mutation strategy parameters (intermediate, discrete or none) +# --TauLoc=1 # -l : Local Tau (before normalization) diff --git a/deprecated/eo/tutorial/Lesson4/binary_value.h b/deprecated/eo/tutorial/Lesson4/binary_value.h new file mode 100644 index 000000000..f8dd5891d --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/binary_value.h @@ -0,0 +1,25 @@ +#include + +//----------------------------------------------------------------------------- + +/** Just a simple function that takes binary value of a chromosome and sets + the fitnes. + @param _chrom A binary chromosome +*/ + +template double binary_value(const Chrom& _chrom) +{ + double sum = 0; + for (unsigned i = 0; i < _chrom.size(); i++) + if (_chrom[i]) + sum += _chrom[i]; + return sum; +} + +struct BinaryValue +{ + template void operator()(Chrom& _chrom) + { + _chrom.fitness(binary_value(_chrom)); + } +}; diff --git a/deprecated/eo/tutorial/Lesson4/real_value.h b/deprecated/eo/tutorial/Lesson4/real_value.h new file mode 100644 index 000000000..f8ef3e589 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson4/real_value.h @@ -0,0 +1,16 @@ +#include +//----------------------------------------------------------------------------- + + +/** Just a simple function that takes an eoEsBase and sets the fitnes + to sphere + @param _ind vector +*/ + +double real_value(const std::vector& _ind) +{ + double sum = 0; + for (unsigned i = 0; i < _ind.size(); i++) + sum += _ind[i] * _ind[i]; + return sqrt(sum); +} diff --git a/deprecated/eo/tutorial/Lesson5/CMakeLists.txt b/deprecated/eo/tutorial/Lesson5/CMakeLists.txt new file mode 100644 index 000000000..011687b8a --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/CMakeLists.txt @@ -0,0 +1,56 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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_DEPENDENCIES(OneMaxEA es ga eo eoutils) +ADD_DEPENDENCIES(OneMaxLibEA es ga eo eoutils) + +###################################################################################### +### 4) Optionnal +###################################################################################### + +SET(ONEMAXEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(OneMaxEA PROPERTIES VERSION "${ONEMAXEA_VERSION}") + +SET(ONEMAXLIBEA_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(OneMaxLibEA PROPERTIES VERSION "${ONEMAXLIBEA_VERSION}") + +###################################################################################### +### 5) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(OneMaxEA es ga eo eoutils) +TARGET_LINK_LIBRARIES(OneMaxLibEA es ga eo eoutils) + +###################################################################################### +### 6) Configure project installation paths +###################################################################################### + +INSTALL(TARGETS OneMaxEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson5 COMPONENT examples) +INSTALL(TARGETS OneMaxLibEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson5 COMPONENT examples) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson5/Makefile.simple b/deprecated/eo/tutorial/Lesson5/Makefile.simple new file mode 100644 index 000000000..ace0df586 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/Makefile.simple @@ -0,0 +1,56 @@ +### This Makefile is part of the tutorial of the EO library +# 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 + +# if you use this Makefile as a starting point for another application +# you might need to modify the following +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, +# 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.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c $*.cpp + +# local sources +COMMON_SOURCES = eoOneMax.h \ + eoOneMaxEvalFunc.h \ + eoOneMaxInit.h \ + eoOneMaxMutation.h \ + eoOneMaxQuadCrossover.h \ + make_genotype_OneMax.h \ + make_op_OneMax.h + +NO_LIB_SOURCES = OneMaxEA.cpp + +LIB_SOURCES = OneMaxLibEA.cpp make_OneMax.cpp + + +SOURCES = $(COMMON_SOURCES) OneMaxEA.cpp OneMaxLibEA.cpp make_OneMax.cpp + +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 + +OneMaxLibEA : OneMaxLibEA.o make_OneMax.o + $(CXX) -g -o $@ OneMaxLibEA.o make_OneMax.o $(DIR_EO)/utils/libeoutils.a $(DIR_EO)/libeo.a -lm + +tar : ; tar czvf OneMax.tgz *.h *.cpp Makefile + +all : $(ALL) + +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 diff --git a/deprecated/eo/tutorial/Lesson5/OneMaxEA.cpp b/deprecated/eo/tutorial/Lesson5/OneMaxEA.cpp new file mode 100644 index 000000000..14a0f4c5e --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/OneMaxEA.cpp @@ -0,0 +1,188 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +This is the template main file. +It includes all other files that have been generated by the script create.sh +so it is the only file to compile. + +In case you want to build up a separate library for your new Evolving Object, +you'll need some work - follow what's done in the src/ga dir, used in the +main file BitEA in tutorial/Lesson4 dir. +Or you can wait until we do it :-) +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoOneMax MUST derive from EO for some fitness + */ +#include "eoOneMax.h" + +/** definition of initilizqtion: + * class eoOneMaxInit MUST derive from eoInit + */ +#include "eoOneMaxInit.h" + +/** definition of evaluation: + * class eoOneMaxEvalFunc MUST derive from eoEvalFunc + * and should test for validity before doing any computation + * see tutorial/Templates/evalFunc.tmpl + */ +#include "eoOneMaxEvalFunc.h" + +// GENOTYPE eoOneMax ***MUST*** be templatized over the fitness + +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* +// START fitness type: double or eoMaximizingFitness if you are maximizing +// eoMinimizingFitness if you are minimizing +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 + +// 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" +eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) +{ + return do_make_op(_parser, _state, _init); +} + +// Use existing modules to define representation independent routines +// These are parser-based definitions of objects + +// how to initialize the population +// it IS representation independent if an eoInit is given +#include +eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +// the stopping criterion +#include +eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +// outputs (stats, population dumps, ...) +#include +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} + +// evolution engine (selection and replacement) +#include +eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +// simple call to the algo. stays there for consistency reasons +// no template for that one +#include +// the instanciating fitnesses +#include +void run_ea(eoAlgo& _ga, eoPop& _pop) +{ + do_run(_ga, _pop); +} + +// checks for help demand, and writes the status file +// and make_help; in libutils +void make_help(eoParser & _parser); + +// now use all of the above, + representation dependent things +int main(int argc, char* argv[]) +{ + + try + { + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + // The fitness + ////////////// + eoOneMaxEvalFunc plainEval/* (varType _anyVariable) */; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // the genotype - through a genotype initializer + eoInit& init = make_genotype(parser, state, Indi()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + + //// 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 + ////////////////////////////////////////////// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorithm + + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out + cout << "Initial Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + } + catch(exception& e) + { + cout << e.what() << endl; + } + return 0; +} diff --git a/deprecated/eo/tutorial/Lesson5/OneMaxLibEA.cpp b/deprecated/eo/tutorial/Lesson5/OneMaxLibEA.cpp new file mode 100644 index 000000000..febcca445 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/OneMaxLibEA.cpp @@ -0,0 +1,162 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +This is the template main file for compiling after creating a +library. +See make_OneMax.cpp file. +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoOneMax MUST derive from EO for some fitness + */ +#include "eoOneMax.h" + +/** definition of initilizqtion: + * class eoOneMaxInit MUST derive from eoInit + */ +#include "eoOneMaxInit.h" + +/** definition of evaluation: + * class eoOneMaxEvalFunc MUST derive from eoEvalFunc + * and should test for validity before doing any computation + * see tutorial/Templates/evalFunc.tmpl + */ +#include "eoOneMaxEvalFunc.h" + +// GENOTYPE eoOneMax ***MUST*** be templatized over the fitness + +// +// START fitness type: double or eoMaximizingFitness if you are maximizing +// eoMinimizingFitness if you are minimizing +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 + +// create an initializer - done here and NOT in make_OneMax.cpp +// because it is NOT representation independent +#include "make_genotype_OneMax.h" +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" +eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) +{ + return do_make_op(_parser, _state, _init); +} + +// The representation independent routines are simply declared here + +// how to initialize the population +// it IS representation independent if an eoInit is given +eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init); + +// the stopping criterion +eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval); + +// outputs (stats, population dumps, ...) +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue); + +// 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 +// no template for that one +void run_ea(eoAlgo& _ga, eoPop& _pop); + +// checks for help demand, and writes the status file +// and make_help; in libutils - just a declaration, code in libeoutils.a +void make_help(eoParser & _parser); + +// now use all of the above, + representation dependent things +// from here on, no difference with eoOneMax.cpp +int main(int argc, char* argv[]) +{ + + try + { + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + // The fitness + ////////////// + eoOneMaxEvalFunc plainEval/* (varType _anyVariable) */; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // the genotype - through a genotype initializer + eoInit& init = make_genotype(parser, state, Indi()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + + //// 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 + ////////////////////////////////////////////// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorithm + + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out + cout << "Initial Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + } + catch(exception& e) + { + cout << e.what() << endl; + } + return 0; +} diff --git a/deprecated/eo/tutorial/Lesson5/eoOneMax.h b/deprecated/eo/tutorial/Lesson5/eoOneMax.h new file mode 100644 index 000000000..e78b90505 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/eoOneMax.h @@ -0,0 +1,110 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +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 + + * Note that you MUST derive your structure from EO + * but you MAY use some other already prepared class in the hierarchy + * 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 + * a default constructor + * IO routines printOn and readFrom + * + * Note that operator<< and operator>> are defined at EO level + * using these routines + */ +template< class FitT> +class eoOneMax: public EO { +public: + /** Ctor: you MUST provide a default ctor. + * though such individuals will generally be processed + * by some eoInit object + */ + eoOneMax() + { + // START Code of default Ctor of an eoOneMax object + // END Code of default Ctor of an eoOneMax object + } + + virtual ~eoOneMax() + { + // START Code of Destructor of an eoEASEAGenome object + // END Code of Destructor of an eoEASEAGenome object + } + + virtual string className() const { return "eoOneMax"; } + + /** printing... */ + void printOn(ostream& _os) const + { + // First write the fitness + EO::printOn(_os); + _os << ' '; + // START Code of default output + + /** HINTS + * in EO we systematically write the sizes of things before the things + * so readFrom is easier to code (see below) + */ + _os << b.size() << ' ' ; + for (unsigned i=0; i::readFrom(_is); + // START Code of input + + /** HINTS + * remember the eoOneMax object will come from the default ctor + * this is why having the sizes written out is useful + */ + unsigned s; + _is >> s; + b.resize(s); + for (unsigned i=0; i> bTmp; + b[i] = bTmp; + } + // END Code of input + } + + // accessing and setting values + void setB(vector & _b) + { + b=_b; + } + const vector & B() + { + return b; + } + +private: // put all data here + // START Private data of an eoOneMax object + std::vector b; + // END Private data of an eoOneMax object +}; + +#endif diff --git a/deprecated/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h b/deprecated/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h new file mode 100644 index 000000000..e9c31d793 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/eoOneMaxEvalFunc.h @@ -0,0 +1,68 @@ +/** -*- 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 + +// include whatever general include you need +#include +#include + +// 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 +*/ +template +class eoOneMaxEvalFunc : public eoEvalFunc +{ +public: + /// Ctor - no requirement +// START eventually add or modify the anyVariable argument + eoOneMaxEvalFunc() + // eoOneMaxEvalFunc( 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 + } + + /** Actually compute the fitness + * + * @param EOT & _eo the EO object to evaluate + * it should stay templatized to be usable + * with any fitness type + */ + void operator()(EOT & _eo) + { + // test for invalid to avoid recomputing fitness of unmodified individuals + if (_eo.invalid()) + { + double fit; // to hold fitness value + // START Code of computation of fitness of the eoOneMax object + const vector & b = _eo.B(); + fit = 0; + for (unsigned i=0; i + +/** + * 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 + * atoms of an eoVector you will need an eoInit) + */ +template +class eoOneMaxInit: public eoInit { +public: + /// Ctor - no requirement +// START eventually add or modify the anyVariable argument +// eoOneMaxInit() + eoOneMaxInit( unsigned _vecSize) : vecSize(_vecSize) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoOneMaxInit object + // END Code of Ctor of an eoOneMaxInit object + } + + + /** initialize a genotype + * + * @param _genotype generally a genotype that has been default-constructed + * whatever it contains will be lost + */ + void operator()(GenotypeT & _genotype) + { + // START Code of random initialization of an eoOneMax object + vector b(vecSize); + for (unsigned i=0; i + +/** + * 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 +class eoOneMaxMutation: public eoMonOp +{ +public: + /** + * Ctor - no requirement + */ + // START eventually add or modify the anyVariable argument + 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 + } + + /// The class name. Used to display statistics + string className() const { return "eoOneMaxMutation"; } + + /** + * modifies the parent + * @param _genotype The parent genotype (will be modified) + */ + bool operator()(GenotypeT & _genotype) + { + 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 + } + +private: +// START Private data of an eoOneMaxMutation object + // varType anyVariable; // for example ... +// END Private data of an eoOneMaxMutation object +}; + +#endif diff --git a/deprecated/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h b/deprecated/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h new file mode 100644 index 000000000..b10942157 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/eoOneMaxQuadCrossover.h @@ -0,0 +1,70 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors +*/ + +/* +Template for simple quadratic crossover operators +================================================= + +Quadratic crossover operators modify the both genotypes +*/ + +#ifndef eoOneMaxQuadCrossover_H +#define eoOneMaxQuadCrossover_H + +#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 +class eoOneMaxQuadCrossover: public eoQuadOp +{ +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + 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 + } + + /// The class name. Used to display statistics + string className() const { return "eoOneMaxQuadCrossover"; } + + /** + * eoQuad crossover - modifies both parents + * @param _genotype1 The first parent + * @param _genotype2 The second parent + */ + bool operator()(GenotypeT& _genotype1, GenotypeT & _genotype2) + { + 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 + } + +private: +// START Private data of an eoOneMaxQuadCrossover object + // varType anyVariable; // for example ... +// END Private data of an eoOneMaxQuadCrossover object +}; + +#endif diff --git a/deprecated/eo/tutorial/Lesson5/make_OneMax.cpp b/deprecated/eo/tutorial/Lesson5/make_OneMax.cpp new file mode 100644 index 000000000..7c2c05ee6 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/make_OneMax.cpp @@ -0,0 +1,128 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +This is the template file that llows separate compilation of +everything that is representation independant (evolution engine and +general output) for an Evolutionary Algorithm with scalar fitness. + +It includes of course the definition of the genotype (eoOneMax.h) and +is written like the make_xxx.cpp files in dirs src/ga (for bitstrings) +and src/es (for real vectors). + +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoOneMax MUST derive from EO for some fitness + */ +#include "eoOneMax.h" + +// create an initializer: this is NOT representation-independent +// and will be done in the main file +// However, should you decide to freeze that part, you could use the +// following (and remove it from the main file, of course!!!) +//------------------------------------------------------------------ +// #include "make_genotype_OneMax.h" +// 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 +//--------------------------------------- +// #include "make_op_OneMax.h" +// eoGenOp>& make_op(eoParser& _parser, eoState& _state, eoInit>& _init) +// { +// return do_make_op(_parser, _state, _init); +// } + +// eoGenOp>& make_op(eoParser& _parser, eoState& _state, eoInit>& _init) +// { +// return do_make_op(_parser, _state, _init); +// } + +// The following modules use ***representation independent*** routines + +// how to initialize the population +// it IS representation independent if an eoInit is given +#include +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +// the stopping criterion +#include +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +// outputs (stats, population dumps, ...) +#include +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) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} + +// evolution engine (selection and replacement) +#include +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +// simple call to the algo. stays there for consistency reasons +// no template for that one +#include +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} diff --git a/deprecated/eo/tutorial/Lesson5/make_genotype_OneMax.h b/deprecated/eo/tutorial/Lesson5/make_genotype_OneMax.h new file mode 100644 index 000000000..ebbdd306e --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/make_genotype_OneMax.h @@ -0,0 +1,75 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_genotype_h +#define _make_genotype_h + +#include +#include + // also need the parser and param includes +#include +#include + + +/* + * This fuction does the create an eoInit + * + * 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 + * 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 + * 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 + * that is ***not properly initialized*** +*/ + +template +eoInit & do_make_genotype(eoParameterLoader& _parser, eoState& _state, EOT) +{ + // 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(); + + unsigned vecSize = _parser.createParam(unsigned(8), "VecSize", "Size of the bitstrings", 'v',"Representation").value(); + + // Then built the initializer - a pointer, stored in the eoState + eoInit* init = new eoOneMaxInit(vecSize); + // store in state + _state.storeFunctor(init); + // and return a reference + return *init; +} + +#endif diff --git a/deprecated/eo/tutorial/Lesson5/make_op_OneMax.h b/deprecated/eo/tutorial/Lesson5/make_op_OneMax.h new file mode 100644 index 000000000..e157720fa --- /dev/null +++ b/deprecated/eo/tutorial/Lesson5/make_op_OneMax.h @@ -0,0 +1,210 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_op_OneMax_h +#define _make_op_OneMax_h + +// the operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include + +/** definition of mutation: + * class eoOneMaxMonop MUST derive from eoMonOp + */ +#include "eoOneMaxMutation.h" + +/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2): + * class eoOneMaxBinCrossover MUST derive from eoBinOp + * OR + * class eoOneMaxQuadCrossover MUST derive from eoQuadOp + */ +// #include "eoOneMaxBinOp.h" +// OR +#include "eoOneMaxQuadCrossover.h" + + // also need the parser and state includes +#include +#include + + +/////////////////// variation operators /////////////// +// canonical (crossover + mutation) only at the moment // + +/* + * 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 + * about the genotypes, the init has it all (e.g. bounds, ...) + * Simply do + * EOT myEO; + * _init(myEO); + * and myEO is then an ACTUAL object + * + * As usual, the template is the complete EOT even though only the fitness + * is actually templatized here: the following only applies to eoOneMax +*/ + +template +eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit& _init) +{ + // this is a temporary version, while Maarten codes the full tree-structured + // general operator input + // BTW we must leave that simple version available somehow, as it is the one + // that 90% people use! + + + ///////////////////////////// + // Variation operators + //////////////////////////// + // read crossover and mutations, combine each in a proportional Op + // and create the eoGenOp that calls crossover at rate pCross + // then mutation with rate pMut + + // the crossovers + ///////////////// + + // here we can have eoQuadOp (2->2) 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 + eoQuadOp *cross = new eoOneMaxQuadCrossover /* (varType _anyVariable) */; + // store in the state + _state.storeFunctor(cross); + + // read its relative rate in the combination + double cross1Rate = _parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", '1', "Variation Operators").value(); + + // and create the combined operator with this one + eoPropCombinedQuadOp *propXover = + new eoPropCombinedQuadOp(*cross, cross1Rate); + // and of course stor it in the state + _state.storeFunctor(propXover); + + + // 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); + _state.storeFunctor(cross); + 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); + + + // the mutation: same story + //////////////// + // you can have more than one - combined in a proportional way + + // for each mutation, + // - define the mutator object + // - read its rate from the parser + // - add it to the proportional combination + + // a first mutation + eoMonOp *mut = new eoOneMaxMutation/* (varType _anyVariable) */; + _state.storeFunctor(mut); + // its relative rate in the combination + double mut1Rate = _parser.createParam(1.0, "mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value(); + // and the creation of the combined operator with this one + eoPropCombinedMonOp *propMutation = new eoPropCombinedMonOp(*mut, mut1Rate); + _state.storeFunctor(propMutation); + + // Optional: A second(and third, and ...) mutation with their rates + // of course you must create the corresponding classes + // and all ***MUST*** derive from eoMonOp + + /* Uncomment if necessary - and replicate as many time as you need + mut = new eoOneMaxSecondMutation(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); + */ + // if you want some gentle output, the last one shoudl be like + // propMutation.add(*mut, mutXXXRate, true); + + // end of crossover and mutation definitions + //////////////////////////////////////////// + +// END Modify definitions of objects by eventually add parameters +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* + +// from now on, you do not need to modify anything +// though you CAN add things to the checkpointing (see tutorial) + + // now build the eoGenOp: + // 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 + // a QuadCopy and our crossover + // with proba pMut, our mutation + + // but of course you're free to use any smart combination you could think of + // especially, if you have to use eoBinOp rather than eoQuad Op youll have + // to modify that part + + // First read the individual level parameters + eoValueParam& pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ); + // minimum check + if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) ) + throw runtime_error("Invalid pCross"); + + eoValueParam& pMutParam = _parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" ); + // minimum check + if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) ) + throw runtime_error("Invalid pMut"); + + + // the crossover - with probability pCross + eoProportionalOp * propOp = new eoProportionalOp ; + _state.storeFunctor(propOp); + eoQuadOp *ptQuad = new eoQuadCloneOp; + _state.storeFunctor(ptQuad); + propOp->add(*propXover, pCrossParam.value()); // crossover, with proba pcross + propOp->add(*ptQuad, 1-pCrossParam.value()); // nothing, with proba 1-pcross + + // now the sequential + eoSequentialOp *op = new eoSequentialOp; + _state.storeFunctor(op); + op->add(*propOp, 1.0); // always do combined crossover + op->add(*propMutation, pMutParam.value()); // then mutation, with proba pmut + + // that's it - return a reference + return *op; +} +#endif diff --git a/deprecated/eo/tutorial/Lesson6/BinaryPSO.cpp b/deprecated/eo/tutorial/Lesson6/BinaryPSO.cpp new file mode 100644 index 000000000..2e670f536 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson6/BinaryPSO.cpp @@ -0,0 +1,182 @@ +//----------------------------------------------------------------------------- +// BinaryPSO.cpp +//----------------------------------------------------------------------------- +//* +// An instance of a VERY simple Real-coded binary Particle Swarm Optimization Algorithm +// +//----------------------------------------------------------------------------- +#include +#include +#include + +#include + +// Use functions from namespace std +using namespace std; + +//----------------------------------------------------------------------------- +typedef eoMinimizingFitness FitT; +typedef eoBitParticle < FitT > Particle; +//----------------------------------------------------------------------------- + + +// EVALFUNC +//----------------------------------------------------------------------------- +// Just a simple function that takes binary value of a chromosome and sets +// the fitness +double binary_value (const Particle & _particle) +{ + double sum = 0; + for (unsigned i = 0; i < _particle.size(); i++) + sum +=_particle[i]; + return (sum); +} + + + +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=500; + const unsigned int VEC_SIZE = 10; + const unsigned int POP_SIZE = 20; + const unsigned int NEIGHBORHOOD_SIZE= 3; + + 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; + + +////////////////////////// +// RANDOM SEED +////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + + +/// SWARM + // population <=> swarm + eoPop pop; + +/// EVALUATION + // Evaluation: from a plain C++ fn to an EvalFunc Object + eoEvalFuncPtr eval( binary_value ); + + +/////////////// +/// TOPOLOGY +////////////// + // ring topology + eoRingTopology topology(NEIGHBORHOOD_SIZE); + + +///////////////////// +// INITIALIZATION +//////////////////// + // position initialization + 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); + + // first best position initialization component + eoFirstIsBestInit < Particle > localInit; + + // Create an eoInitialier that: + // - performs a first evaluation of the particles + // - initializes the velocities + // - 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; + + +/////////////// +/// VELOCITY +////////////// + // Create the bounds for the velocity not go to far away + eoRealVectorBounds bnds(VEC_SIZE,VELOCITY_MIN,VELOCITY_MAX); + + // the velocity itself that needs the topology and a few constants + eoStandardVelocity velocity (topology,INERTIA,LEARNING_FACTOR1,LEARNING_FACTOR2,bnds); + + +/////////////// +/// FLIGHT +////////////// + // Binary flight based on sigmoid function + eoSigBinaryFlight flight; + + +//////////////////////// +/// STOPPING CRITERIA +/////////////////////// + // the algo will run for MAX_GEN iterations + eoGenContinue genCont (MAX_GEN); + + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + // standard PSO requires + // stopping criteria, evaluation,velocity, flight + + eoEasyPSO pso(genCont, eval, velocity, flight); + + // Apply the algo to the swarm - that's it! + pso(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL POPULATION:" << endl; + for (unsigned i = 0; i < pop.size(); ++i) + cout << "\t best fit=" << pop[i] << endl; + +} + + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/tutorial/Lesson6/CMakeLists.txt b/deprecated/eo/tutorial/Lesson6/CMakeLists.txt new file mode 100644 index 000000000..8614165b5 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson6/CMakeLists.txt @@ -0,0 +1,51 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +ENDIF(WIN32 AND NOT CYGWIN) + +###################################################################################### +### 3) Define your targets +###################################################################################### + +ADD_EXECUTABLE(BinaryPSO BinaryPSO.cpp) +ADD_EXECUTABLE(RealPSO RealPSO.cpp) + +###################################################################################### +### 4) Optionnal +###################################################################################### + +SET(BINARYPSO_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(BinaryPSO PROPERTIES VERSION "${BINARYPSO_VERSION}") + +SET(REALPSO_VERSION ${GLOBAL_VERSION}) +SET_TARGET_PROPERTIES(RealPSO PROPERTIES VERSION "${REALPSO_VERSION}") + +###################################################################################### +### 5) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(BinaryPSO eo eoutils) +TARGET_LINK_LIBRARIES(RealPSO eo eoutils) + +###################################################################################### +### 6) Configure project installation paths +###################################################################################### + +INSTALL(TARGETS BinaryPSO RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson6 COMPONENT examples) +INSTALL(TARGETS RealPSO RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson6 COMPONENT examples) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Lesson6/Makefile.simple b/deprecated/eo/tutorial/Lesson6/Makefile.simple new file mode 100644 index 000000000..5cdc5a466 --- /dev/null +++ b/deprecated/eo/tutorial/Lesson6/Makefile.simple @@ -0,0 +1,31 @@ +### This Makefile is part of the tutorial of the EO library +# 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 + +# if you use this Makefile as a starting point for another application +# you might need to modify the following +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, +# 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.o: ; $(CXX) -DPACKAGE=\"eo\" -DVERSION=\"0.9.3\" -I. -I$(DIR_EO) -Wall -g -c -pg $*.cpp + +PSO = BinaryPSO RealPSO + +ALL = $(PSO) + +lesson6 : $(PSO) + +all : $(ALL) + +clean : + @/bin/rm $(ALL) *.o *.sav *.xg *.status *~ diff --git a/deprecated/eo/tutorial/Lesson6/RealPSO.cpp b/deprecated/eo/tutorial/Lesson6/RealPSO.cpp new file mode 100644 index 000000000..23f67100f --- /dev/null +++ b/deprecated/eo/tutorial/Lesson6/RealPSO.cpp @@ -0,0 +1,183 @@ +//----------------------------------------------------------------------------- +// RealPSO.cpp +//----------------------------------------------------------------------------- +//* +// An instance of a VERY simple Real-coded Particle Swarm Optimization Algorithm +// +//----------------------------------------------------------------------------- +#include +#include +#include + +#include + +// Use functions from namespace std +using namespace std; + +//----------------------------------------------------------------------------- +typedef eoMinimizingFitness FitT; +typedef eoRealParticle < FitT > Particle; +//----------------------------------------------------------------------------- + + +// EVALFUNC +//----------------------------------------------------------------------------- +// a simple fitness function that computes the euclidian norm of a real vector +FitT real_value (const Particle & _particle) +{ + double sum = 0; + for (unsigned i = 0; i < _particle.size(); i++) + sum += pow(_particle[i],2); + return (sqrt(sum)); +} + + + +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; + +////////////////////////// +// RANDOM SEED +////////////////////////// + //reproducible random seed: if you don't change SEED above, + // you'll aways get the same result, NOT a random run + rng.reseed(SEED); + + +/// SWARM + // population <=> swarm + eoPop pop; + +/// EVALUATION + // Evaluation: from a plain C++ fn to an EvalFunc Object + eoEvalFuncPtr eval( real_value ); + + +/////////////// +/// TOPOLOGY +////////////// + // linear topology + eoLinearTopology topology(NEIGHBORHOOD_SIZE); + + +///////////////////// +// INITIALIZATION +//////////////////// + // position initialization + 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); + + // first best position initialization component + eoFirstIsBestInit < Particle > localInit; + + // Create an eoInitialier that: + // - performs a first evaluation of the particles + // - initializes the velocities + // - 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; + + +/////////////// +/// VELOCITY +////////////// + // Create the bounds for the velocity not go to far away + eoRealVectorBounds bnds(VEC_SIZE,VELOCITY_MIN,VELOCITY_MAX); + + // the velocity itself that needs the topology and a few constants + eoStandardVelocity velocity (topology,INERTIA,LEARNING_FACTOR1,LEARNING_FACTOR2,bnds); + + +/////////////// +/// FLIGHT +////////////// + // flight + eoStandardFlight flight; + + +//////////////////////// +/// STOPPING CRITERIA +/////////////////////// + // the algo will run for MAX_GEN iterations + eoGenContinue genCont (MAX_GEN); + + +// GENERATION + ///////////////////////////////////////// + // the algorithm + //////////////////////////////////////// + // standard PSO requires + // stopping criteria, evaluation,velocity, flight + + eoEasyPSO pso(genCont, eval, velocity, flight); + + // Apply the algo to the swarm - that's it! + pso(pop); + +// OUTPUT + // Print (sorted) intial population + pop.sort(); + cout << "FINAL POPULATION:" << endl; + for (unsigned i = 0; i < pop.size(); ++i) + cout << "\t best fit=" << pop[i] << endl; + +} + + +// A main that catches the exceptions + +int main(int argc, char **argv) +{ + try + { + main_function(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} +//----------------------------------------------------------------------------- diff --git a/deprecated/eo/tutorial/Makefile.simple b/deprecated/eo/tutorial/Makefile.simple new file mode 100644 index 000000000..b82ca27fe --- /dev/null +++ b/deprecated/eo/tutorial/Makefile.simple @@ -0,0 +1,32 @@ +SUBDIRS = Lesson1 Lesson2 Lesson3 Lesson4 Lesson5 Lesson6 + +all: + for i in $(SUBDIRS); do cd $$i && $(MAKE) all; cd ..; done + +lesson1 : + cd Lesson1; make + +lesson2 : + cd Lesson2; make + +lesson3 : + cd Lesson3; make + +lesson4 : + cd Lesson4; make + +lesson5 : + cd Lesson5; make + +lesson6 : + cd Lesson6; make + +#empty dist and distdir to let top-level 'make' do its job +dist : + +distdir : + +check : + +clean: + for i in $(SUBDIRS); do cd $$i && $(MAKE) clean; cd ..; done diff --git a/deprecated/eo/tutorial/README b/deprecated/eo/tutorial/README new file mode 100644 index 000000000..e9d994100 --- /dev/null +++ b/deprecated/eo/tutorial/README @@ -0,0 +1,12 @@ +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, +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 +systems. Any help is welcome! + +Be patient ... +evoMarc diff --git a/deprecated/eo/tutorial/Templates/CMakeLists.txt.src-tmpl b/deprecated/eo/tutorial/Templates/CMakeLists.txt.src-tmpl new file mode 100755 index 000000000..ee23cd0d4 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/CMakeLists.txt.src-tmpl @@ -0,0 +1,45 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +INCLUDE_DIRECTORIES(${MyStruct_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/do) + +###################################################################################### + + + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +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) + LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +ENDIF(WIN32 AND NOT CYGWIN) + +###################################################################################### + + + +###################################################################################### +### 3) Define your targets +###################################################################################### + +ADD_EXECUTABLE(MyStructEA MyStructEA.cpp) + +###################################################################################### + + +###################################################################################### +### 4) Link the librairies for the targets +###################################################################################### + +TARGET_LINK_LIBRARIES(MyStructEA eo eoutils ga es) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Templates/CMakeLists.txt.top-tmpl b/deprecated/eo/tutorial/Templates/CMakeLists.txt.top-tmpl new file mode 100755 index 000000000..c653b6815 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/CMakeLists.txt.top-tmpl @@ -0,0 +1,40 @@ +###################################################################################### +### 1) Main project config +###################################################################################### + +# set the project name +PROJECT(MyStructEA) + +# set a language for the entire project. +ENABLE_LANGUAGE(CXX) + +##################################################################################### + + +###################################################################################### +### 2) We need to know where EO is installed +###################################################################################### + +IF(NOT EO_SOURCE_DIR) + SET( EO_SOURCE_DIR + 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) +ENDIF(NOT EO_BINARY_DIR) +###################################################################################### + + +###################################################################################### +### 3) Where must cmake go now ? +###################################################################################### + +SUBDIRS(src) + +###################################################################################### diff --git a/deprecated/eo/tutorial/Templates/ChangeLog b/deprecated/eo/tutorial/Templates/ChangeLog new file mode 100644 index 000000000..2ede582ea --- /dev/null +++ b/deprecated/eo/tutorial/Templates/ChangeLog @@ -0,0 +1,48 @@ +2007-02-22 Jochen Kpper + + * 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. + +2007-01-16 Jochen Kpper + + * README: Add instructions for bash. + +2007-01-14 Jochen Kpper + + * createEOproject.sh: Set TargetDir to /tmp/. This is a workaround + 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. + +2006-12-16 Jochen Kpper + + * Makefile.am (EXTRA_DIST): Distribute exactly the necessary files + + * 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. + + + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/deprecated/eo/tutorial/Templates/EO.tpl b/deprecated/eo/tutorial/Templates/EO.tpl new file mode 100644 index 000000000..959ad56a8 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/EO.tpl @@ -0,0 +1,938 @@ +\TEMPLATE_START// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEA.cpp +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// +// +// Main file for creating a new representation in EO +// ================================================= +// +// This main file includes all other files that have been generated by the +// script create.sh, so it is the only file to compile. +// +// In case you want to build up a separate library for your new Evolving Object, +// you'll need some work - follow what's done in the src/ga dir, used in the +// main file BitEA in tutorial/Lesson4 dir. +// Or you can wait until we do it :-) + +// Miscellany includes and declarations +#include +using namespace std; + +// eo general include +#include "eo" +// real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +unsigned *pCurrentGeneration; +unsigned *pEZ_NB_GEN; +double EZ_MUT_PROB, EZ_XOVER_PROB, EZ_REPL_PERC=0.0; +int EZ_NB_GEN, EZ_POP_SIZE; +unsigned long EZ_NB_EVALUATIONS=0L; + +inline int random(int b1=0, int b2=1){ + return rng.random(b2-b1)+b1; +} +inline double random(double b1=0, double b2=1){ + return rng.uniform(b2-b1)+b1; +} +inline float random(float b1=0, float b2=1){ + return rng.uniform(b2-b1)+b1; +} + +\ANALYSE_PARAMETERS +\INSERT_USER_DECLARATIONS +\INSERT_INITIALISATION_FUNCTION + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class EASEAGenome MUST derive from EO for some fitness + */ +#include "EASEAGenome.h" + +// GENOTYPE EASEAGenome ***MUST*** be templatized over the fitness + +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* +// START fitness type: double or eoMaximizingFitness if you are maximizing +// eoMinimizingFitness if you are minimizing +typedef \MINIMAXI MyFitT ; // type of fitness +// END fitness type +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* + +// Then define your EO objects using that fitness type +typedef EASEAGenome Indi; // ***MUST*** derive from EO + +\INSERT_USER_FUNCTIONS + +/** definition of evaluation: + * class EASEAEvalFunc MUST derive from eoEvalFunc + * and should test for validity before doing any computation + * see tutorial/Templates/evalFunc.tmpl + */ +#include "EASEAEvalFunc.h" + +/** definition of initialization: + * class EASEAGenomeInit MUST derive from eoInit + */ +#include "EASEAInit.h" + +/** include all files defining variation operator classes + */ +#include "EASEAMutation.h" +#include "EASEAQuadCrossover.h" + +// Use existing modules to define representation independent routines +// These are parser-based definitions of objects + +// how to initialize the population +// it IS representation independent if an eoInit is given +#include +eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init){ + return do_make_pop(_parser, _state, _init); +} + +// the stopping criterion +#include "make_continue.h" +eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval){ + return do_make_continue(_parser, _state, _eval); +} + +// outputs (stats, population dumps, ...) +#include +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) { + return do_make_checkpoint(_parser, _state, _eval, _continue); +} + +// evolution engine (selection and replacement) +#include +eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op){ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +// simple call to the algo. stays there for consistency reasons +// no template for that one +#include +// the instanciating fitnesses +#include +void run_ea(eoAlgo& _ga, eoPop& _pop){ + do_run(_ga, _pop); +} + +// checks for help demand, and writes the status file +// and make_help; in libutils +void make_help(eoParser & _parser); + +// now use all of the above, + representation dependent things +int main(int argc, char* argv[]){ + +try { +\INSERT_INIT_FCT_CALL + + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + // The fitness + ////////////// + EASEAEvalFunc plainEval/* (varType _anyVariable) */; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // a genotype initializer + EASEAInit init; + // or, if you need some parameters, you might as well + // - write a constructor of the eoMyStructInit that uses a parser + // - call it from here: + // eoEASEAInit init(parser); + + + // Build the variation operator (any seq/prop construct) + // here, a simple example with only 1 crossover (2->2, a QuadOp) and + // one mutation, is given. + // Hints to have choice among multiple crossovers and mutations are given + + // A (first) crossover (possibly use the parser in its Ctor) + EASEAQuadCrossover cross /* (eoParser parser) */; + + // IF MORE THAN ONE: + + // read its relative rate in the combination +// double cross1Rate = parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", '1', "Variation Operators").value(); + + // create the combined operator with the first one (rename it cross1 !!!) +// eoPropCombinedQuadOp cross(cross1, cross1Rate); + + // and as many as you want the following way: + // 1- write the new class by mimicking eoEASEAQuadCrossover.h + // 2- include that file here together with eoEASEAQuadCrossover above + // 3- uncomment and duplicate the following lines: + // +// eoEASEASecondCrossover cross2(eoParser parser); +// double cross2Rate = parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value(); +// cross.add(cross2, cross2Rate); + + // NOTE: if you want some gentle output, the last one shoudl be like + // cross.add(cross, crossXXXRate, true); + + /////////////// Same thing for MUTATION + + // a (first) mutation (possibly use the parser in its Ctor) + EASEAMutation mut /* (eoParser parser) */; + + // IF MORE THAN ONE: + + // read its relative rate in the combination +// double mut1Rate = parser.createParam(1.0, "mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value(); + + // create the combined operator with the first one (rename it cross1 !!!) +// eoPropCombinedMonOp mut(mut1, mut1Rate); + + // and as many as you want the following way: + // 1- write the new class by mimicking eoEASEAMutation.h + // 2- include that file here together with eoEASEAMutation above + // 3- uncomment and duplicate the following lines: + // +// eoEASEASecondMutation mut2(eoParser parser); +// double mut2Rate = parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); +// mut.add(mut2, mut2Rate); + + // NOTE: if you want some gentle output, the last one shoudl be like + // mut.add(mut, mutXXXRate, true); + + // now encapsulate your crossover(s) and mutation(s) into an eoGeneralOp + // so you can fully benefit of the existing evolution engines + + // First read the individual level parameters + double pCross = parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ).value(); + // minimum check + if ( (pCross < 0) || (pCross > 1) ) + throw runtime_error("Invalid pCross"); + + double pMut = parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" ).value(); + // minimum check + if ( (pMut < 0) || (pMut > 1) ) + throw runtime_error("Invalid pMut"); + + // now create the generalOp + eoSGAGenOp op(cross, pCross, mut, pMut); + + + + //// 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 + ////////////////////////////////////////////// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + // give popSize to AESAE control + EZ_POP_SIZE = pop.size(); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorithm + + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out +// cout << "Initial Population\n"; +// pop.sortedPrintOn(cout); +// cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Best individual in final population\n"; + cout << pop.best_element() << endl; + + } + catch(exception& e) + { + cout << e.what() << endl; + } + return 0; +} + +\START_EO_GENOME_H_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEAGenome.h +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// + +#ifndef _EASEAGenome_h +#define _EASEAGenome_h + +/** + * Always write a comment in this format before class definition + * if you want the class to be documented by Doxygen + + * Note that you MUST derive your structure from EO + * but you MAY use some other already prepared class in the hierarchy + * 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 + * a default constructor + * IO routines printOn and readFrom + * + * Note that operator<< and operator>> are defined at EO level + * using these routines + */ +\ANALYSE_USER_CLASSES +\INSERT_USER_CLASSES + +template< class FitT> +class EASEAGenome: public EO { +public: + /** Ctor: you MUST provide a default ctor. + * though such individuals will generally be processed + * by some eoInit object + */ + EASEAGenome() : EO() + { + // START Code of default Ctor of an EASEAGenome object +\GENOME_CTOR + // END Code of default Ctor of an EASEAGenome object + } + + EASEAGenome(const EASEAGenome & arg) : EO() + { +\GENOME_CTOR + copy(arg); + } + + virtual ~EASEAGenome() + { + // START Code of Destructor of an EASEAGenome object + \GENOME_DTOR + // END Code of Destructor of an EASEAGenome object + } + + virtual string className() const { return "EASEAGenome"; } + + EASEAGenome& operator=(const EASEAGenome & arg) { + copy(arg); + return *this; + } + + void copy(const EASEAGenome& genome) + { + if(&genome != this){ + \GENOME_DTOR + \COPY_CTOR + if (genome.invalid()) { // copying an invalid genome + fitness(FitT()); // put a valid value (i.e. non NAN) + invalidate(); // but INVALIDATE the genome + } + else + fitness(genome.fitness()); + } + } + + bool operator==(const EASEAGenome & genome) const { + \EQUAL + return true; + } + + bool operator!=(const EASEAGenome & genome) const { + return !(*this==genome); + } + + /** printing... */ + void printOn(ostream& os) const + { + // First write the fitness + EO::printOn(os); + os << ' '; + // START Code of default output + + /** HINTS + * in EO we systematically write the sizes of things before the things + * so readFrom is easier to code (see below) + */ +\INSERT_DISPLAY +\WRITE + // END Code of default output + } + + /** reading... + * of course, your readFrom must be able to read what printOn writes!!! + */ + void readFrom(istream& is) + { + // of course you should read the fitness first! + EO::readFrom(is); + // START Code of input + + /** HINTS + * remember the EASEAGenome object will come from the default ctor + * this is why having the sizes written out is useful + */ +\READ + // END Code of input + } + + //private: // put all data here - no privacy in EASEA + // START Private data of an EASEAGenome object +\INSERT_GENOME + // END Private data of an EASEAGenome object +}; +#endif + +\START_EO_EVAL_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEAEvalFunc.h +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// + +/* +Evaluator in EO: a functor that computes the fitness of an EO +============================================================= +*/ + +#ifndef _EASEAEvalFunc_h +#define _EASEAEvalFunc_h + +// include whatever general include you need +#include +#include + +// 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 +*/ +template +class EASEAEvalFunc : public eoEvalFunc +{ +public: + /// Ctor - no requirement +// START eventually add or modify the anyVariable argument + EASEAEvalFunc() + // EASEAEvalFunc( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an EASEAEvalFunc object + // END Code of Ctor of an EASEAEvalFunc object + } + + /** Actually compute the fitness + * + * @param EOT & _eo the EO object to evaluate + * it should stay templatized to be usable + * with any fitness type + */ + void operator()(EOT & genome) + { + // test for invalid to avoid recomputing fitness of unmodified individuals + if (genome.invalid()) + { + // START Code of computation of fitness of the EASEA object +\INSERT_EVALUATOR + // END Code of computation of fitness of the EASEA object + } + } + +private: +// START Private data of an EASEAEvalFunc object + // varType anyVariable; // for example ... +// END Private data of an EASEAEvalFunc object +}; + + +#endif + +\START_EO_INITER_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEAInit.h +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// + +/* +objects initialization in EO +============================ +*/ + +#ifndef _EASEAInit_h +#define _EASEAInit_h + +// 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 + * atoms of an eoVector you will need an eoInit) + */ +template +class EASEAInit: public eoInit { +public: + /// Ctor - no requirement +// START eventually add or modify the anyVariable argument + EASEAInit() + // EASEAInit( varType & _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an EASEAInit object + // END Code of Ctor of an EASEAInit object + } + + + /** initialize a genotype + * + * @param _genotype generally a genotype that has been default-constructed + * whatever it contains will be lost + */ + void operator()(GenotypeT & _genotype) + { + // START Code of random initialization of an EASEAGenome object +\INSERT_EO_INITIALISER + // END Code of random initialization of an EASEAGenome object + _genotype.invalidate(); // IMPORTANT in case the _genotype is old + } + +private: +// START Private data of an EASEAInit object + // varType & anyVariable; // for example ... +// END Private data of an EASEAInit object +}; + +#endif + + +\START_EO_MUT_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEAMutation.h +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// + +/* +simple mutation operators +========================= +*/ + +#ifndef EASEAMutation_H +#define EASEAMutation_H + + +#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 +class EASEAMutation: public eoMonOp +{ +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + EASEAMutation() + // EASEAMutation( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an EASEAMutation object + // END Code of Ctor of an EASEAMutation object + } + + /// The class name. Used to display statistics + string className() const { return "EASEAMutation"; } + + /** + * modifies the parent + * @param _genotype The parent genotype (will be modified) + */ + bool operator()(GenotypeT & _genotype) + { + // START code for mutation of the _genotype object +\INSERT_MUTATOR + // END code for mutation of the _genotype object + +private: +// START Private data of an EASEAMutation object + // varType anyVariable; // for example ... +// END Private data of an EASEAMutation object +}; + +#endif + +\START_EO_QUAD_XOVER_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEAQuadCrossover.h +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// + +/* +Template for simple quadratic crossover operators +================================================= + +Quadratic crossover operators modify both genotypes +*/ + +#ifndef EASEAQuadCrossover_H +#define EASEAQuadCrossover_H + +#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 +class EASEAQuadCrossover: public eoQuadOp +{ +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + EASEAQuadCrossover() + // EASEAQuadCrossover( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an EASEAQuadCrossover object + // END Code of Ctor of an EASEAQuadCrossover object + } + + /// The class name. Used to display statistics + string className() const { return "EASEAQuadCrossover"; } + + /** + * eoQuad crossover - modifies both genotypes + */ + bool operator()(GenotypeT& child1, GenotypeT & child2) + { + GenotypeT parent1(child1); + GenotypeT parent2(child2); + + // START code for crossover of child1 and child2 objects +\INSERT_CROSSOVER + return (parent1!=child1)||(parent2!=child2); + // END code for crossover of child1 and child2 objects + } + +private: +// START Private data of an EASEAQuadCrossover object + // varType anyVariable; // for example ... +// END Private data of an EASEAQuadCrossover object +}; + +#endif + +\START_EO_CONTINUE_TPL// -*- mode: c++; c-indent-level: 2; c++-member-init-indent: 8; comment-column: 35; -*- +// +// (The above line is useful in Emacs-like editors) +// +//************************************* +// +// EASEA_make_continue.h +// +// C++ file generated by AESAE-EO v0.7 +// +//************************************* +// + +#ifndef _make_continue_h +#define _make_continue_h + +/* +Contains the templatized version of parser-based choice of stopping criterion +It can then be instantiated, and compiled on its own for a given EOType +(see e.g. in dir ga, ga.cpp) +*/ + +// Continuators - all include eoContinue.h +#include +#include +#include +#include +#include +#ifndef _MSC_VER +#include // CtrlC handling (using 2 global variables!) +#endif + + // also need the parser and param includes +#include +#include + + +/////////////////// the stopping criterion //////////////// +template +eoCombinedContinue * make_combinedContinue(eoCombinedContinue *_combined, eoContinue *_cont) +{ + if (_combined) // already exists + _combined->add(*_cont); + else + _combined = new eoCombinedContinue(*_cont); + return _combined; +} + +template +eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval) +{ + //////////// Stopping criterion /////////////////// + // the combined continue - to be filled + eoCombinedContinue *continuator = NULL; + + // for each possible criterion, check if wanted, otherwise do nothing + + // First the eoGenContinue - need a default value so you can run blind + // but we also need to be able to avoid it <--> 0 + eoValueParam& maxGenParam = _parser.createParam(\NB_GEN, "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion"); + // and give control to EASEA + EZ_NB_GEN = maxGenParam.value(); + pEZ_NB_GEN = & maxGenParam.value(); + + // do not test for positivity in EASEA + // 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); + // } + + // the steadyGen continue - only if user imput + eoValueParam& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion"); + 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); + } + + // Same thing with Eval - but here default value is 0 + eoValueParam& maxEvalParam = _parser.createParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)",'E',"Stopping criterion"); + + 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); + } + /* + // the steadyEval continue - only if user imput + eoValueParam& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion"); + 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); + } + */ + // the target fitness + eoFitContinue *fitCont; + 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); + } + +#ifndef _MSC_VER + // the CtrlC interception (Linux only I'm afraid) + eoCtrlCContinue *ctrlCCont; + eoValueParam& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion"); + if (_parser.isItThere(ctrlCParam)) + { + ctrlCCont = new eoCtrlCContinue; + // store + _state.storeFunctor(ctrlCCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, ctrlCCont); + } +#endif + + // now check that there is at least one! + if (!continuator) + throw runtime_error("You MUST provide a stopping criterion"); + // OK, it's there: store in the eoState + _state.storeFunctor(continuator); + + // and return + return *continuator; +} + +#endif + +\START_EO_PARAM_TPL#************************************* +# +# EASEA.prm +# +# Parameter file generated by AESAE-EO v0.7 +# +#************************************* +###### General ###### +# --help=0 # -h : Prints this message +# --stopOnUnknownParam=1 # Stop if unknown param entered +--seed=0 # -S : Random number seed + +###### Evolution Engine ###### +--popSize=\POP_SIZE # -P : Population Size +--selection=\SELECTOR\SELECT_PRM # -S : Selection: Roulette, Ranking(p,e), DetTour(T), StochTour(t) or Sequential(ordered/unordered) +--nbOffspring=\OFF_SIZE # -O : Nb of offspring (percentage or absolute) +--replacement=General # Type of replacement: Generational, ESComma, ESPlus, SSGA(T), EP(T) + +###### Evolution Engine / Replacement ###### +--elite=\ELITE_SIZE # Nb of elite parents (percentage or absolute) +--eliteType=\ELITISM # Strong (true) or weak (false) elitism (set elite to 0 for none) +--surviveParents=\SURV_PAR_SIZE # Nb of surviving parents (percentage or absolute) +--reduceParents=\RED_PAR\RED_PAR_PRM # Parents reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform +--surviveOffspring=\SURV_OFF_SIZE # Nb of surviving offspring (percentage or absolute) +--reduceOffspring=\RED_OFF\RED_OFF_PRM # Offspring reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform +--reduceFinal=\RED_FINAL\RED_FINAL_PRM # Final reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform + +###### Output ###### +# --useEval=1 # Use nb of eval. as counter (vs nb of gen.) +# --useTime=1 # Display time (s) every generation +# --printBestStat=1 # Print Best/avg/stdev every gen. +# --printPop=0 # Print sorted pop. every gen. + +###### Output - Disk ###### +# --resDir=Res # Directory to store DISK outputs +# --eraseDir=1 # erase files in dirName if any +# --fileBestStat=0 # Output bes/avg/std to file + +###### Output - Graphical ###### +# --plotBestStat=0 # Plot Best/avg Stat +# --plotHisto=0 # Plot histogram of fitnesses + +###### Persistence ###### +# --Load= # -L : A save file to restart from +# --recomputeFitness=0 # -r : Recompute the fitness after re-loading the pop.? +# --saveFrequency=0 # Save every F generation (0 = only final state, absent = never) +# --saveTimeInterval=0 # Save every T seconds (0 or absent = never) +# --status=OneMaxGenomeEA.status # Status file + +###### Stopping criterion ###### +# --maxGen=100 # -G : Maximum number of generations () = none) +# --steadyGen=100 # -s : Number of generations with no improvement +# --minGen=0 # -g : Minimum number of generations +# --maxEval=0 # -E : Maximum number of evaluations (0 = none) +# --targetFitness=0 # -T : Stop when fitness reaches +# --CtrlC=0 # -C : Terminate current generation upon Ctrl C + +###### Variation Operators ###### +# --cross1Rate=1 # -1 : Relative rate for crossover 1 +# --mut1Rate=1 # -1 : Relative rate for mutation 1 +--pCross=\XOVER_PROB # -C : Probability of Crossover +--pMut=\MUT_PROB # -M : Probability of Mutation + +\START_EO_MAKEFILE_TPL#************************************* +# +# EASEA.mak +# +# Makefile generated by AESAE-EO v0.7 +# +#************************************* + +# sample makefile for building an EA evolving a new genotype + +DIR_EO = \EO_DIR + +.cpp: ; c++ -DPACKAGE=\"eo\" -I. -I$(DIR_EO)/src -Wall -g -o $@ $*.cpp $(DIR_EO)/src/libeo.a $(DIR_EO)/src/utils/libeoutils.a + +.cpp.o: ; c++ -DPACKAGE=\"eo\" -I. -I\EO_DIR/src -Wall -g -c $*.cpp + +LIB_EO = $(DIR_EO)/src/utils/libeoutils.a $(DIR_EO)/src/libeo.a + +SOURCES = EASEA.cpp \ + EASEAEvalFunc.h \ + EASEAGenome.h \ + EASEAInit.h \ + EASEAMutation.h \ + EASEAQuadCrossover.h \ + $(LIB_EO) + +ALL = EASEA + +EASEA : $(SOURCES) + c++ -g -I. -I$(DIR_EO)/src -o $@ EASEA.cpp $(LIB_EO) -lm + +all : $(ALL) + +clean : ; /bin/rm *.o $(ALL) + +\TEMPLATE_END diff --git a/deprecated/eo/tutorial/Templates/Makefile.am.src-tmpl b/deprecated/eo/tutorial/Templates/Makefile.am.src-tmpl new file mode 100644 index 000000000..579f1895b --- /dev/null +++ b/deprecated/eo/tutorial/Templates/Makefile.am.src-tmpl @@ -0,0 +1,16 @@ +bin_PROGRAMS = MyStruct + +noinst_HEADERS = eoMyStruct.h \ + eoMyStructEvalFunc.h \ + eoMyStructInit.h \ + eoMyStructMutation.h \ + eoMyStructQuadCrossover.h + +MyStruct_SOURCES = MyStructEA.cpp + + +dnl Local Variables: +dnl coding: iso-8859-1 +dnl mode: makefile-automake +dnl fill-column: 80 +dnl End: diff --git a/deprecated/eo/tutorial/Templates/Makefile.am.top-tmpl b/deprecated/eo/tutorial/Templates/Makefile.am.top-tmpl new file mode 100644 index 000000000..7a943fe13 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/Makefile.am.top-tmpl @@ -0,0 +1,8 @@ +SUBDIRS = src + + +dnl Local Variables: +dnl coding: iso-8859-1 +dnl mode: makefile-automake +dnl fill-column: 80 +dnl End: diff --git a/deprecated/eo/tutorial/Templates/MyStructEA.cpp b/deprecated/eo/tutorial/Templates/MyStructEA.cpp new file mode 100644 index 000000000..1478e3085 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/MyStructEA.cpp @@ -0,0 +1,188 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +This is the template main file. +It includes all other files that have been generated by the script create.sh +so it is the only file to compile. + +In case you want to build up a separate library for your new Evolving Object, +you'll need some work - follow what's done in the src/ga dir, used in the +main file BitEA in tutorial/Lesson4 dir. +Or you can wait until we do it :-) +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoMyStruct MUST derive from EO for some fitness + */ +#include "eoMyStruct.h" + +/** definition of initilizqtion: + * class eoMyStructInit MUST derive from eoInit + */ +#include "eoMyStructInit.h" + +/** definition of evaluation: + * class eoMyStructEvalFunc MUST derive from eoEvalFunc + * and should test for validity before doing any computation + * see tutorial/Templates/evalFunc.tmpl + */ +#include "eoMyStructEvalFunc.h" + +// GENOTYPE eoMyStruct ***MUST*** be templatized over the fitness + +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* +// START fitness type: double or eoMaximizingFitness if you are maximizing +// eoMinimizingFitness if you are minimizing +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 + +// create an initializer +#include "make_genotype_MyStruct.h" +eoInit & make_genotype(eoParser& _parser, eoState&_state, Indi _eo) +{ + return do_make_genotype(_parser, _state, _eo); +} + +// and the variation operaotrs +#include "make_op_MyStruct.h" +eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) +{ + return do_make_op(_parser, _state, _init); +} + +// Use existing modules to define representation independent routines +// These are parser-based definitions of objects + +// how to initialize the population +// it IS representation independent if an eoInit is given +#include +eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +// the stopping criterion +#include +eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +// outputs (stats, population dumps, ...) +#include +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} + +// evolution engine (selection and replacement) +#include +eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +// simple call to the algo. stays there for consistency reasons +// no template for that one +#include +// the instanciating fitnesses +#include +void run_ea(eoAlgo& _ga, eoPop& _pop) +{ + do_run(_ga, _pop); +} + +// checks for help demand, and writes the status file +// and make_help; in libutils +void make_help(eoParser & _parser); + +// now use all of the above, + representation dependent things +int main(int argc, char* argv[]) +{ + + try + { + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + // The fitness + ////////////// + eoMyStructEvalFunc plainEval/* (varType _anyVariable) */; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // the genotype - through a genotype initializer + eoInit& init = make_genotype(parser, state, Indi()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + + //// 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 + ////////////////////////////////////////////// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorithm + + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out +// cout << "Initial Population\n"; +// pop.sortedPrintOn(cout); +// cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + } + catch(exception& e) + { + cout << e.what() << endl; + } + return 0; +} diff --git a/deprecated/eo/tutorial/Templates/MyStructLibEA.cpp b/deprecated/eo/tutorial/Templates/MyStructLibEA.cpp new file mode 100644 index 000000000..54e9f2ff9 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/MyStructLibEA.cpp @@ -0,0 +1,162 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +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 +(make_MyStruct.cpp) and compiling it once and for all. +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoMyStruct MUST derive from EO for some fitness + */ +#include "eoMyStruct.h" + +/** definition of initilizqtion: + * class eoMyStructInit MUST derive from eoInit + */ +#include "eoMyStructInit.h" + +/** definition of evaluation: + * class eoMyStructEvalFunc MUST derive from eoEvalFunc + * and should test for validity before doing any computation + * see tutorial/Templates/evalFunc.tmpl + */ +#include "eoMyStructEvalFunc.h" + +// GENOTYPE eoMyStruct ***MUST*** be templatized over the fitness + +// +// START fitness type: double or eoMaximizingFitness if you are maximizing +// eoMinimizingFitness if you are minimizing +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 + +// create an initializer - done here and NOT in make_MyStruct.cpp +// because it is NOT representation independent +#include "make_genotype_MyStruct.h" +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" +eoGenOp& make_op(eoParser& _parser, eoState& _state, eoInit& _init) +{ + return do_make_op(_parser, _state, _init); +} + +// The representation independent routines are simply declared here + +// how to initialize the population +// it IS representation independent if an eoInit is given +eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init); + +// the stopping criterion +eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval); + +// outputs (stats, population dumps, ...) +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue); + +// 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 +// no template for that one +void run_ea(eoAlgo& _ga, eoPop& _pop); + +// checks for help demand, and writes the status file +// and make_help; in libutils - just a declaration, code in libeoutils.a +void make_help(eoParser & _parser); + +// now use all of the above, + representation dependent things +// from here on, no difference with eoMyStruct.cpp +int main(int argc, char* argv[]) +{ + + try + { + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + // The fitness + ////////////// + eoMyStructEvalFunc plainEval/* (varType _anyVariable) */; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // the genotype - through a genotype initializer + eoInit& init = make_genotype(parser, state, Indi()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + + //// 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 + ////////////////////////////////////////////// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + + ///// End of construction of the algorithm + + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out + cout << "Initial Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + } + catch(exception& e) + { + cout << e.what() << endl; + } + return 0; +} diff --git a/deprecated/eo/tutorial/Templates/MyStructSEA.cpp b/deprecated/eo/tutorial/Templates/MyStructSEA.cpp new file mode 100644 index 000000000..5a05169ea --- /dev/null +++ b/deprecated/eo/tutorial/Templates/MyStructSEA.cpp @@ -0,0 +1,350 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +This is the template main file. +It includes all other files that have been generated by the script create.sh +so it is the only file to compile. + +In case you want to build up a separate library for your new Evolving Object, +you'll need some work - follow what's done in the src/ga dir, used in the +main file BitEA in tutorial/Lesson4 dir. +Or you can wait until we do it :-) +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoMyStruct MUST derive from EO for some fitness + */ +#include "eoMyStruct.h" + +/** definition of initilizqtion: + * class eoMyStructInit MUST derive from eoInit + */ +#include "eoMyStructInit.h" + +/** definition of evaluation: + * class eoMyStructEvalFunc MUST derive from eoEvalFunc + * and should test for validity before doing any computation + * see tutorial/Templates/evalFunc.tmpl + */ +#include "eoMyStructEvalFunc.h" + +/** definitions of operators: write as many classes as types of operators + * and include them here. In this simple example, + * one crossover (2->2) and one mutation (1->1) operators are used + */ +#include "eoMyStructQuadCrossover.h" +#include "eoMyStructMutation.h" + +/* and (possibly) your personal statistics */ +#include "eoMyStructStat.h" + +// GENOTYPE eoMyStruct ***MUST*** be templatized over the fitness + +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* +// START fitness type: double or eoMaximizingFitness if you are maximizing +// eoMinimizingFitness if you are minimizing +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 + + +// Use existing modules to define representation independent routines + +// how to initialize the population +// it IS representation independent if an eoInit is given +#include +eoPop& make_pop(eoParser& _parser, eoState& _state, eoInit & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +// the stopping criterion +#include +eoContinue& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +// outputs (stats, population dumps, ...) +#include +eoCheckPoint& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter& _eval, eoContinue& _continue) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} + +// evolution engine (selection and replacement) +#include +eoAlgo& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op, eoDistance *_dist = NULL) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); +} + +// simple call to the algo. stays there for consistency reasons +// no template for that one +#include +// the instanciating fitnesses +#include +void run_ea(eoAlgo& _ga, eoPop& _pop) +{ + do_run(_ga, _pop); +} + +// checks for help demand, and writes the status file +// and make_help; in libutils +void make_help(eoParser & _parser); + +// now use all of the above, + representation dependent things +int main(int argc, char* argv[]) +{ +try + { + eoParser parser(argc, argv); // for user-parameter reading + + eoState state; // keeps all things allocated + + // The fitness + ////////////// + eoMyStructEvalFunc plainEval/* (varType _anyVariable) */; + // turn that object into an evaluation counter + eoEvalFuncCounter eval(plainEval); + + // a genotype initializer + eoMyStructInit init; + // or, if you need some parameters, you might as well + // - write a constructor of the eoMyStructInit that uses a parser + // - call it from here: + // eoMyStructInit init(parser); + + // if you want to do sharing, you'll need a distance. + // see file utils/eoDistance.h + // + // IF you representation has an operator[]() double-castable, + // then you can use for instance the quadratic distance (L2 norm) + // eoQuadDistance dist; + // or the Hamming distance (L1 norm) + // eoHammingDistance dist; + + + // Build the variation operator (any seq/prop construct) + // here, a simple example with only 1 crossover (2->2, a QuadOp) and + // one mutation, is given. + // Hints to have choice among multiple crossovers and mutations are given + + // A (first) crossover (possibly use the parser in its Ctor) + eoMyStructQuadCrossover cross /* (eoParser parser) */; + + // IF MORE THAN ONE: + + // read its relative rate in the combination +// double cross1Rate = parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", '1', "Variation Operators").value(); + + // create the combined operator with the first one (rename it cross1 !!!) +// eoPropCombinedQuadOp cross(cross1, cross1Rate); + + // and as many as you want the following way: + // 1- write the new class by mimicking eoMyStructQuadCrossover.h + // 2- include that file here together with eoMyStructQuadCrossover above + // 3- uncomment and duplicate the following lines: + // +// eoMyStructSecondCrossover cross2(eoParser parser); +// double cross2Rate = parser.createParam(1.0, "cross2Rate", "Relative rate for crossover 2", '2', "Variation Operators").value(); +// cross.add(cross2, cross2Rate); + + // NOTE: if you want some gentle output, the last one shoudl be like + // cross.add(cross, crossXXXRate, true); + + /////////////// Same thing for MUTATION + + // a (first) mutation (possibly use the parser in its Ctor) + eoMyStructMutation mut /* (parser) */; + + // IF MORE THAN ONE: + + // read its relative rate in the combination +// double mut1Rate = parser.createParam(1.0, "mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value(); + + // create the combined operator with the first one (rename it cross1 !!!) +// eoPropCombinedMonOp mut(mut1, mut1Rate); + + // and as many as you want the following way: + // 1- write the new class by mimicking eoMyStructMutation.h + // 2- include that file here together with eoMyStructMutation above + // 3- uncomment and duplicate the following lines: + // +// eoMyStructSecondMutation mut2(eoParser parser); +// double mut2Rate = parser.createParam(1.0, "mut2Rate", "Relative rate for mutation 2", '2', "Variation Operators").value(); +// mut.add(mut2, mut2Rate); + + // NOTE: if you want some gentle output, the last one shoudl be like + // mut.add(mut, mutXXXRate, true); + + // now encapsulate your crossover(s) and mutation(s) into an eoGeneralOp + // so you can fully benefit of the existing evolution engines + + // First read the individual level parameters + double pCross = parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ).value(); + // minimum check + if ( (pCross < 0) || (pCross > 1) ) + throw runtime_error("Invalid pCross"); + + double pMut = parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" ).value(); + // minimum check + if ( (pMut < 0) || (pMut > 1) ) + throw runtime_error("Invalid pMut"); + + // now create the generalOp + eoSGAGenOp op(cross, pCross, mut, pMut); + + + //// Now some representation-independent things + // + // You do not need to modify anything beyond this point + // unless you want to add specific statistics to the checkpoint + // in which case you should uncomment the corresponding block + // and possibly modify the parameters in the stat object creation + ////////////////////////////////////////////// + + // initialize the population + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval); + // output + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval, term); + + + // UNCOMMENT the following commented block if you want to add you stats + + // if uncommented, it is assumed that you will want to print some stat. + // if not, then the following objects will be created uselessly - but what the heck! + + eoMyStructStat myStat; // or maybe myStat(parser); + checkpoint.add(myStat); + // This one is probably redundant with the one in make_checkpoint, but w.t.h. + eoIncrementorParam generationCounter("Gen."); + checkpoint.add(generationCounter); + // need to get the name of the redDir param (if any) + std::string dirName = parser.getORcreateParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk").value() + "/"; + + + // those need to be pointers because of the if's + eoStdoutMonitor *myStdOutMonitor; + eoFileMonitor *myFileMonitor; +#ifdef HAVE_GNUPLOT + eoGnuplot1DMonitor *myGnuMonitor; +#endif + + // now check how you want to output the stat: + bool printMyStructStat = parser.createParam(false, "coutMyStructStat", "Prints my stat to screen, one line per generation", '\0', "My application").value(); + bool fileMyStructStat = parser.createParam(false, "fileMyStructStat", "Saves my stat to file (in resDir", '\0', "My application").value(); + bool plotMyStructStat = parser.createParam(false, "plotMyStructStat", "On-line plots my stat using gnuplot", '\0', "My application").value(); + + // should we write it on StdOut ? + if (printMyStructStat) + { + myStdOutMonitor = new eoStdoutMonitor(false); + // don't forget to store the memory in the state + state.storeFunctor(myStdOutMonitor); + // and of course to add the monitor to the checkpoint + checkpoint.add(*myStdOutMonitor); + // and the different fields to the monitor + myStdOutMonitor->add(generationCounter); + myStdOutMonitor->add(eval); + myStdOutMonitor->add(myStat); + } + + // first check the directory (and creates it if not exists already): + if (fileMyStructStat || plotMyStructStat) + if (! testDirRes(dirName, true) ) + throw runtime_error("Problem with resDir"); + + // should we write it to a file ? + if (fileMyStructStat) + { + // the file name is hard-coded - of course you can read + // a string parameter in the parser if you prefer + myFileMonitor = new eoFileMonitor(dirName + "myStat.xg"); + // don't forget to store the memory in the state + state.storeFunctor(myFileMonitor); + // and of course to add the monitor to the checkpoint + checkpoint.add(*myFileMonitor); + // and the different fields to the monitor + myFileMonitor->add(generationCounter); + myFileMonitor->add(eval); + myFileMonitor->add(myStat); + } + +#ifdef HAVE_GNUPLOT + // should we PLOT it on StdOut ? (one dot per generation, incremental plot) + if (plotMyStructStat) + { + myGnuMonitor = new eoGnuplot1DMonitor(dirName+"plot_myStat.xg",minimizing_fitness()); + // NOTE: you cand send commands to gnuplot at any time with the method + // myGnuMonitor->gnuplotCommand(string) + // par exemple, gnuplotCommand("set logscale y") + + // don't forget to store the memory in the state + state.storeFunctor(myGnuMonitor); + // and of course to add the monitor to the checkpoint + checkpoint.add(*myGnuMonitor); + // and the different fields to the monitor (X = eval, Y = myStat) + myGnuMonitor->add(eval); + myGnuMonitor->add(myStat); + } +#endif + + // algorithm (need the operator!) + eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op); + // and the distance if you want to do sharing + // eoAlgo& ga = make_algo_scalar(parser, state, eval, checkpoint, op, &dist); + + ///// End of construction of the algorithm + + ///////////////////////////////////////// + // to be called AFTER all parameters have been read!!! + make_help(parser); + + //// GO + /////// + // evaluate intial population AFTER help and status in case it takes time + apply(eval, pop); + // if you want to print it out +// cout << "Initial Population\n"; +// pop.sortedPrintOn(cout); +// cout << endl; + + run_ea(ga, pop); // run the ga + + cout << "Final Population\n"; + pop.sortedPrintOn(cout); + cout << endl; + + } + catch(exception& e) + { + cout << e.what() << endl; + } + return 0; +} diff --git a/deprecated/eo/tutorial/Templates/README b/deprecated/eo/tutorial/Templates/README new file mode 100644 index 000000000..33d9438e5 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/README @@ -0,0 +1,34 @@ +This Templates directory contains template files of an EO project and +a script createEOproject.sh to create a complete new EO project. + +The template requires a complete installation of EO, that is, you must +have run "make install" in the build-directory. + +In particular, the C++ compiler must also know how to find the EO +include files and the linker must find the EO libraries. Most +probably, that means that you have to set the variables +CPLUS_INCLUDE_PATH and LIBRARY_PATH, i.e. for a standard installation +and using tcsh: + setenv CPLUS_INCLUDE_PATH /usr/local/include/eo:"$CPLUS_INCLUDE_PATH" + setenv LIBRARY_PATH /usr/local/lib:"$LIBRARY_PATH" + +When running bash, use this: + export CPLUS_INCLUDE_PATH=/usr/local/include/eo:"$CPLUS_INCLUDE_PATH" + export LIBRARY_PATH=/usr/local/lib:"$LIBRARY_PATH" + + +You can freely move the created project around. However, whenever you +change the location of the source- or build-directories, you need to +run + touch configure.ac && autoreconf +in the source-directory and + make +in the build-directory (which might or might not be the same for you). + + +When you add additional source files to the project, simply add them +to the _SOURCES variable in src/Makefile.am. Header files +should be added to noinst_HEADERS. + + +See README.manual for more details. diff --git a/deprecated/eo/tutorial/Templates/README.manual b/deprecated/eo/tutorial/Templates/README.manual new file mode 100644 index 000000000..38693d83b --- /dev/null +++ b/deprecated/eo/tutorial/Templates/README.manual @@ -0,0 +1,143 @@ +This is the old template-directory README. Most of this information is +still accurate and it contains more details than the new README. +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 +(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). + +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 +in the Lesson4 of the tutorial, but with YOUR genotype instead of +bitstrings or vector. More details in Lesson5 of the tutorial. + +It is assumed in the following that you have read the first part of +the tutorial (Lessons 1 to 4). + +Creating the algorithm for your genotype +---------------------------------------- +In what follows, we will suppose that you want to evolve some data +structure, and that you have enough programming skills to be able to +write C code for its random initilialization, its crossover, its +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). + +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 +eoAppliXXX) + +1- cd to the tutorial dir + +2- create the directory for your application (let's assume you call it +APPLICATION): type in + + mkdir APPLICATION + +3- go to the Templates dir + + cd Templates + +and run the helper script create.sh with the following arguments + + ./create.sh Appli ../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 + 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 + +Note: You can go directly to step 6 and 7: you'll get a lot of +warnings, but will be able to run an EA that does nothing! + +5- Edit those files to suit your needs. The minimal addition you'll need +to make are + in eoAppli.h define your genotype + in eoAppliInit.h define the initialization of one genotype + in eoAppliMutation.h define the mutation of one genotype + in eoAppliQuadCrossover.h define the crossover of 2 genotypes + +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 + +7- Run the resulting program: + + % eoAppliEA + +The default output is one line per generation with the generation +number, the number of evaluations performed, the best and average +fitnesses in the population. +The algorithm stops by default after 100 generations. + +8- Customize the parameters: copy eoAppliEA.status into +e.g. eoAppliEA.param, edit eoAppliEA.param (uncomment the lines you +want to become active), and run + + % eoAppliEA @eoAppliEA.param + +(see the Lesson 5 of the tutorial for more details now). + +HINTS +----- + +1- If some new classes you create require some user parameter, you can +either read them in the file where they are created (e.g. +make_op_Appli.h for variation operators), or pass the eoParser to the +constructor of the class, and read the parameter from the parser. + +2- If you stick to privacy for the data in your EO class, you will +probably need to write accessors to those data, as well as some public +methods to modify them, as soon as some other methods need them too. + +3- The sample make_op_Appli.h supposes that you ony have one crossover +and one mutation operator. However, the code for multiple operators is +there: you can have for instance 2 crossover operators, and choose +among them according to relative weights (proportional choice) - same +for mutation. Look at the operator section in eoAppliEA.cpp In +particular, the user parameters cross1Rate and mut1Rate are totally +useless for a single operator. + +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 +* 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 + 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); + +and change the name of the class from eoAppliSecondMutation to your +name eoAppliBetterMutation (you can also change the keyword from +mut2Rate to something more meaningful like BetterMutationRate). +You're done! + +In case of problem: Marc.Schoenauer@inria.fr diff --git a/deprecated/eo/tutorial/Templates/README.tmpl b/deprecated/eo/tutorial/Templates/README.tmpl new file mode 100644 index 000000000..b64416566 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/README.tmpl @@ -0,0 +1,21 @@ +This is an autogenerated EO project. It was (most probably) generated +using the createEOproject.sh script in the +/tutorial/Templates directory. + +The project has a complete build-infrastructure based on +automake/autoconf. You can simply run "make" in this directory to have +the program compiled. The executable build will be in src/. In case of +problem during this step, please read the README file in the +...eo-dir/tutorial/Templates directory. + +After creation, the project should compile nicely - but of course the +resulting program does noting at all but print a few silly lines. + +Fill in the marked code-snippets in the files in src/ and you have a +complete EA project (detailed explanations in EO Tutorial - Lesson 5). + +Enjoy! + + +For details, for example on moving your project around or adding new +files, see /tutorial/Templates/README. diff --git a/deprecated/eo/tutorial/Templates/binCrossover.tmpl b/deprecated/eo/tutorial/Templates/binCrossover.tmpl new file mode 100644 index 000000000..c3f44c5af --- /dev/null +++ b/deprecated/eo/tutorial/Templates/binCrossover.tmpl @@ -0,0 +1,70 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +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 +*/ + +#ifndef eoMyStructBinCrossover_H +#define eoMyStructBinCrossover_H + +#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 +class eoMyStructBinCrossover: public eoBinOp +{ +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + eoMyStructBinCrossover() + // eoMyStructBinCrossover( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMyStructEvalFunc object + // END Code of Ctor of an eoMyStructEvalFunc object + } + + /// The class name. Used to display statistics + string className() const { return "eoMyStructBinCrossover"; } + + /** + * binCrossover - modifies first genotype only + * @param _genotype1 The first genotype + * @param _genotype2 The second genotype - const + */ + bool operator()(GenotypeT & _genotype1, const GenotypeT & _genotype2) + { + // START code for crossover of _genotype1 and _genotype2 objects + + /** Requirement + * if _genotype1 has been modified + * return true; + * otherwise + * return false; + */ + + // END code for crossover of _genotype1 and _genotype2 objects + } + +private: +// START Private data of an eoMyStructBinCrossover object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructBinCrossover object +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/configure.ac.tmpl b/deprecated/eo/tutorial/Templates/configure.ac.tmpl new file mode 100644 index 000000000..8c09bf41a --- /dev/null +++ b/deprecated/eo/tutorial/Templates/configure.ac.tmpl @@ -0,0 +1,39 @@ +# EO template autogeneration configure.ac template +# +# Copyright (C) 2006 Jochen Kpper +# +dnl Process this file with autoconf to produce a configure script. +AC_INIT(MyStruct, 0.1) +AC_CONFIG_SRCDIR(src/eoMyStruct.h) +AM_INIT_AUTOMAKE +AC_CONFIG_HEADERS(config.h) + +dnl Checks for programs. +AC_PROG_CC +AC_PROG_CXX +AC_ISC_POSIX + +dnl Checks for header files. +AC_STDC_HEADERS +AC_LANG(C++) +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_CHECK_LIB([eo], [main], [], + AC_MSG_ERROR([Evolving Objects library is required.])) +AC_CHECK_LIB([es], [main], [], + AC_MSG_ERROR([EO Evolutionary strategies library is required.])) + +dnl Checks for library functions. + +AC_OUTPUT([Makefile src/Makefile]) + + +dnl Local Variables: +dnl coding: iso-8859-1 +dnl mode: autoconf +dnl fill-column: 80 +dnl End: diff --git a/deprecated/eo/tutorial/Templates/continue.tmpl b/deprecated/eo/tutorial/Templates/continue.tmpl new file mode 100644 index 000000000..bfcee4d34 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/continue.tmpl @@ -0,0 +1,64 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for continuator in EO, i.e. stopping conditions for EO algorithms +========================================================================== +*/ + +#ifndef _eoMyStructContinue_h +#define _eoMyStructContinue_h + +// 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 + * be called with an eoPop + */ +template< class EOT> +class eoMyStructContinue: public eoContinue { +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + eoMyStructContinue() + // eoMyStructBinCrossover( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMyStructEvalFunc object + // END Code of Ctor of an eoMyStructEvalFunc object + } + + + /** Returns false when you want to stop + * + * @param _pop an eoPop + */ + virtual bool operator() ( const eoPop& _pop ) + { + bool stopCondition ; // to store the stopping condition + // START Code of computation of stopping condition + // stopCondition = blablabla + // END Code of computation of stopping condition + if (stopCondition) // the algo will stop upon return FALSE + { + cout << "STOP in eoMyStructContinue \n"; + return false; + } + return true; // == do not stop + } + +private: +// START Private data of an eoMyStructContinue object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructContinue object +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/createEOproject.sh b/deprecated/eo/tutorial/Templates/createEOproject.sh new file mode 100755 index 000000000..9f932f909 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/createEOproject.sh @@ -0,0 +1,116 @@ +#! /bin/tcsh -f +# +# Script to create a completely new EO project from templates +# +# Originally by Marc Schoenauer +# Copyright (C) 2006 Jochen Kpper + +if ($PWD:t != Templates) then + echo "You must start this shell script from the EO Template directory" + exit +endif + +if ($#argv < 1) then + echo "Usage: $0 ApplicationName [TargetDirName]" + 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 +endif + +# we're going to do something +echo " " +if ($#argv == 1) then + set TargetDir = /tmp/$1 +else + set TargetDir = $2 +endif +if ( -d $TargetDir ) then + echo "Warning: The target directory does exist already." + echo -n "Overwrite (yes/no)? " + set REP = $< + if ($REP != "yes") then + echo "Stopping, nothing done!" + exit + endif +else if ( -e $TargetDir ) then + echo "Warning: $TargetDir exist but isn't a directory." + echo "Stopping, nothing done!" + exit +endif +mkdir -p $TargetDir/src + + +# creating files +echo "Creating source files for application $1 in $TargetDir/src" +sed s/MyStruct/$1/g eoMyStruct.tmpl > $TargetDir/src/eo$1.h +sed s/MyStruct/$1/g init.tmpl > $TargetDir/src/eo$1Init.h +sed s/MyStruct/$1/g stat.tmpl > $TargetDir/src/eo$1Stat.h +sed s/MyStruct/$1/g evalFunc.tmpl > $TargetDir/src/eo$1EvalFunc.h +sed s/MyStruct/$1/g mutation.tmpl > $TargetDir/src/eo$1Mutation.h +sed s/MyStruct/$1/g quadCrossover.tmpl > $TargetDir/src/eo$1QuadCrossover.h +sed s/MyStruct/$1/g MyStructSEA.cpp > $TargetDir/src/$1EA.cpp + +echo "Creating build-support files for application $1 in $TargetDir" +sed s/MyStruct/$1/g configure.ac.tmpl > $TargetDir/configure.ac +sed s/MyStruct/$1/g Makefile.am.top-tmpl > $TargetDir/Makefile.am +sed s/MyStruct/$1/g Makefile.am.src-tmpl > $TargetDir/src/Makefile.am + + +##### Build a ready-to-use CMake config + +# need paths +set eo_src_var = 'EO_SRC_DIR' +echo "$PWD" > temp.txt +sed -e "s/\//\\\//g" temp.txt > temp2.txt +set safe_eo_path = `cat temp2.txt` +set safe_eo_path = "$safe_eo_path\/..\/.." + +set eo_bin_var = 'EO_BIN_DIR' +set eo_src_path = "$safe_eo_path" +set eo_bin_path = "$safe_eo_path\/build" + +sed -e "s/MyStruct/$1/g" -e "s/$eo_src_var/$eo_src_path/g" -e "s/$eo_bin_var/$eo_bin_path/g" CMakeLists.txt.top-tmpl > $TargetDir/CMakeLists.txt +sed -e "s/MyStruct/$1/g" CMakeLists.txt.src-tmpl > $TargetDir/src/CMakeLists.txt + +# remove temp dirs +rm -f temp.txt temp2.txt + +##### + + +sed s/MyStruct/$1/g README.tmpl > $TargetDir/README +touch $TargetDir/AUTHORS +touch $TargetDir/COPYING +touch $TargetDir/ChangeLog +touch $TargetDir/INSTALL +touch $TargetDir/NEWS + +echo "Successfully created project $1 in $TargetDir!" +echo "Start building the new project" + + +### building new project with the Autotools +#cd $TargetDir +#aclocal || exit +#autoheader || exit +#automake --add-missing --copy --gnu || exit + +# !!!!! uncompatible option: --force-missing for the latest version of automake + +#autoconf || exit +#./configure || exit +#make || exit + +# New: building new project using CMake +cd $TargetDir +#mkdir build +#cd build +cmake . || exit +make || exit + + +# done +echo "" +echo "Project $1 successfully build in $TargetDir!" +echo "Implement your code and enjoy." diff --git a/deprecated/eo/tutorial/Templates/eoMyStruct.tmpl b/deprecated/eo/tutorial/Templates/eoMyStruct.tmpl new file mode 100644 index 000000000..f68def2a8 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/eoMyStruct.tmpl @@ -0,0 +1,117 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +Mandatory: +- a default constructor (constructor without any argument) +- the I/O functions (readFrom and printOn) + +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). + +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. +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 + + * Note that you MUST derive your structure from EO + * but you MAY use some other already prepared class in the hierarchy + * 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 + * a default constructor + * IO routines printOn and readFrom + * + * Note that operator<< and operator>> are defined at EO level + * using these routines + */ +template< class FitT> +class eoMyStruct: public EO { +public: + /** Ctor: you MUST provide a default ctor. + * though such individuals will generally be processed + * by some eoInit object + */ + eoMyStruct() + { + // START Code of default Ctor of an eoMyStruct object + // END Code of default Ctor of an eoMyStruct object + } + + /** Copy Ctor: you MUST provide a copy ctor if the default + * one is not what you want + * If this is the case, uncomment and fill the following + */ + /* + eoMyStruct(const eoMyStruct &) + { + // START Code of copy Ctor of an eoMyStruct object + // END Code of copy Ctor of an eoMyStruct object + } + */ + + + virtual ~eoMyStruct() + { + // START Code of Destructor of an eoEASEAGenome object + // END Code of Destructor of an eoEASEAGenome object + } + + virtual string className() const { return "eoMyStruct"; } + + /** printing... */ + void printOn(ostream& os) const + { + // First write the fitness + EO::printOn(os); + os << ' '; + // START Code of default output + + /** HINTS + * in EO we systematically write the sizes of things before the things + * so readFrom is easier to code (see below) + */ + + // END Code of default output + } + + /** reading... + * of course, your readFrom must be able to read what printOn writes!!! + */ + void readFrom(istream& is) + { + // of course you should read the fitness first! + EO::readFrom(is); + // START Code of input + + /** HINTS + * remember the eoMyStruct object will come from the default ctor + * this is why having the sizes written out is useful + */ + + // END Code of input + } + +private: // put all data here + // START Private data of an eoMyStruct object + // END Private data of an eoMyStruct object +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/evalFunc.tmpl b/deprecated/eo/tutorial/Templates/evalFunc.tmpl new file mode 100644 index 000000000..34eae4c43 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/evalFunc.tmpl @@ -0,0 +1,65 @@ +/** -*- 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 + +// include whatever general include you need +#include +#include + +// 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 +*/ +template +class eoMyStructEvalFunc : public eoEvalFunc +{ +public: + /// Ctor - no requirement +// START eventually add or modify the anyVariable argument + eoMyStructEvalFunc() + // eoMyStructEvalFunc( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMyStructEvalFunc object + // END Code of Ctor of an eoMyStructEvalFunc object + } + + /** Actually compute the fitness + * + * @param EOT & _eo the EO object to evaluate + * it should stay templatized to be usable + * with any fitness type + */ + void operator()(EOT & _eo) + { + // test for invalid to avoid recomputing fitness of unmodified individuals + if (_eo.invalid()) + { + double fit; // to hold fitness value + // START Code of computation of fitness of the eoMyStruct object + // fit = blablabla + // END Code of computation of fitness of the eoMyStruct object + _eo.fitness(fit); + } + } + +private: +// START Private data of an eoMyStructEvalFunc object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructEvalFunc object +}; + + +#endif diff --git a/deprecated/eo/tutorial/Templates/init.tmpl b/deprecated/eo/tutorial/Templates/init.tmpl new file mode 100644 index 000000000..d49e52ef4 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/init.tmpl @@ -0,0 +1,57 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for EO objects initialization in EO +============================================ +*/ + +#ifndef _eoMyStructInit_h +#define _eoMyStructInit_h + +// 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 + * atoms of an eoVector you will need an eoInit) + */ +template +class eoMyStructInit: public eoInit { +public: + /// Ctor - no requirement +// START eventually add or modify the anyVariable argument + eoMyStructInit() + // eoMyStructInit( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMyStructInit object + // END Code of Ctor of an eoMyStructInit object + } + + + /** initialize a genotype + * + * @param _genotype generally a genotype that has been default-constructed + * whatever it contains will be lost + */ + void operator()(GenotypeT & _genotype) + { + // START Code of random initialization of an eoMyStruct object + // END Code of random initialization of an eoMyStruct object + _genotype.invalidate(); // IMPORTANT in case the _genotype is old + } + +private: +// START Private data of an eoMyStructInit object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructInit object +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl b/deprecated/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl new file mode 100644 index 000000000..fea5a2a67 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/lessOffspringExternalSelectorGenOp.tmpl @@ -0,0 +1,81 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for general operators +=============================== +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 +*/ + +#ifndef eoLessOffspringExternalSelectorGenOp_H +#define eoLessOffspringExternalSelectorGenOp_H + +#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() + * must be called if the genotypes of the indis is modified + */ +template +class eoLessOffspringExternalSelectorGenOp: public eoGenOp +{ +public: + /** + * (Default) Constructor. + */ + eoLessOffspringExternalSelectorGenOp(eoSelectOne & _sel, paramType _anyParameter) : + sel(_sel), anyParameter(_anyParameter) {} + + /// The class name. Used to display statistics + string className() const { return "eoLessOffspringExternalSelectorGenOp"; } + + /// The TOTAL number of offspring (here = nb of parents modified in place) + unsigned max_production(void) { return NbLeftParents; } + + /** + * eoShrinkGen operator - modifies some parents in the populator + * using extra "parents" selected from an external selector + * + * @param _pop a POPULATOR (not a simple population) + */ + void apply(eoPopulator& _plop) + { + // First, select as many parents as you will have offspring + EOT& parent1 = *_plop; // select the first parent + ++_plop; // advance once for each selected parents + ... + EOT& parentN = *_plop; // say you want N offspring + + // 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()); + + // modify (in place) the "true" parents + // (i.e. parent1, ..., parentsN) + ... + + // invalidate fitnesses of modified parents + parent1.invalidate(); + ... + parentN.invalidate(); + } + + +private: + eoSelectOne & sel; + paramType anyParameter +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl b/deprecated/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl new file mode 100644 index 000000000..8fdd8ff66 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/lessOffspringSameSelectorGenOp.tmpl @@ -0,0 +1,76 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for general operators +=============================== +i.e. that takes any number of parents and generates any number of offspring + +a GenOp that creates less offspring than there are parents + +First version, get parents from populator using the imbedded select() method +*/ + +#ifndef eoLessOffspringSameSelectorGenOp_H +#define eoLessOffspringSameSelectorGenOp_H + +#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() + * must be called if the genotypes of the indis is modified + */ +template +class eoLessOffspringSameSelectorGenOp: public eoGenOp +{ +public: + /** + * (Default) Constructor. + */ + eoLessOffspringSameSelectorGenOp(paramType _anyParameter) : + anyParameter(_anyParameter) {} + + /// The class name. Used to display statistics + string className() const { return "eoLessOffspringSameSelectorGenOp"; } + + /// The TOTAL number of offspring (here = nb of remaining modified parents) + unsigned max_production(void) { return NbLeftParents; } + + /** + * eoLesOffspringSameSelectorGenOp operator - + * gets extra parents from the populator + * + * @param _pop a POPULATOR (not a simple population) + */ + void apply(eoPopulator& _plop) + { + // First, select as many parents as you will have offspring + EOT& parent1 = *_plop; // select the first parent + ++_plop; // advance once for each selected parents + ... + EOT& parentN = *_plop; // say you want N offspring + + // Now select extra parents from the populator + EOT& parentN+1 = _plop.select(); + ... + EOT& parentN+K = _plop.select(); + + // modify the first N parents + ... + + // oh right, and invalidate their fitnesses + parent1.invalidate(); + ... + parentN.invalidate(); + } + +private: + paramType anyParameter +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/make_MyStruct.cpp b/deprecated/eo/tutorial/Templates/make_MyStruct.cpp new file mode 100644 index 000000000..aaf183c91 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/make_MyStruct.cpp @@ -0,0 +1,128 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for creating a new representation in EO +================================================ + +This is the template file that allows separate compilation of +everything that is representation independant (evolution engine and +general output) for an Evolutionary Algorithm with scalar fitness. + +It includes of course the definition of the genotype (eoMyStruct.h) and +is written like the make_xxx.cpp files in dirs src/ga (for bitstrings) +and src/es (for real vectors). + +*/ + +// Miscilaneous include and declaration +#include +using namespace std; + +// eo general include +#include "eo" +// the real bounds (not yet in general eo include) +#include "utils/eoRealVectorBounds.h" + +// include here whatever specific files for your representation +// Basically, this should include at least the following + +/** definition of representation: + * class eoMyStruct MUST derive from EO for some fitness + */ +#include "eoMyStruct.h" + +// create an initializer: this is NOT representation-independent +// and will be done in the main file +// However, should you decide to freeze that part, you could use the +// following (and remove it from the main file, of course!!!) +//------------------------------------------------------------------ +// #include "make_genotype_MyStruct.h" +// eoInit> & make_genotype(eoParser& _parser, eoState&_state, eoMyStruct _eo) +// { +// return do_make_genotype(_parser, _state, _eo); +// } + +// eoInit> & make_genotype(eoParser& _parser, eoState&_state, eoMyStruct _eo) +// { +// return do_make_genotype(_parser, _state, _eo); +// } + +// same thing for the variation operaotrs +//--------------------------------------- +// #include "make_op_MyStruct.h" +// eoGenOp>& make_op(eoParser& _parser, eoState& _state, eoInit>& _init) +// { +// return do_make_op(_parser, _state, _init); +// } + +// eoGenOp>& make_op(eoParser& _parser, eoState& _state, eoInit>& _init) +// { +// return do_make_op(_parser, _state, _init); +// } + +// The following modules use ***representation independent*** routines + +// how to initialize the population +// it IS representation independent if an eoInit is given +#include +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +eoPop >& make_pop(eoParser& _parser, eoState& _state, eoInit > & _init) +{ + return do_make_pop(_parser, _state, _init); +} + +// the stopping criterion +#include +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +eoContinue >& make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter > & _eval) +{ + return do_make_continue(_parser, _state, _eval); +} + +// outputs (stats, population dumps, ...) +#include +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) +{ + return do_make_checkpoint(_parser, _state, _eval, _continue); +} + +// evolution engine (selection and replacement) +#include +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +eoAlgo >& make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc >& _eval, eoContinue >& _continue, eoGenOp >& _op) +{ + return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); +} + +// simple call to the algo. stays there for consistency reasons +// no template for that one +#include +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} + +void run_ea(eoAlgo >& _ga, eoPop >& _pop) +{ + do_run(_ga, _pop); +} diff --git a/deprecated/eo/tutorial/Templates/make_genotype_MyStruct.h b/deprecated/eo/tutorial/Templates/make_genotype_MyStruct.h new file mode 100644 index 000000000..7cc279467 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/make_genotype_MyStruct.h @@ -0,0 +1,73 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_genotype_h +#define _make_genotype_h + +#include +#include + // also need the parser and param includes +#include +#include + + +/* + * This fuction does the create an eoInit + * + * 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 + * 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 + * 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 + * that is ***not properly initialized*** +*/ + +template +eoInit & do_make_genotype(eoParser& _parser, eoState& _state, EOT) +{ + // 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(); + + // Then built the initializer - a pointer, stored in the eoState + eoInit* init = new eoMyStructInit /* ( param ) */ ; + // store in state + _state.storeFunctor(init); + // and return a reference + return *init; +} + +#endif diff --git a/deprecated/eo/tutorial/Templates/make_op_MyStruct.h b/deprecated/eo/tutorial/Templates/make_op_MyStruct.h new file mode 100644 index 000000000..d857e8958 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/make_op_MyStruct.h @@ -0,0 +1,210 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _make_op_MyStruct_h +#define _make_op_MyStruct_h + +// the operators +#include +#include +#include +#include +// combinations of simple eoOps (eoMonOp and eoQuadOp) +#include + +/** definition of mutation: + * class eoMyStructMonop MUST derive from eoMonOp + */ +#include "eoMyStructMutation.h" + +/** definition of crossover (either as eoBinOp (2->1) or eoQuadOp (2->2): + * class eoMyStructBinCrossover MUST derive from eoBinOp + * OR + * class eoMyStructQuadCrossover MUST derive from eoQuadOp + */ +// #include "eoMyStructBinOp.h" +// OR +#include "eoMyStructQuadCrossover.h" + + // also need the parser and state includes +#include +#include + + +/////////////////// variation operators /////////////// +// canonical (crossover + mutation) only at the moment // + +/* + * 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 + * about the genotypes, the init has it all (e.g. bounds, ...) + * Simply do + * EOT myEO; + * _init(myEO); + * and myEO is then an ACTUAL object + * + * As usual, the template is the complete EOT even though only the fitness + * is actually templatized here: the following only applies to eoMyStruct +*/ + +template +eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit& _init) +{ + // this is a temporary version, while Maarten codes the full tree-structured + // general operator input + // BTW we must leave that simple version available somehow, as it is the one + // that 90% people use! + + + ///////////////////////////// + // Variation operators + //////////////////////////// + // read crossover and mutations, combine each in a proportional Op + // and create the eoGenOp that calls crossover at rate pCross + // then mutation with rate pMut + + // the crossovers + ///////////////// + + // here we can have eoQuadOp (2->2) 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 + eoQuadOp *cross = new eoMyStructQuadCrossover /* (varType _anyVariable) */; + // store in the state + _state.storeFunctor(cross); + + // read its relative rate in the combination + double cross1Rate = _parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", '1', "Variation Operators").value(); + + // and create the combined operator with this one + eoPropCombinedQuadOp *propXover = + new eoPropCombinedQuadOp(*cross, cross1Rate); + // and of course stor it in the state + _state.storeFunctor(propXover); + + + // 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); + _state.storeFunctor(cross); + 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); + + + // the mutation: same story + //////////////// + // you can have more than one - combined in a proportional way + + // for each mutation, + // - define the mutator object + // - read its rate from the parser + // - add it to the proportional combination + + // a first mutation + eoMonOp *mut = new eoMyStructMutation/* (varType _anyVariable) */; + _state.storeFunctor(mut); + // its relative rate in the combination + double mut1Rate = _parser.createParam(1.0, "mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value(); + // and the creation of the combined operator with this one + eoPropCombinedMonOp *propMutation = new eoPropCombinedMonOp(*mut, mut1Rate); + _state.storeFunctor(propMutation); + + // Optional: A second(and third, and ...) mutation with their rates + // of course you must create the corresponding classes + // and all ***MUST*** derive from eoMonOp + + /* Uncomment if necessary - and replicate as many time as you need + mut = new eoMyStructSecondMutation(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); + */ + // if you want some gentle output, the last one shoudl be like + // propMutation.add(*mut, mutXXXRate, true); + + // end of crossover and mutation definitions + //////////////////////////////////////////// + +// END Modify definitions of objects by eventually add parameters +//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* + +// from now on, you do not need to modify anything +// though you CAN add things to the checkpointing (see tutorial) + + // now build the eoGenOp: + // 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 + // a QuadCopy and our crossover + // with proba pMut, our mutation + + // but of course you're free to use any smart combination you could think of + // especially, if you have to use eoBinOp rather than eoQuad Op youll have + // to modify that part + + // First read the individual level parameters + eoValueParam& pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ); + // minimum check + if ( (pCrossParam.value() < 0) || (pCrossParam.value() > 1) ) + throw runtime_error("Invalid pCross"); + + eoValueParam& pMutParam = _parser.createParam(0.1, "pMut", "Probability of Mutation", 'M', "Variation Operators" ); + // minimum check + if ( (pMutParam.value() < 0) || (pMutParam.value() > 1) ) + throw runtime_error("Invalid pMut"); + + + // the crossover - with probability pCross + eoProportionalOp * propOp = new eoProportionalOp ; + _state.storeFunctor(propOp); + eoQuadOp *ptQuad = new eoQuadCloneOp; + _state.storeFunctor(ptQuad); + propOp->add(*propXover, pCrossParam.value()); // crossover, with proba pcross + propOp->add(*ptQuad, 1-pCrossParam.value()); // nothing, with proba 1-pcross + + // now the sequential + eoSequentialOp *op = new eoSequentialOp; + _state.storeFunctor(op); + op->add(*propOp, 1.0); // always do combined crossover + op->add(*propMutation, pMutParam.value()); // then mutation, with proba pmut + + // that's it - return a reference + return *op; +} +#endif diff --git a/deprecated/eo/tutorial/Templates/moreOffspringGenOp.tmpl b/deprecated/eo/tutorial/Templates/moreOffspringGenOp.tmpl new file mode 100644 index 000000000..9d0b17762 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/moreOffspringGenOp.tmpl @@ -0,0 +1,77 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for general operators +=============================== +i.e. that takes any number of parents and generates any number of offspring + +Here, a GenOp that creates more (or same number of) offspring +than there are parents +*/ + +#ifndef eoMoreOffspringGenOp_H +#define eoMoreOffspringGenOp_H + +#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() + * must be called if the genotypes of the indis is modified + */ +template +class eoMoreOffspringGenOp: public eoGenOp +{ +public: + /** + * (Default) Constructor. + */ + eoMoreOffspringGenOp(paramType _anyParameter) : + anyParameter(_anyParameter) {} + + /// The class name. Used to display statistics + string className() const { return "eoMoreOffspringGenOp"; } + + /// The TOTAL number of offspring (including modified parents) + unsigned max_production(void) { return NbOffspring; } + + /** + * eoMoreOffspringGenOp operator - eventually modifies the parents + * BUT does generate more offspring + * + * @param _pop a POPULATOR (not a simple population) + */ + void apply(eoPopulator& _plop) + { + EOT& parent1 = *_plop; // select the first parent + ++_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 + + // apply operator to the parents (modifying them AND generating + // new individuals ofs1, ofs2, ..., ofsN + ++_plop; // advance before each insertion + _plop.insert(ofs1); + ... + ++_plop; // advance before each insertion + _plop.insert(ofsN); + + // oh right, and invalidate fitnesses of modified parents + parent1.invalidate(); + ... + parentN.invalidate(); + } + + +private: + paramType anyParameter +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/mutation.tmpl b/deprecated/eo/tutorial/Templates/mutation.tmpl new file mode 100644 index 000000000..48785313c --- /dev/null +++ b/deprecated/eo/tutorial/Templates/mutation.tmpl @@ -0,0 +1,68 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is useful in Emacs-like editors + */ + +/* +Template for simple mutation operators +====================================== +*/ + +#ifndef eoMyStructMutation_H +#define eoMyStructMutation_H + + +#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 +class eoMyStructMutation: public eoMonOp +{ +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + eoMyStructMutation() + // eoMyStructMutation( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMyStructEvalFunc object + // END Code of Ctor of an eoMyStructEvalFunc object + } + + /// The class name. Used to display statistics + string className() const { return "eoMyStructMutation"; } + + /** + * modifies the parent + * @param _genotype The parent genotype (will be modified) + */ + bool operator()(GenotypeT & _genotype) + { + 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 + } + +private: +// START Private data of an eoMyStructMutation object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructMutation object +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/quadCrossover.tmpl b/deprecated/eo/tutorial/Templates/quadCrossover.tmpl new file mode 100644 index 000000000..93f104a08 --- /dev/null +++ b/deprecated/eo/tutorial/Templates/quadCrossover.tmpl @@ -0,0 +1,71 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for simple quadratic crossover operators +================================================= + +Quadratic crossover operators modify the both genotypes +*/ + +#ifndef eoMyStructQuadCrossover_H +#define eoMyStructQuadCrossover_H + +#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 +class eoMyStructQuadCrossover: public eoQuadOp +{ +public: + /** + * Ctor - no requirement + */ +// START eventually add or modify the anyVariable argument + eoMyStructQuadCrossover() + // eoMyStructQuadCrossover( varType _anyVariable) : anyVariable(_anyVariable) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMyStructEvalFunc object + // END Code of Ctor of an eoMyStructEvalFunc object + } + + /// The class name. Used to display statistics + string className() const { return "eoMyStructQuadCrossover"; } + + /** + * eoQuad crossover - _genotype1 and _genotype2 are the (future) + * offspring, i.e. _copies_ of the parents, to be modified + * @param _genotype1 The first parent + * @param _genotype2 The second parent + */ + bool operator()(GenotypeT& _genotype1, GenotypeT & _genotype2) + { + 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 + } + +private: +// START Private data of an eoMyStructQuadCrossover object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructQuadCrossover object +}; + +#endif diff --git a/deprecated/eo/tutorial/Templates/stat.tmpl b/deprecated/eo/tutorial/Templates/stat.tmpl new file mode 100644 index 000000000..9f807d24d --- /dev/null +++ b/deprecated/eo/tutorial/Templates/stat.tmpl @@ -0,0 +1,63 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +The above line is usefulin Emacs-like editors + */ + +/* +Template for computing statistics on eoPop +============================================ +*/ + +#ifndef _eoMyStructStat_h +#define _eoMyStructStat_h + +// 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 + * + * ASSUMPTION on the class GenoypeT: + * it needs to derive from EO (i.e. has a Fitness). + * + * It is assumed that you want to compute a double. + * In case you want something else, then your stat should derive from + * eoStat + * where class T is the class of the computed statistics + */ +template +class eoMyStructStat : public eoStat +{ +public : + typedef typename EOT::Fitness Fitness; + +// START eventually add or modify the anyVariable argument + /** Ctor - you change the default name of course. + * @param + * _description : inherited from eoValueParam (eoStat is an from eoVapueParam) + */ + eoMyStructStat(std::string _description = "eoMyStructStat ") : + eoStat(0.0, _description) +// END eventually add or modify the anyVariable argument + { + // START Code of Ctor of an eoMonReelStat object + // END Code of Ctor of an eoMonReelStat object + } + + void operator()(const eoPop& _pop){ + double tmpStat(0.); + // START Code for computing the statistics - in tmpStat + // tmpStat = blablabla + // END Code for computing the statistics + eoStat::value() = tmpStat; // store the stat in the eoParam value() field + } + + virtual std::string className(void) const { return "eoMyStructStat"; } +private : +// START Private data of an eoMyStructStat object + // varType anyVariable; // for example ... +// END Private data of an eoMyStructStat object +}; + +#endif diff --git a/deprecated/eo/tutorial/html/BitEA.html b/deprecated/eo/tutorial/html/BitEA.html new file mode 100644 index 000000000..7d75bec5b --- /dev/null +++ b/deprecated/eo/tutorial/html/BitEA.html @@ -0,0 +1,261 @@ + + + + + + BitEA.cpp + + +Back to Lesson 4 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+
+

+BitEA.cpp

+Click on the figure to see the corresponding code.
+In the code, the colors are meaningfull
+The actual code is in boldface and the comment in normal face. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
  + + + + + +
+#include <iostream>
+#include <ga/make_ga.h>
+#include <apply.h>
+
+
+ + + + +
+ +#include "binary_value.h"
+
+
+ + + + +
+ +using namespace std;
+int main(int argc, char* argv[])
+{
+  try
+  {
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+// define your genotype and fitness types
+  typedef eoBit<double> EOT;
+
+
+ + + + +
+ +  eoParser parser(argc, argv);  // for user-parameter reading
+
+
+ + + + +
+ +  eoState state;      // keeps all things allocated
+  ///// FIRST, problem or representation dependent stuff
+  //////////////////////////////////////////////////////
+
+
+ + + + +
+ +  // The evaluation fn - encapsulated into an eval counter for output
+  eoEvalFuncPtr<EOT, float> mainEval( binary_value<EOT> );
+  eoEvalFuncCounter<EOT> eval(mainEval);
+
+
+ + + + +
+ +  // the genotype - through a genotype initializer
+  eoInit<EOT>& init = make_genotype(parser, state, EOT());
+
+
+ + + + +
+ +  // Build the variation operator (any seq/prop construct)
+  eoGenOp<EOT>& op = make_op(parser, state, init);
+
+
+ + + + +
+ +  //// Now the representation-independent things
+  //////////////////////////////////////////////
+  // initialize the population - and evaluate
+  // yes, this is representation indepedent once you have an eoInit
+  eoPop<EOT>& pop    = make_pop(parser, state, init);
+
+
+ + + + +
+ +  // stopping criteria
+  eoContinue<EOT> & term = make_continue(parser, state, eval);
+  // output
+  eoCheckPoint<EOT> & checkpoint = make_checkpoint(parser, state, eval, term);
+
+
+ + + + +
+ +  // algorithm (need the operator!)
+  eoAlgo<EOT>& ga = make_algo_scalar(parser, state, eval, checkpoint, op);
+  ///// End of construction of the algorith
+  /////////////////////////////////////////
+
+
+ + + + +
+ +  // to be called AFTER all parameters have been read!!!
+  make_help(parser);
+  //// GO
+  ///////
+
+
+ + + + +
+ +  // evaluate intial population AFTER help and status in case it takes time
+  apply(eval, pop);
+
+
+ + + + +
+ +  // print it out (sort witout modifying)
+  cout << "Initial Population\n";
+  pop.sortedPrintOn(cout);
+  cout << endl;
+
+
+ + + + +
+ +  run_ea(ga, pop); // run the ga
+
+
+ + + + +
+ +  // print it out (sort witout modifying)
+  cout << "Final Population\n";
+  pop.sortedPrintOn(cout);
+  cout << endl;
+
+
+ + + + +
+ +  }
+  catch(exception& e)
+  {
+      cout << e.what() << endl;
+  }
+}
+
+
Back to Lesson 4 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+
Last +modified: Wed Mar 6 05:40:27 2002 + + + diff --git a/deprecated/eo/tutorial/html/EA_tutorial.jpg b/deprecated/eo/tutorial/html/EA_tutorial.jpg new file mode 100644 index 000000000..11c0695fc Binary files /dev/null and b/deprecated/eo/tutorial/html/EA_tutorial.jpg differ diff --git a/deprecated/eo/tutorial/html/FirstBitEA.html b/deprecated/eo/tutorial/html/FirstBitEA.html new file mode 100644 index 000000000..4caa11055 --- /dev/null +++ b/deprecated/eo/tutorial/html/FirstBitEA.html @@ -0,0 +1,369 @@ + + + + + + FirstBitEA.cpp + + + +Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+FirstBitEA.cpp

+Click on the figure to see the corresponding code.
+In the code, the colors are meaningfull
+The actual code is in boldface and the comment in normal face. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
  + + + + + +
+//-----------------------------------------------------------------------------
+// FirstBitEA.cpp
+//-----------------------------------------------------------------------------
+//*
+// Still an instance of a VERY simple Bitstring Genetic Algorithm
+// (see FirstBitGA.cpp) but now with  Breeder - and Combined Ops
+//
+//-----------------------------------------------------------------------------
+// standard includes
+#include <stdexcept>  // runtime_error
+#include <iostream>    // cout
+#include <strstream>  // ostrstream, istrstream
+// the general include for eo
+#include <eo>
+
+
+ + + + +
+ +#include <ga.h>
+//-----------------------------------------------------------------------------
+// define your individuals
+typedef eoBit<double> Indi; // A bitstring with fitness double
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+// a simple fitness function that computes the number of ones of a bitstring
+// Now in a separate file, and declared as binary_value(const vector<bool> &)
+#include "binary_value.h"
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+void main_function(int argc, char **argv)
+{
+
+
+ + + + +
+ +  const unsigned int SEED = 42; // seed for random number generator
+  const unsigned int T_SIZE = 3; // size for tournament selection
+  const unsigned int VEC_SIZE = 8; // Number of bits in genotypes
+  const unsigned int POP_SIZE = 20; // Size of population
+  const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
+  const float CROSS_RATE = 0.8; // Crossover rate
+  const double P_MUT_PER_BIT = 0.01; // probability of bit-flip mutation
+  const float MUT_RATE = 1.0; // mutation rate
+  // some parameters for chosing among different operators
+  const double onePointRate = 0.5;        // rate for 1-pt Xover
+  const double twoPointsRate = 0.5;        // rate for 2-pt Xover
+  const double URate = 0.5;                      // rate for Uniform Xover
+  const double bitFlipRate = 0.5;          // rate for bit-flip mutation
+  const double oneBitRate = 0.5;            // rate for one-bit mutation
+
+
+ + + + +
+ +  //////////////////////////
+  //  Random seed
+  //////////////////////////
+  //reproducible random seed: if you don't change SEED above,
+  // you'll aways get the same result, NOT a random run
+  rng.reseed(SEED);
+
+
+ + + + +
+ +  /////////////////////////////
+  // Fitness function
+  ////////////////////////////
+  // Evaluation: from a plain C++ fn to an EvalFunc Object
+  // you need to give the full description of the function
+  eoEvalFuncPtr<Indi, double, const vector<bool>& > eval(  binary_value );
+
+
+ + + + +
+ +  ////////////////////////////////
+  // Initilisation of population
+  ////////////////////////////////
+  // based on eoUniformGenerator class (see utils/eoRndGenerators.h)
+  eoUniformGenerator<bool> uGen;
+  eoInitFixedLength<Indi> random(VEC_SIZE, uGen);
+  // Initialization of the population
+  eoPop<Indi> pop(POP_SIZE, random);
+  // and evaluate it in one line
+  apply<Indi>(eval, pop); // STL syntax
+
+
+ + + + +
+ +  // sort pop before printing it!
+  pop.sort();
+  // Print (sorted) intial population (raw printout)
+  cout << "Initial Population" << endl;
+  cout << pop;
+
+
+ + + + +
+ +  /////////////////////////////////////
+  // selection and replacement
+  ////////////////////////////////////
+
+
+ + + + +
+ +  // The robust tournament selection
+  eoDetTournamentSelect<Indi> selectOne(T_SIZE);            // T_SIZE in [2,POP_SIZE]
+ +  // is now encapsulated in a eoSelectPerc (entage)
+  eoSelectPerc<Indi> select(selectOne);// by default rate==1
+
+
+ + + + +
+ +  // And we now have the full slection/replacement - though with
+  // no replacement (== generational replacement) at the moment :-)
+  eoNoReplacement<Indi> replace;
+
+
+ + + + +
+ +  //////////////////////////////////////
+  // The variation operators
+  //////////////////////////////////////
+
+
+ + + + +
+ +  // 1-point crossover for bitstring
+  eo1PtBitXover<Indi> xover1;
+  // uniform crossover for bitstring
+  eoUBitXover<Indi> xoverU;
+  // 2-pots xover
+  eoNPtsBitXover<Indi> xover2(2);
+  // Combine them with relative rates
+  eoPropCombinedQuadOp<Indi> xover(xover1, onePointRate);
+  xover.add(xoverU, URate);
+  xover.add(xover2, twoPointsRate, true);
+
+
+ + + + +
+ +  
+  // standard bit-flip mutation for bitstring
+  eoBitMutation<Indi>  mutationBitFlip(P_MUT_PER_BIT);
+  // mutate exactly 1 bit per individual
+  eoDetBitFlip<Indi> mutationOneBit;
+  // Combine them with relative rates
+  eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
+  mutation.add(mutationOneBit, oneBitRate, true);
+  
+ +  // The operators are  encapsulated into an eoTRansform object
+  eoSGATransform<Indi> transform(xover, CROSS_RATE, mutation, MUT_RATE);
+
+
+ + + + +
+ + +
+ + + + +
+ +  //////////////////////////////////////
+  // termination conditions: use more than one
+  /////////////////////////////////////
+  // stop after MAX_GEN generations
+  eoGenContinue<Indi> genCont(MAX_GEN);
+  // do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement
+  eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, STEADY_GEN);
+  // stop when fitness reaches a target (here VEC_SIZE)
+  eoFitContinue<Indi> fitCont(0);
+  // do stop when one of the above says so
+  eoCombinedContinue<Indi> continuator(genCont);
+  continuator.add(steadyCont);
+  continuator.add(fitCont);
+
+
+ + + + +
+ +  /////////////////////////////////////////
+  // the algorithm
+  ////////////////////////////////////////
+  // Easy EA requires
+  // selection, transformation, eval, replacement, and stopping criterion
+  eoEasyEA<Indi> gga(continuator, eval, select, transform, replace);
+  // Apply algo to pop - that's it!
+  gga(pop);
+  
+
+
+ + + + +
+ +  // Print (sorted) intial population
+  pop.sort();
+  cout << "FINAL Population\n" << pop << endl;
+
+
+ + + + +
+ +}
+// A main that catches the exceptions
+int main(int argc, char **argv)
+{
+#ifdef _MSC_VER
+  //  rng.reseed(42);
+      int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
+        flag |= _CRTDBG_LEAK_CHECK_DF;
+      _CrtSetDbgFlag(flag);
+//    _CrtSetBreakAlloc(100);
+#endif
+      try
+      {
+              main_function(argc, argv);
+      }
+      catch(exception& e)
+      {
+              cout << "Exception: " << e.what() << '\n';
+      }
+      return 1;
+}
+
+
Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+
Last +modified: Sun Nov 19 22:26:27 2000 + + + diff --git a/deprecated/eo/tutorial/html/FirstBitGA.html b/deprecated/eo/tutorial/html/FirstBitGA.html new file mode 100644 index 000000000..d3012829a --- /dev/null +++ b/deprecated/eo/tutorial/html/FirstBitGA.html @@ -0,0 +1,312 @@ + + + + + + FirstBitGA.html + + + +Back to Lesson 1 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+Code for FirstBitGA

+Click on the figure to see the corresponding code. +
In the code, the colors are meaningfull +
The actual code is in boldface and the comment in normal face. +
+
+ + + + +
//----------------------------------------------------------------------------- +
// FirstBitGA.cpp +
//----------------------------------------------------------------------------- +
//* +
// An instance of a VERY simple Bitstring +Genetic Algorithm +
// +
//----------------------------------------------------------------------------- +
// standard includes +
#include <stdexcept>  // runtime_error  +
#include <iostream>    +// cout +
#include <strstream>  // ostrstream, +istrstream +
// the general include for eo +
#include <eo>
+ + + + + +
#include <ga.h>
+//----------------------------------------------------------------------------- +
// define your individuals +
typedef eoBit<double> Indi;        +// A bitstring with fitness double
+ + + + + +
//----------------------------------------------------------------------------- +
// a simple fitness function that computes +the number of ones of a bitstring +
//  @param _indi A biststring individual +
double binary_value(const +Indi & _indi) +
{ +
 double sum = 0; +
 for (unsigned i = 0; i < _indi.size(); +i++) +
     sum += _indi[i]; +
 return sum; +
}
+ + + + + +
//----------------------------------------------------------------------------- +
void main_function(int argc, char **argv) +
{
+ + + + + +
 // all parameters are hard-coded! +
 const unsigned int SEED = 42;          +// seed for random number generator +
 const unsigned int T_SIZE = 3;        +// size for tournament selection +
 const unsigned int VEC_SIZE = 8;    +// Number of bits in genotypes +
 const unsigned int POP_SIZE = 20;  +// Size of population +
 const unsigned int MAX_GEN = 100;  +// Maximum number of generation before STOP +
 const float CROSS_RATE = 0.8;          +// Crossover rate +
 const double P_MUT_PER_BIT = 0.01; +// probability of bit-flip mutation +
 const float MUT_RATE = 1.0;              +// mutation rate
+ + + + + +
////////////////////////// +
 //  Random seed +
 ////////////////////////// +
 //reproducible random seed: +if you don't change SEED above,  +
 // you'll aways get the same +result, NOT a random run +
 rng.reseed(SEED);
+ + + + + +
 ///////////////////////////// +
 // Fitness function +
 //////////////////////////// +
 // Evaluation: from a plain +C++ fn to an EvalFunc Object +
 eoEvalFuncPtr<Indi> eval(  +binary_value );
+ + + + + +
 //////////////////////////////// +
 // Initilisation of population +
 //////////////////////////////// +
 // declare the population +
 eoPop<Indi> pop; +
 // fill it! +
 for (unsigned int igeno=0; igeno<POP_SIZE; +igeno++) +
     { +
         +Indi v;                    +// void individual, to be filled +
         +for (unsigned ivar=0; ivar<VEC_SIZE; ivar++) +
             +{ +
                 +bool r = rng.flip(); // new value, random in {0,1} +
                 +v.push_back(r);          // +append that random value to v +
             +} +
         +eval(v);                                +// evaluate it +
         +pop.push_back(v);              +// and put it in the population +
     }
+ + + + + +
 // sort pop before printing +it! +
 pop.sort(); +
 // Print (sorted) intial population +(raw printout) +
 cout << "Initial Population" +<< endl; +
 cout << pop;
+ + + + + +
 ///////////////////////////////////// +
 // selection and replacement +
 ////////////////////////////////////
+ + + + + +
 // The robust tournament selection +
 eoDetTournamentSelect<Indi> select(T_SIZE);  +// T_SIZE in [2,POP_SIZE]
+ + + + + +
 // The simple GA evolution engine +uses generational replacement +
 // so no replacement procedure +is needed
+ + + + + +
+ + + + + +
 ////////////////////////////////////// +
 // The variation operators +
 //////////////////////////////////////
+ + + + + +
 // 1-point crossover for bitstring +
 eo1PtBitXover<Indi> xover;
+ + + + + +
+
 // standard bit-flip mutation +for bitstring +
 eoBitMutation<Indi>  mutation(P_MUT_PER_BIT);
+ + + + + +
 ////////////////////////////////////// +
 // termination condition +
 ///////////////////////////////////// +
 // stop after MAX_GEN generations +
 eoGenContinue<Indi> continuator(MAX_GEN); +
 
+ + + + + +
 ///////////////////////////////////////// +
 // the algorithm +
 //////////////////////////////////////// +
 // standard Generational GA +requires as parameters +
 // selection, evaluation, crossover +and mutation, stopping criterion +

 eoSGA<Indi> gga(select, xover, +CROSS_RATE, mutation, MUT_RATE,  +
                                 +eval, continuator); +
 // Apply algo to pop - that's +it! +
 gga(pop); +
 

+ + + + + +
 // Print (sorted) intial population +
 pop.sort(); +
 cout << "FINAL Population\n" +<< pop << endl;
+ + + + + +
} +
// A main that catches the exceptions +
int main(int argc, char **argv) +
{ +
#ifdef _MSC_VER +
 //  rng.reseed(42); +
     int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); +
       flag +|= _CRTDBG_LEAK_CHECK_DF; +
     _CrtSetDbgFlag(flag); +
//    _CrtSetBreakAlloc(100); +
#endif +
     try +
     { +
             +main_function(argc, argv); +
     } +
     catch(exception& +e) +
     { +
             +cout << "Exception: " << e.what() << '\n'; +
     } +
     return 1; +
}
+ +
Back to Lesson 1 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Sun Nov +19 08:31:26 2000 + + diff --git a/deprecated/eo/tutorial/html/FirstRealEA.html b/deprecated/eo/tutorial/html/FirstRealEA.html new file mode 100644 index 000000000..ad60c2c22 --- /dev/null +++ b/deprecated/eo/tutorial/html/FirstRealEA.html @@ -0,0 +1,354 @@ + + + + + + FirstRealEA.cpp + + +Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+FirstRealEA.cpp

+Click on the figure to see the corresponding code. +
In the code, the colors are meaningfull +
The actual code is in boldface and the comment in normal face. +
+
+ + + + +
//----------------------------------------------------------------------------- +
// FirstRealEA.cpp +
//----------------------------------------------------------------------------- +
//* +
// Still an instance of a VERY simple Real-coded  +Genetic Algorithm  +
// (see FirstBitGA.cpp) but now with  +Breeder - and Combined Ops +
// +
//----------------------------------------------------------------------------- +
// standard includes +
#include <stdexcept>  // runtime_error  +
#include <iostream>    +// cout +
#include <strstream>  // ostrstream, +istrstream +
// the general include for eo +
#include <eo>
+ + + + + +
#include <es.h>
+//----------------------------------------------------------------------------- +
// define your individuals +
typedef eoReal<double> Indi; 
+ + + + + +
//----------------------------------------------------------------------------- +
// a simple fitness function that computes +the euclidian norm of a real vector +
// Now in a separate file, and declared as +binary_value(const vector<bool> &) +
#include "real_value.h"
+ + + + + +
//----------------------------------------------------------------------------- +
void main_function(int argc, char **argv) +
{
+ + + + + +
 const unsigned int SEED = 42; // +seed for random number generator +
 const unsigned int T_SIZE = 3; // +size for tournament selection +
 const unsigned int VEC_SIZE = 8; +// Number of object variables in genotypes +
 const unsigned int POP_SIZE = 20; +// Size of population +
 const unsigned int MAX_GEN = 500; +// Maximum number of generation before STOP +
 const unsigned int MIN_GEN = 10;  +// Minimum number of generation before ... +
 const unsigned int STEADY_GEN = +50; // stop after STEADY_GEN gen. without improvelent +
 const float P_CROSS = 0.8; // +Crossover probability +
 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 +
 // 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 +
 const double uniformMutRate = 0.5; +// relative weight for uniform mutation +
 const double detMutRate = 0.5;     +// relative weight for det-uniform mutation +
 const double normalMutRate = 0.5;  +// relative weight for normal mutation
+ + + + + +
 ////////////////////////// +
 //  Random seed +
 ////////////////////////// +
 //reproducible random seed: +if you don't change SEED above,  +
 // you'll aways get the same +result, NOT a random run +
 rng.reseed(SEED);
+ + + + + +
 ///////////////////////////// +
 // Fitness function +
 //////////////////////////// +
 // Evaluation: from a plain +C++ fn to an EvalFunc Object +
 // you need to give the full +description of the function +
 eoEvalFuncPtr<Indi, double, const +vector<double>& > eval(  real_value );
+ + + + + +
 //////////////////////////////// +
 // Initilisation of population +
 //////////////////////////////// +
 // based on a uniform generator +
 eoInitFixedLength<Indi, uniform_generator<double> +> +
         +random(VEC_SIZE, uniform_generator<double>(-1.0, 1.0)); +
   // Initialization of +the population +
 eoPop<Indi> pop(POP_SIZE, random); +

 // and evaluate it in one loop +
 apply<Indi>(eval, pop); // +STL syntax

+ + + + + +
 // sort pop before printing +it! +
 pop.sort(); +
 // Print (sorted) intial population +(raw printout) +
 cout << "Initial Population" +<< endl; +
 cout << pop;
+ + + + + +
 ///////////////////////////////////// +
 // selection and replacement +
 ////////////////////////////////////
+ + + + + +
 // The robust tournament selection +
 eoDetTournamentSelect<Indi> selectOne(T_SIZE); +
// +is now encapsulated in a eoSelectPerc (entage) +
 eoSelectPerc<Indi> select(selectOne);// +by default rate==1
+ + + + + +
 // And we now have the full +slection/replacement - though with  +
 // no replacement (== generational +replacement) at the moment :-) +
 eoNoReplacement<Indi> replace; 
+ + + + + +
 ////////////////////////////////////// +
 // The variation operators +
 //////////////////////////////////////
+ + + + + +
 // uniform chooce on segment +made by the parents +
 eoSegmentCrossover<Indi> xoverS; +
 // uniform choice in hypercube +built by the parents +
 eoHypercubeCrossover<Indi> xoverA; +
 // Combine them with relative +weights +
 eoPropCombinedQuadOp<Indi> xover(xoverS, +segmentRate); +
 xover.add(xoverA, hypercubeRate, +true);
+ + + + + +
+
 // offspring(i) uniformly chosen +in [parent(i)-epsilon, parent(i)+epsilon] +
 eoUniformMutation<Indi>  +mutationU(EPSILON);  +
 // k (=1) coordinates of parents +are uniformly modified +
 eoDetUniformMutation<Indi>  +mutationD(EPSILON);  +
 // all coordinates of parents are normally +modified (stDev SIGMA) +
 eoNormalMutation<Indi>  +mutationN(SIGMA);  +
 // Combine them with relative +weights +
 eoPropCombinedMonOp<Indi> mutation(mutationU, +uniformMutRate); +
 mutation.add(mutationD, detMutRate); +
 mutation.add(mutationN, normalMutRate, +true); +

 // The operators are  encapsulated +into an eoTRansform object +
 eoSGATransform<Indi> transform(xover, +P_CROSS, mutation, P_MUT);

+ + + + + +
+ + + + + +
 ////////////////////////////////////// +
 // termination conditions: use +more than one +
 ///////////////////////////////////// +
 // stop after MAX_GEN generations +
 eoGenContinue<Indi> genCont(MAX_GEN); +
 // do MIN_GEN gen., then stop +after STEADY_GEN gen. without improvement +
 eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, +STEADY_GEN); +
 // stop when fitness reaches +a target (here VEC_SIZE) +
 eoFitContinue<Indi> fitCont(0); +
 // do stop when one of the above +says so +
 eoCombinedContinue<Indi> continuator(genCont); +
 continuator.add(steadyCont); +
 continuator.add(fitCont);
+ + + + + +
 ///////////////////////////////////////// +
 // the algorithm +
 //////////////////////////////////////// +
 // Easy EA requires  +
 // selection, transformation, +eval, replacement, and stopping criterion +
 eoEasyEA<Indi> gga(continuator, +eval, select, transform, replace); +
 // Apply algo to pop - that's +it! +
 cout << "\n              +Here we go\n\n"; +
 gga(pop); +
 
+ + + + + +
 // Print (sorted) intial population +
 pop.sort(); +
 cout << "FINAL Population\n" +<< pop << endl;
+ + + + + +
} +
// A main that catches the exceptions +
int main(int argc, char **argv) +
{ +
#ifdef _MSC_VER +
 //  rng.reseed(42); +
     int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); +
       flag +|= _CRTDBG_LEAK_CHECK_DF; +
     _CrtSetDbgFlag(flag); +
//    _CrtSetBreakAlloc(100); +
#endif +
     try +
     { +
             +main_function(argc, argv); +
     } +
     catch(exception& +e) +
     { +
             +cout << "Exception: " << e.what() << '\n'; +
     } +
     return 1; +
}
+ +
Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Wed Nov +29 07:38:36 2000 + + diff --git a/deprecated/eo/tutorial/html/FirstRealGA.html b/deprecated/eo/tutorial/html/FirstRealGA.html new file mode 100644 index 000000000..f228adfac --- /dev/null +++ b/deprecated/eo/tutorial/html/FirstRealGA.html @@ -0,0 +1,350 @@ + + + + + + FirstRealGA.html + + + +Back to Lesson 1 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+Code for FirstRealGA

+Click on the figure to see the corresponding code.
+In the code, the colors are meaningfull
+The actual code is in boldface and the comment in normal face. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
  + + + + + +
+//-----------------------------------------------------------------------------
+// FirstRealGA.cpp
+//-----------------------------------------------------------------------------
+//*
+// An instance of a VERY simple Real-coded Genetic Algorithm
+//
+//-----------------------------------------------------------------------------
+// standard includes
+#include <stdexcept>  // runtime_error
+#include <iostream>    // cout
+#include <strstream>  // ostrstream, istrstream
+// the general include for eo
+#include <eo>
+
+
+ + + + +
+ +#include <es.h>
+//-----------------------------------------------------------------------------
+// define your individuals
+ typedef eoReal<double> Indi;
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+// a simple fitness function that computes the euclidian norm of a real vector
+//      @param _indi A real-valued individual
+ +double real_value(const Indi & _indi)
+{
+  double sum = 0;
+  for (unsigned i = 0; i < _indi.size(); i++)
+          sum += _indi[i]*_indi[i];
+  return (-sum);                      // maximizing only
+}
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+void main_function(int argc, char **argv)
+{
+
+
+ + + + +
+ +  // all parameters are hard-coded!
+  const unsigned int SEED = 42; // seed for random number generator
+  const unsigned int VEC_SIZE = 8; // Number of object variables in genotypes
+  const unsigned int POP_SIZE = 20; // Size of population
+  const unsigned int T_SIZE = 3; // size for tournament selection
+  const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
+  const float CROSS_RATE = 0.8; // Crossover rate
+  const double EPSILON = 0.01;  // range for real uniform mutation
+  const float MUT_RATE = 0.5;    // mutation rate
+
+
+ + + + +
+ + +  //////////////////////////
+  //  Random seed
+  //////////////////////////
+  //reproducible random seed: if you don't change SEED above,
+  // you'll aways get the same result, NOT a random run
+  rng.reseed(SEED);
+
+
+ + + + +
+ +  /////////////////////////////
+  // Fitness function
+  ////////////////////////////
+  // Evaluation: from a plain C++ fn to an EvalFunc Object
+  eoEvalFuncPtr<Indi> eval(  real_value );
+
+
+ + + + +
+ +  ////////////////////////////////
+  // Initilisation of population
+  ////////////////////////////////
+  // declare the population
+  eoPop<Indi> pop;
+  // fill it!
+  for (unsigned int igeno=0; igeno<POP_SIZE; igeno++)
+      {
+          Indi v;                  // void individual, to be filled
+          for (unsigned ivar=0; ivar<VEC_SIZE; ivar++)
+              {
+                  double r = 2*rng.uniform() - 1; // new value, random in [-1,1)
+                  v.push_back(r);            // append that random value to v
+              }
+          eval(v);                                  // evaluate it
+          pop.push_back(v);                // and put it in the population
+      }
+
+
+ + + + +
+ +  // sort pop before printing it!
+  pop.sort();
+  // Print (sorted) intial population (raw printout)
+  cout << "Initial Population" << endl;
+  cout << pop;
+
+
+ + + + +
+ +  /////////////////////////////////////
+  // selection and replacement
+  ////////////////////////////////////
+
+
+ + + + +
+ +  // The robust tournament selection
+  eoDetTournamentSelect<Indi> select(T_SIZE);            // T_SIZE in [2,POP_SIZE]
+
+
+ + + + +
+ +  // eoSGA uses generational replacement by default
+  // so no replacement procedure has to be given
+
+
+ + + + +
+ + +
+ + + + +
+ +  //////////////////////////////////////
+  // termination condition
+  /////////////////////////////////////
+  // stop after MAX_GEN generations
+  eoGenContinue<Indi> continuator(MAX_GEN);
+  
+
+
+ + + + +
+ +  //////////////////////////////////////
+  // The variation operators
+  //////////////////////////////////////
+
+
+ + + + +
+ +  // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon]
+  eoUniformMutation<Indi>  mutation(EPSILON);
+
+
+ + + + +
+ +  // offspring(i) is a linear combination of parent(i)
+  eoSegmentCrossover<Indi> xover;
+
+
+ + + + +
+ +  /////////////////////////////////////////
+  // the algorithm
+  ////////////////////////////////////////
+  // standard Generational GA requires
+  // selection, evaluation, crossover and mutation, stopping criterion
+
+  eoSGA<Indi> gga(select, xover, CROSS_RATE, mutation, MUT_RATE,
+                                    eval, continuator);
+  // Apply algo to pop - that's it!
+  gga(pop);
+  
+
+
+ + + + +
+ +  // Print (sorted) intial population
+  pop.sort();
+  cout << "FINAL Population\n" << pop << endl;
+
+
+ + + + +
+ +}
+// A main that catches the exceptions
+int main(int argc, char **argv)
+{
+#ifdef _MSC_VER
+  //  rng.reseed(42);
+      int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
+        flag |= _CRTDBG_LEAK_CHECK_DF;
+      _CrtSetDbgFlag(flag);
+//    _CrtSetBreakAlloc(100);
+#endif
+      try
+      {
+              main_function(argc, argv);
+      }
+      catch(exception& e)
+      {
+              cout << "Exception: " << e.what() << '\n';
+      }
+      return 1;
+}
+
+
Back to Lesson 1 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+
Last +modified: Sun Nov 19 08:31:29 2000 + + + diff --git a/deprecated/eo/tutorial/html/Firstmerge.html b/deprecated/eo/tutorial/html/Firstmerge.html new file mode 100644 index 000000000..2c4e7b9c5 --- /dev/null +++ b/deprecated/eo/tutorial/html/Firstmerge.html @@ -0,0 +1,286 @@ + + + + + + Differences + + +Back to Lesson 1 - +Tutorial +main page - +Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+FirstBitGA and FirstRealGA: differences

+Below is a comparison of the codes for both algorithms (comments have been +removed). +
Warning: the pink +background here denotes the differences, not the section  of +the algorithm, which is only recalled by the color of the text! +
These differences are limited to +
    +
  • +the declaration of the type of the genotypes,
  • + +
  • +the fitness function (what did you expect +:-),
  • + +
  • +the initialization (and if you look carefully, +you'll find out that only a small part of the initialization is different, +as both genotypes are eoFixedLength objects) and of course
  • + +
  • +the choice of variation operators (including +the parameter for the mutation).
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#include +<stdexcept > +
#include <iostream> +
#include <strstream> +
#include <eo>
#include +<stdexcept > +
#include <iostream> +
#include <strstream> +
#include <eo>
#include <es.h>
+typedef eoReal<double> Indi;
#include <ga.h>
+typedef eoBit<double> Indi;
double +real_value(const Indi & _indi) +
{ +
  double +sum = 0; +
  for (unsigned +i = 0; i < _indi.size(); i++) +
      +sum += _indi[i]*_indi[i]; +
  return +(-sum);   // maximizing +
}
double +binary_value(const Indi & _indi) +
{ +
  double +sum = 0; +
  for (unsigned +i = 0; i < _indi.size(); i++) +
      +sum += _indi[i]; +
  return +(sum); +
}
void +main_function(int argc, char **argv) +
{ +
const unsigned +int SEED = 42; +
const unsigned +int VEC_SIZE = 8; +
const unsigned +int POP_SIZE = 20; +
const unsigned +int T_SIZE = 3; +
const unsigned +int MAX_GEN = 500; +
const float +CROSS_RATE = 0.8; +
const float +MUT_RATE = 0.5;
void +main_function(int argc, char **argv) +
{ +
const unsigned +int SEED = 42; +
const unsigned +int VEC_SIZE = 8; +
const unsigned +int POP_SIZE = 20; +
const unsigned +int T_SIZE = 3; +
const unsigned +int MAX_GEN = 500; +
const float +CROSS_RATE = 0.8; +
const float +MUT_RATE = 0.5;
const +double EPSILON = 0.01;const +double P_MUT_PER_BIT = 0.01;
eoEvalFuncPtr<Indi> +eval(real_value);eoEvalFuncPtr<Indi> +eval(binary_value);
eoPop<Indi> +pop; +
for (unsigned +int igeno=0; igeno<POP_SIZE; igeno++) +
  { +
    +Indi v; +
    +for (unsigned ivar=0; ivar<VEC_SIZE; ivar++) +
      +{
eoPop<Indi> +pop; +
for (unsigned +int igeno=0; igeno<POP_SIZE; igeno++) +
  { +
    +Indi v; +
    +for (unsigned ivar=0; ivar<VEC_SIZE; ivar++) +
      +{
        +double r = 2*rng.uniform() - 1;        +bool r = rng.flip(); 
        +v.push_back(r); // +
      +} +
    +eval(v); +
    +pop.push_back(v); +
  } +
pop.sort(); +
cout << +"Initial Population" << endl; +
cout << +pop; +
eoDetTournament<Indi> +select(T_SIZE); +
eoGenContinue<Indi> +continuator(MAX_GEN);
        +v.push_back(r); // +
      +} +
    +eval(v); +
    +pop.push_back(v); +
  } +
pop.sort(); +
cout << +"Initial Population" << endl; +
cout << +pop; +
eoDetTournament<Indi> +select(T_SIZE); +
eoGenContinue<Indi> +continuator(MAX_GEN);
eoUniformMutation<Indi>  +mutation(EPSILON); +
eoSegmentCrossover<Indi> +xover;
eoBitMutation<Indi>  +mutation(P_MUT_PER_BIT); +
eo1PtBitXover<Indi> +xover;
+eoSGA<Indi> +gga(select, xover, CROSS_RATE, +
                +mutation, MUT_RATE, eval, continuator); +
gga(pop); +
pop.sort(); +
cout << +"FINAL Population\n" << pop << endl; +
} +
int main(int +argc, char **argv) +
{ +
... [technical +code removed] +
}
+eoSGA<Indi> +gga(select, xover, CROSS_RATE, +
                +mutation, MUT_RATE, eval, continuator); +
gga(pop); +
pop.sort(); +
cout << +"FINAL Population\n" << pop << endl; +
} +
int main(int +argc, char **argv) +
{ +
[... technical +code removed ] +
}
+ +
Back to Lesson 1 - +Tutorial +main page - +Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Tue Nov 7 07:49:47 CET 2000 + + diff --git a/deprecated/eo/tutorial/html/NoWay.html b/deprecated/eo/tutorial/html/NoWay.html new file mode 100644 index 000000000..74d7204cc --- /dev/null +++ b/deprecated/eo/tutorial/html/NoWay.html @@ -0,0 +1,77 @@ + + + + + + Tutorial: Solutions + + +Tutorial main page - +Algorithm-Based +- Component-Based - Programming +hints -EO +documentation +
+
+
+

+Tutorial:

+ +
Solutions of exercises
+ +

No, we won't +provide +any +hypertext link directly to the correct code, so you get a chance +to find out the solution by yourself without immediately going there  +:-))) +

What you should do: +

    +
  • +copy the code of an example onto another name (e.g. mytest.cpp)
  • + +
  • +edit and modify mytest.cpp +according to the corresponding instructions of the exercise
  • + +
  • +compile mytest.cpp by typing +make +mytest at system prompt, and you will hopefully get an +executable file named mytest +(for Unix systems: if eventually someone tells me how to do that in Windows, +apart that you'll probably end up with an executable file named mytest.exe...).
  • +
+ +
+
What you may do later: +

All solutions to exercises are in the same +sub-dir of the Tutorial directory than the example files (i.e. +Lesson1 for Lesson1, yes!) and are named exerciseN.p.cpp +where N is the lesson number and p the exercise number. Hence you may browse +through the code, eventually modifying it, and then simply type, in the +corresponding directory, +
... % make exerciseN.p +
which will compile file exerciseN.p.cpp +into executable exerciseN.p +(for Unix systems: if eventually someone tells me how to do that in Windows, +you'll probably end up with an executable file named exerciseN.p.exe). +

+


+
What you may not do: +
Complain that it does not work under Windows :-)
+ +
Tutorial main page - +Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Fri Nov 3 18:49:12 CET 2000 + + diff --git a/deprecated/eo/tutorial/html/OneMaxEA.html b/deprecated/eo/tutorial/html/OneMaxEA.html new file mode 100644 index 000000000..47102a452 --- /dev/null +++ b/deprecated/eo/tutorial/html/OneMaxEA.html @@ -0,0 +1,360 @@ + + + + + + Templates/OneMaxEA.cpp + + +Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+
+

+Templates/OneMaxEA.cpp

+The places where you have to put some code are on pink +background.. Only the the character +colors have the usual meaning. +
+ + + + +
/** -*- mode: c++; c-indent-level: +4; c++-member-init-indent: 8; comment-column: 35; -*- +
The above line is usefulin Emacs-like editors +
*/ +
/* +
Template for creating a new representation +in EO +
================================================ +
This is the template main file. +
It includes all other files that have been +generated by the script create.sh +
so it is the only file to compile. +
In case you want to build up a separate library +for your new Evolving Object, +
you'll need some work - follow what's done +in the src/ga dir, used in the +
main file BitEA in tutorial/Lesson4 dir. +
Or you can wait until we do it :-) +
*/ +
// Miscilaneous include and declaration  +
#include <iostream> +
using namespace std; +
// eo general include +
#include "eo" +
// the real bounds (not yet in general eo +include) +
#include "utils/eoRealVectorBounds.h" +
// include here whatever specific files for +your representation +
// Basically, this should include at least +the following +
/** definition of representation:  +
* class eoOneMax MUST derive from EO<FitT> +for some fitness +
*/
+ + + + + +
#include "eoOneMax.h" +
/** definition of initilizqtion:  +
* class eoOneMaxInit MUST derive from eoInit<eoOneMax> +
*/
+ + + + + +
#include "eoOneMaxInit.h" +
/** definition of evaluation:  +
* class eoOneMaxEvalFunc MUST derive from +eoEvalFunc<eoOneMax> +
* and should test for validity before doing +any computation +
* see tutorial/Templates/evalFunc.tmpl +
*/
+ + + + + +
#include "eoOneMaxEvalFunc.h" +
// GENOTYPE    eoOneMax ***MUST*** +be templatized over the fitness
+ + + + + +
// START fitness type: double or eoMaximizingFitness +if you are maximizing +
//                                        +eoMinimizingFitness if you are minimizing +
typedef eoMinimizingFitness MyFitT ; // +type of fitness  +
// END fitness type
+ + + + + +
+ + + + + +
// Then define your EO objects using that +fitness type +
typedef eoOneMax<MyFitT> Indi;           +// ***MUST*** derive from EO 
+ + + + + +
// create an initializer +
#include "make_genotype_OneMax.h" +
eoInit<Indi> & make_genotype(eoParser& +_parser, eoState&_state, Indi _eo) +
{ +
 return do_make_genotype(_parser, +_state, _eo); +
+ + + + + +
// and the variation operaotrs +
#include "make_op_OneMax.h" +
eoGenOp<Indi>&  make_op(eoParser& +_parser, eoState& _state, eoInit<Indi>& _init) +
{ +
 return do_make_op(_parser, _state, +_init); +
}
+ + + + + +
// Use existing modules to define representation +independent routines +
// These are parser-based definitions of +objects +
// how to initialize the population  +
// it IS representation independent if an +eoInit is given +
#include <do/make_pop.h> +
eoPop<Indi >&  make_pop(eoParser& +_parser, eoState& _state, eoInit<Indi> & _init) +
{ +
 return do_make_pop(_parser, _state, +_init); +
}
+ + + + + +
// the stopping criterion +
#include <do/make_continue.h> +
eoContinue<Indi>& make_continue(eoParser& +_parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval) +
{ +
 return do_make_continue(_parser, +_state, _eval); +
}
+ + + + + +
// outputs (stats, population dumps, ...) +
#include <do/make_checkpoint.h> +
eoCheckPoint<Indi>& make_checkpoint(eoParser& +_parser, eoState& _state, eoEvalFuncCounter<Indi>& _eval, eoContinue<Indi>& +_continue)  +
{ +
 return do_make_checkpoint(_parser, +_state, _eval, _continue); +
}
+ + + + + +
// evolution engine (selection and replacement) +
#include <do/make_algo_scalar.h> +
eoAlgo<Indi>&  make_algo_scalar(eoParser& +_parser, eoState& _state, eoEvalFunc<Indi>& _eval, eoContinue<Indi>& +_continue, eoGenOp<Indi>& _op) +
{ +
 return do_make_algo_scalar(_parser, +_state, _eval, _continue, _op); +
}
+ + + + + +
// simple call to the algo. stays there for +consistency reasons  +
// no template for that one +
#include <do/make_run.h> +
// the instanciating fitnesses +
#include <eoScalarFitness.h> +
void run_ea(eoAlgo<Indi>& _ga, +eoPop<Indi>& _pop) +
{ +
 do_run(_ga, _pop); +
} +
// checks for help demand, and writes the +status file +
// and make_help; in libutils +
void make_help(eoParser & _parser); +
// now use all of the above, + representation +dependent things +
int main(int argc, char* argv[]) +
{ +
 try +
 { +
 eoParser parser(argc, argv);   +// for user-parameter reading +
 eoState state;       +// keeps all things allocated
+ + + + + +
      // +The fitness +
      ////////////// +
   eoOneMaxEvalFunc<Indi> +plainEval /* (varType  _anyVariable) */;; +
    // turn that object +into an evaluation counter +
   eoEvalFuncCounter<Indi> +eval(plainEval);
+ + + + + +
  // the genotype - through a +genotype initializer +
 eoInit<Indi>& init = make_genotype(parser, +state, Indi());
+ + + + + +
  // Build the variation operator +(any seq/prop construct) +
 eoGenOp<Indi>& op = make_op(parser, +state, init); +
  //// 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 +
  //////////////////////////////////////////////
+ + + + + +
  // initialize the population +
  // yes, this is representation +indepedent once you have an eoInit +
 eoPop<Indi>& pop    += make_pop(parser, state, init);
+ + + + + +
  // stopping criteria +
 eoContinue<Indi> & term = +make_continue(parser, state, eval);
+ + + + + +
  // output +
 eoCheckPoint<Indi> & checkpoint += make_checkpoint(parser, state, eval, term);
+ + + + + +
  // algorithm (need the operator!) +
 eoAlgo<Indi>& ga = make_algo_scalar(parser, +state, eval, checkpoint, op); +
  ///// End of construction of +the algorithm +
  ///////////////////////////////////////// +
  // to be called AFTER all parameters +have been read!!! +
 make_help(parser); +
  //// GO +
  ///////
+ + + + + +
  // evaluate intial population +AFTER help and status in case it takes time +
 apply<Indi>(eval, pop); +
  // if you want to print it +out +
//    cout << "Initial +Population\n"; +
//    pop.sortedPrintOn(cout); +
//    cout << endl;
+ + + + + +
 run_ea(ga, pop); // run the +ga +
 cout << "Final Population\n"; +
 pop.sortedPrintOn(cout); +
 cout << endl; +
 } +
 catch(exception& e) +
 { +
     cout << +e.what() << endl; +
 } +
 return 0; +
}
+ +
Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Sat May +4 07:37:41 2002 + + diff --git a/deprecated/eo/tutorial/html/SecondBitEA.html b/deprecated/eo/tutorial/html/SecondBitEA.html new file mode 100644 index 000000000..ea043f026 --- /dev/null +++ b/deprecated/eo/tutorial/html/SecondBitEA.html @@ -0,0 +1,569 @@ + + + + + + SecondBitEA.cpp + + + +Back to Lesson 3 - Tutorial +main page - Algorithm-Based - Component-Based +- +Programming +hints - EO +documentation +
+
+
+

+SecondBitEA.cpp

+Click on the figure to see the corresponding code. +
In the code, the colors are meaningfull +
The actual code is in boldface and the comment in normal face. +

For this particular program, as all new lines are concerned with program +parameter input and information output, the font +color for program-parameter-related sections will refer +to the section where the parameters are used whereas the background +color will remain blue. +

+
+ + + + +
//----------------------------------------------------------------------------- +
// SecondGA.cpp +
//----------------------------------------------------------------------------- +
//* +
// Same code than FirstBitEA as far as Evolutionary +Computation is concerned +
// but now you learn to enter the parameters +in a more flexible way +
// and to twidle the output to your preferences! +
//----------------------------------------------------------------------------- +
// standard includes +
#include <stdexcept>  // runtime_error  +
#include <iostream>   // +cout +
#include <strstream>  // ostrstream, +istrstream +
#include <fstream> +
// the general include for eo +
#include <eo>
+ + + + + +
// a simple fitness function that computes +the number of ones of a bitstring +
#include "binary_value.h"
+ + + + + +
//----------------------------------------------------------------------------- +
// define your genotype and fitness types +
typedef eoBit<double> Indi;
+ + + + + +
// the main_function: nothing changed(!), +except variable initialization +
void main_function(int argc, char **argv) +
{
+ + + + + + + + + +
//----------------------------------------------------------------------------- +
// instead of having all values of useful +parameters as constants, read them: +
// either on the command line (--option=value +or -o=value) +
//        +or in a parameter file (same syntax, order independent,  +
//                                    +# = usual comment character  +
//        +or in the environment (TODO) +

// First define a parser from the command-line +arguments +
eoParser +parser(argc, argv); +

// For each parameter, define Parameter, read +it through the parser, +
// and assign the value to the variable +
+
eoValueParam<uint32> seedParam(time(0), +"seed", "Random number seed", 'S'); +
parser.processParam( +seedParam ); +
unsigned seed += seedParam.value(); +

// decription +of genotype +
eoValueParam<unsigned int>& vecSizeParam(8, +"vecSize", "Genotype size",'V'); +
parser.processParam( vecSizeParam, "Representation" +); +
unsigned vecSize = vecSizeParam.value(); +

// parameters for evolution engine +
eoValueParam<unsigned int>& popSizeParam(10, +"popSize", "Population size",'P'); +
parser.processParam( popSizeParam, "Evolution +engine" ); +
unsigned popSize = popSizeParam.value(); +

eoValueParam<unsigned int>& tSizeParam(10, +"tSize", "Tournament size",'T'); +
parser.processParam( seedParam ); +
unsigned tSize = tSizeParam.value(); +
+
   // init and stop +
eoValueParam<string> loadNameParam("", +"Load","A save file to restart from",'L'); +
parser.processParam( loadNameParam, "Persistence" +); +
string loadName = loadNameParam.value(); +

eoValueParam<unsigned int> maxGenParam(100, +"maxGen", "Maximum number of generations",'G'); +
parser.processParam( maxGenParam, "Stopping +criterion" ); +
unsigned maxGen = maxGenParam.value(); +

eoValueParam<unsigned int> minGenParam(100, +"minGen", "Minimum number of generations",'g'); +
parser.processParam( minGenParam, "Stopping +criterion" ); +
unsigned minGen = minGenParam.value(); +

eoValueParam<unsigned int> steadyGenParam(100, +"steadyGen", "Number of generations with no improvement",'s'); +
parser.processParam( steadyGenParam, "Stopping +criterion" ); +
unsigned steadyGen = steadyGenParam.value(); +

// operators probabilities at the algorithm +level +
eoValueParam<double> pCrossParam(0.6, +"pCross", "Probability of Crossover", 'C');  +
parser.processParam( pCrossParam, "Genetic +Operators" ); +
double pCross = pCrossParam.value(); +

eoValueParam<double> pMutParam(0.1, +"pMut", "Probability of Mutation", 'M'); +
parser.processParam( pMutParam, "Genetic +Operators" ); +
double pMut = pMutParam.value(); +

// relative rates for crossovers +
eoValueParam<double> onePointRateParam(1, +"onePointRate", "Relative rate for one point crossover", '1'); +
parser.processParam( onePointRateParam, +"Genetic Operators" ); +
double onePointRate = onePointRateParam.value(); +

eoValueParam<double> twoPointsRateParam(1, +"twoPointRate", "Relative rate for two point crossover", '2'); +
parser.processParam( twoPointsRateParam, +"Genetic Operators" ); +
double twoPointsRate = twoPointsRateParam.value(); +

eoValueParam<double> uRateParam(2, "uRate", +"Relative rate for uniform crossover", 'U'); +
parser.processParam( uRateParam, "Genetic +Operators" ); +
double URate =  uRateParam.value(); +

// relative rates and private parameters for +mutations; +
eoValueParam<double> pMutPerBitParam(0.01, +"pMutPerBit", "Probability of flipping 1 bit in bit-flip mutation", 'b'); +
parser.processParam( pMutPerBitParam, +"Genetic Operators" ); +
double pMutPerBit = pMutPerBitParam.value(); +

eoValueParam<double> bitFlipRateParam(0.01, +"bitFlipRate", "Relative rate for bit-flip mutation", 'B'); +
parser.processParam( bitFlipRateParam, +"Genetic Operators" ); +
double bitFlipRate =  bitFlipRateParam.value(); +

eoValueParam<double> oneBitRateParam(0.01, +"oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); +
parser.processParam( oneBitRateParam, +"Genetic Operators" ); +
double oneBitRate = oneBitRateParam.value(); +

// the name of the "status" file where all +actual parameter values will be saved +
string str_status = parser.ProgramName() ++ ".status"; // default value +
eoValueParam<string> statusParam(str_status.c_str(), +"status","Status file",'S'); +
parser.processParam( statusParam, "Persistence" +); +

// do the following AFTER ALL PARAMETERS HAVE +BEEN PROCESSED +
// i.e. in case you need parameters somewhere +else, postpone these +
if (parser.userNeedsHelp()) +
   { +
      parser.printHelp(cout); +
      exit(1); +
   } +
if (statusParam.value() != "") +
   { +
      ofstream +os(statusParam.value().c_str()); +
      os << +parser; // and you can use that file as parameter file +
   }

+ + + + + +
 ///////////////////////////// +
 // Fitness function +
 //////////////////////////// +
 // Evaluation: from a plain +C++ fn to an EvalFunc Object ... +
 eoEvalFuncPtr<Indi, double, const +vector<bool>& > plainEval( binary_value ); +
// ... to an object +that counts the nb of actual evaluations +
 eoEvalFuncCounter<Indi> eval(plainEval);
+ + + + + +
 //////////////////////////////// +
 // Initilisation of population +
 //////////////////////////////// +
 // Either load or initialize +
 // create an empty pop +
 eoPop<Indi> pop; +
 // create a state for reading +
 eoState inState; // a state +for loading - WITHOUT the parser +
// register the rng +and the pop in the state, so they can be loaded, +
 // and the present run will +be the exact conitnuation of the saved run +
 // eventually with different +parameters +
 inState.registerObject(rng); +
 inState.registerObject(pop); +

if (load_name +!= "") +
     { +
         +inState.load(load_name); //  load the pop and the rng +
       // +the fitness is read in the file:  +
       // +do only evaluate the pop if the fitness has changed +
     } +
 else +
     { +
         +rng.reseed(seed); +
       // +a Indi random initializer +
       // +based on eoUniformGenerator class (see utils/eoRndGenerators.h) +
       eoUniformGenerator<bool> +uGen; +
       eoInitFixedLength<Indi> +random(vecSize, uGen); +
       // +Init pop from the randomizer: need to use the append function +
         +pop.append(popSize, random);  +
       // +and evaluate pop (STL syntax)  +
         +apply<Indi>(eval, pop); +
     } // end +of initialization of the population

+ + + + + +
 // sort pop for pretty printout +
 pop.sort(); +
 // Print (sorted) intial population +(raw printout) +
 cout << "Initial Population" +<< endl << pop << endl;
+ + + + + +
 ///////////////////////////////////// +
 // selection and replacement +
 ////////////////////////////////////
+ + + + + +
 // The robust tournament selection +
 eoDetTournamentSelect<Indi> selectOne(tSize);       +// tSize in [2,POPSIZE] +
 // is now encapsulated in a +eoSelectPerc (entage) +
 eoSelectPerc<Indi> select(selectOne); +
 // or eoSelectPerc<Indi> select(selectOne, +rate);  +
 // but by default rate==1
+ + + + + +
 // And we now have the full +slection/replacement - though with  +
 // the same generational replacement +at the moment :-) +
 eoGenerationalReplacement<Indi> +replace; 
+ + + + + +
 ////////////////////////////////////// +
 // The variation operators +
 //////////////////////////////////////
+ + + + + +
 // 1-point crossover for bitstring +
 eo1PtBitXover<Indi> xover1; +
 // uniform crossover for bitstring +
 eoUBitXover<Indi> xoverU; +
 // 2-pots xover +
 eoNPtsBitXover<Indi> xover2(2); +
 // Combine them with relative +rates +
 eoPropCombinedQuadOp<Indi> xover(xover1, +onePointRate); +
 xover.add(xoverU, URate); +
 xover.add(xover2, twoPointsRate, +true);
+ + + + + +
 // standard bit-flip mutation +for bitstring +
 eoBitMutation<Indi>  mutationBitFlip(pMutPerBit); +
 // mutate exactly 1 bit per +individual +
 eoDetBitFlip<Indi> mutationOneBit;  +
 // Combine them with relative +rates +
 eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, +bitFlipRate); +
 mutation.add(mutationOneBit, oneBitRate, +true); +
 // The operators are  encapsulated +into an eoTRansform object +
 eoSGATransform<Indi> transform(xover, +pCross, mutation, pMut);
+ + + + + +
 ////////////////////////////////////// +
 // termination condition see +FirstBitEA.cpp +
 ///////////////////////////////////// +
 eoGenContinue<Indi> genCont(maxGen); +
 eoSteadyFitContinue<Indi> steadyCont(minGen, +steadyGen); +
 eoFitContinue<Indi> fitCont(vecSize); +
 eoCombinedContinue<Indi> continuator(genCont); +
 continuator.add(steadyCont); +
 continuator.add(fitCont);
+ + + + + +
 // but now you want to make +many different things every generation  +
 // (e.g. statistics, plots, +...). +
 // the class eoCheckPoint is +dedicated to just that: +
 // Declare a checkpoint (from +a continuator: an eoCheckPoint  +
 // IS AN eoContinue and will +be called in the loop of all algorithms) +
 eoCheckPoint<Indi> checkpoint(continuator); +

  // +Create a counter parameter +
     eoValueParam<unsigned> +generationCounter(0, "Gen."); +

   // +Create an incrementor (sub-class of eoUpdater). Note that the  +
     // parameter's +value is passed by reference,  +
     // so every +time the incrementer is updated (every generation), +
     // the data +in generationCounter will change. +
     eoIncrementor<unsigned> +increment(generationCounter.value()); +
  // +Add it to the checkpoint,  +
     // so the +counter is updated (here, incremented) every generation +
     checkpoint.add(increment); +
  // +now some statistics on the population: +
     // Best fitness +in population +
     eoBestFitnessStat<Indi> +bestStat; +
     // Second +moment stats: average and stdev +
     eoSecondMomentStats<Indi> +SecondStat; +
   // +Add them to the checkpoint to get them called at the appropriate time +
     checkpoint.add(bestStat); +
     checkpoint.add(SecondStat); +
     // The Stdout +monitor will print parameters to the screen ... +
     +eoStdoutMonitor monitor(false); +

     // 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); +
     monitor.add(eval); +// +because now eval is an eoEvalFuncCounter! +
     monitor.add(bestStat); +
     monitor.add(SecondStat); +
     // A file +monitor: will print parameters to ... a File, yes, you got it! +
     eoFileMonitor +fileMonitor("stats.xg", " "); +

     // the checkpoint +mechanism can handle multiple monitors +
     checkpoint.add(fileMonitor); +
     // the fileMonitor +can monitor parameters, too, but you must tell it! +
     fileMonitor.add(generationCounter); +
     fileMonitor.add(bestStat); +
     fileMonitor.add(SecondStat); +
     // Last type +of item the eoCheckpoint can handle: state savers: +
     +eoState outState; +
     // Register +the algorithm into the state +
     +outState.registerObject(parser); +
     outState.registerObject(pop); +
     outState.registerObject(rng); +
     // and feed +the state to state savers +
// save +state every 100th  generation +
     eoCountedStateSaver +stateSaver1(100, outState, "generation");  +
     // save state +every 1 seconds  +
     eoTimedStateSaver    +stateSaver2(1, outState, "time");  +
  // +Don't forget to add the two savers to the checkpoint +
     checkpoint.add(stateSaver1); +
     checkpoint.add(stateSaver2); +
     // and that's +it for the (control and) output

+ + + + + +
 ///////////////////////////////////////// +
 // the algorithm +
 //////////////////////////////////////// +
 // Easy EA requires  +
 // stopping criterion, eval, selection, +transformation, replacement +
 eoEasyEA<Indi> gga(checkpoint, +eval, select, transform, replace); +
 // Apply algo to pop - that's +it! +
 gga(pop);
+ + + + + +
 // Print (sorted) final population +
 pop.sort(); +
 cout << "FINAL Population\n" +<< pop << endl;
+ + + + + +
} +
// A main that catches the exceptions +
int main(int argc, char **argv) +
{ +
#ifdef _MSC_VER +
     int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); +
       flag +|= _CRTDBG_LEAK_CHECK_DF; +
     _CrtSetDbgFlag(flag); +
//    _CrtSetBreakAlloc(100); +
#endif +
     try +
     { +
             +main_function(argc, argv); +
     } +
     catch(exception& +e) +
     { +
             +cout << "Exception: " << e.what() << '\n'; +
     } +
     return 1; +
}
+ +


Back to Lesson 3 - Tutorial +main page - Algorithm-Based - Component-Based +- +Programming +hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Sun Nov +26 09:31:04 2000 + + diff --git a/deprecated/eo/tutorial/html/SecondRealEA.html b/deprecated/eo/tutorial/html/SecondRealEA.html new file mode 100644 index 000000000..7882e7bad --- /dev/null +++ b/deprecated/eo/tutorial/html/SecondRealEA.html @@ -0,0 +1,468 @@ + + + + + + SecondRealEA + + +Back to Lesson 3 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+
+

+SecondRealEA

+Click on the figure to see the corresponding code.
+In the code, the colors are meaningfull
+The actual code is in boldface and the comment in normal face. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
  + + + + + +
+//-----------------------------------------------------------------------------
+// SecondRealEA.cpp
+//-----------------------------------------------------------------------------
+//*
+// Same code than FirstBitEA as far as Evolutionary Computation is concerned
+// but now you learn to enter the parameters in a more flexible way
+// (also slightly different than in SecondBitEA.cpp)
+// and to twidle the output to your preferences (as in SecondBitEA.cpp)
+//
+//-----------------------------------------------------------------------------
+// standard includes
+#include <stdexcept>  // runtime_error
+#include <iostream>    // cout
+#include <strstream>  // ostrstream, istrstream
+// the general include for eo
+#include <eo>
+#include <es.h>
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+// define your individuals
+typedef eoReal<eoMinimizingFitness> Indi;
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+// a simple fitness function that computes the euclidian norm of a real vector
+// Now in a separate file, and declared as binary_value(const vector<bool> &)
+#include "real_value.h"
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+void main_function(int argc, char **argv)
+{
+
+
+ + + + +
+ +//-----------------------------------------------------------------------------
+// instead of having all values of useful parameters as constants, read them:
+// either on the command line (--option=value or -o=value)
+//        or in a parameter file (same syntax, order independent,
+//                                                        # = usual comment character
+//        or in the environment (TODO)
+  // First define a parser from the command-line arguments
+  eoParser parser(argc, argv);
+  
+  // For each parameter, you can in on single line
+  // define the parameter, read it through the parser, and assign it
+  
+ +  unsigned seed = parser.createParam(unsigned(time(0)), "seed", "Random number seed", 'S').value(); // will be in default section General
+  
+  // description of genotype
+  unsigned vecSize = parser.createParam(unsigned(8), "vecSize", "Genotype size",'V', "Representation" ).value();
+    // parameters for evolution engine
+      unsigned popSize = parser.createParam(unsigned(10), "popSize", "Population size",'P', "Evolution engine" ).value();
+      unsigned tSize = parser.createParam(unsigned(2), "tSize", "Tournament size",'T', "Evolution Engine" ).value();
+    // init and stop
+      string loadName = parser.createParam(string(""), "Load","A save file to restart from",'L', "Persistence" ).value();
+
+      unsigned maxGen = parser.createParam(unsigned(100), "maxGen", "Maximum number of generations",'G', "Stopping criterion" ).value();
+      unsigned minGen = parser.createParam(unsigned(100), "minGen", "Minimum number of generations",'g', "Stopping criterion" ).value();
+      unsigned steadyGen = parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion" ).value();
+    // operators probabilities at the algorithm level
+      double pCross = parser.createParam(double(0.6), "pCross", "Probability of Crossover", 'C', "Genetic Operators" ).value();
+      double pMut = parser.createParam(double(0.1), "pMut", "Probability of Mutation", 'M', "Genetic Operators" ).value();
+    // relative rates for crossovers
+      double hypercubeRate = parser.createParam(double(1), "hypercubeRate", "Relative rate for hypercube crossover", '\0', "Genetic Operators" ).value();
+      double segmentRate = parser.createParam(double(1), "segmentRate", "Relative rate for segment crossover", '\0', "Genetic Operators" ).value();
+      // internal parameters for the mutations
+      double EPSILON = parser.createParam(double(0.01), "EPSILON", "Width for uniform mutation", '\0', "Genetic Operators" ).value();
+      
+      double SIGMA = parser.createParam(double(0.3), "SIGMA", "Sigma for normal mutation", '\0', "Genetic Operators" ).value();
+    // relative rates for mutations
+      double uniformMutRate = parser.createParam(double(1), "uniformMutRate", "Relative rate for uniform mutation", '\0', "Genetic Operators" ).value();
+      double detMutRate = parser.createParam(double(1), "detMutRate", "Relative rate for det-uniform mutation", '\0', "Genetic Operators" ).value();
+      double normalMutRate = parser.createParam(double(1), "normalMutRate", "Relative rate for normal mutation", '\0', "Genetic Operators" ).value();
+      // the name of the "status" file where all actual parameter values will be saved
+      string str_status = parser.ProgramName() + ".status"; // default value
+      string statusName = parser.createParam(str_status, "status","Status file",'S', "Persistence" ).value();
+    // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED
+    // i.e. in case you need parameters somewhere else, postpone these
+      if (parser.userNeedsHelp())
+          {
+              parser.printHelp(cout);
+              exit(1);
+          }
+      if (statusName != "")
+          {
+ofstream os(statusName.c_str());
+os << parser; // and you can use that file as parameter file
+          }
+
+
+ + + + +
+ +  /////////////////////////////
+  // Fitness function
+  ////////////////////////////
+  // Evaluation: from a plain C++ fn to an EvalFunc Object
+  // you need to give the full description of the function
+  eoEvalFuncPtr<Indi, double, const vector<double>& > plainEval(  real_value );
+  // ... to an object that counts the nb of actual evaluations
+  eoEvalFuncCounter<Indi> eval(plainEval);
+
+
+ + + + +
+ +  ////////////////////////////////
+  // Initilisation of population
+  ////////////////////////////////
+  // Either load or initialize
+  // create an empty pop
+  eoPop<Indi> pop;
+  // create a state for reading
+  eoState inState; // a state for loading - WITHOUT the parser
+  // register the rng and the pop in the state, so they can be loaded,
+  // and the present run will be the exact conitnuation of the saved run
+  // eventually with different parameters
+  inState.registerObject(rng);
+  inState.registerObject(pop);
+      
+  if (loadName != "")
+      {
+          inState.load(loadName); //  load the pop and the rng
+          // the fitness is read in the file:
+          // do only evaluate the pop if the fitness has changed
+      }
+  else
+      {
+          rng.reseed(seed);
+          // a Indi random initializer
+          // based on boolean_generator class (see utils/rnd_generator.h)
+          eoUniformGenerator<double> uGen(-1.0, 1.0);
+          eoInitFixedLength<Indi> random(vecSize, uGen);
+          // Init pop from the randomizer: need to use the append function
+          pop.append(popSize, random);          
+          // and evaluate pop (STL syntax)      
+          apply<Indi>(eval, pop);
+      } // end of initializatio of the population
+
+
+ + + + +
+ +  // sort pop before printing it!
+  pop.sort();
+  // Print (sorted) intial population (raw printout)
+  cout << "Initial Population" << endl;
+  cout << pop;
+
+
+ + + + +
+ +  /////////////////////////////////////
+  // selection and replacement
+  ////////////////////////////////////
+
+
+ + + + +
+ +  // The robust tournament selection
+  eoDetTournamentSelect<Indi> selectOne(tSize);
+  // is now encapsulated in a eoSelectPerc (entage)
+  eoSelectPerc<Indi> select(selectOne);// by default rate==1
+
+
+ + + + +
+ +  // And we now have the full slection/replacement - though with
+  // no replacement (== generational replacement) at the moment :-)
+  eoGenerationalReplacement<Indi> replace;
+
+
+ + + + +
+ +  //////////////////////////////////////
+  // The variation operators
+  //////////////////////////////////////
+
+
+ + + + +
+ +  // uniform chooce on segment made by the parents
+  eoSegmentCrossover<Indi> xoverS;
+  // uniform choice in hypercube built by the parents
+  eoHypercubeCrossover<Indi> xoverA;
+  // Combine them with relative weights
+  eoPropCombinedQuadOp<Indi> xover(xoverS, segmentRate);
+  xover.add(xoverA, hypercubeRate, true);
+
+
+ + + + +
+ +  // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon]
+  eoUniformMutation<Indi>  mutationU(EPSILON);
+  // k (=1) coordinates of parents are uniformly modified
+  eoDetUniformMutation<Indi>  mutationD(EPSILON);
+  // all coordinates of parents are normally modified (stDev SIGMA)
+  eoNormalMutation<Indi>  mutationN(SIGMA);
+  // Combine them with relative weights
+  eoPropCombinedMonOp<Indi> mutation(mutationU, uniformMutRate);
+  mutation.add(mutationD, detMutRate);
+  mutation.add(mutationN, normalMutRate, true);
+  // The operators are  encapsulated into an eoTRansform object
+  eoSGATransform<Indi> transform(xover, pCross, mutation, pMut);
+
+
+ + + + +
+ +  //////////////////////////////////////
+  // termination condition see FirstBitEA.cpp
+  /////////////////////////////////////
+  eoGenContinue<Indi> genCont(maxGen);
+  eoSteadyFitContinue<Indi> steadyCont(minGen, steadyGen);
+  eoFitContinue<Indi> fitCont(0);
+  eoCombinedContinue<Indi> continuator(genCont);
+  continuator.add(steadyCont);
+  continuator.add(fitCont);
+  
+  
+
+
+ + + + +
+ +  // but now you want to make many different things every generation
+  // (e.g. statistics, plots, ...).
+  // the class eoCheckPoint is dedicated to just that:
+  // Declare a checkpoint (from a continuator: an eoCheckPoint
+  // IS AN eoContinue and will be called in the loop of all algorithms)
+  eoCheckPoint<Indi> checkpoint(continuator);
+  
+      // Create a counter parameter
+      eoValueParam<unsigned> generationCounter(0, "Gen.");
+      
+      // Create an incrementor (sub-class of eoUpdater). Note that the
+      // parameter's value is passed by reference,
+      // so every time the incrementer is updated (every generation),
+      // the data in generationCounter will change.
+      eoIncrementor<unsigned> increment(generationCounter.value());
+      // Add it to the checkpoint,
+      // so the counter is updated (here, incremented) every generation
+      checkpoint.add(increment);
+      // now some statistics on the population:
+      // Best fitness in population
+      eoBestFitnessStat<Indi> bestStat;
+      // Second moment stats: average and stdev
+      eoSecondMomentStats<Indi> SecondStat;
+      // Add them to the checkpoint to get them called at the appropriate time
+      checkpoint.add(bestStat);
+      checkpoint.add(SecondStat);
+      // The Stdout monitor will print parameters to the screen ...
+      eoStdoutMonitor monitor(false);
+        
+      // 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);
+      monitor.add(eval); // because now eval is an eoEvalFuncCounter!
+      monitor.add(bestStat);
+      monitor.add(SecondStat);
+      // A file monitor: will print parameters to ... a File, yes, you got it!
+      eoFileMonitor fileMonitor("stats.xg", " ");
+        
+      // the checkpoint mechanism can handle multiple monitors
+      checkpoint.add(fileMonitor);
+      // the fileMonitor can monitor parameters, too, but you must tell it!
+      fileMonitor.add(generationCounter);
+      fileMonitor.add(bestStat);
+      fileMonitor.add(SecondStat);
+      // Last type of item the eoCheckpoint can handle: state savers:
+      eoState outState;
+      // Register the algorithm into the state (so it has something to save!!)
+      outState.registerObject(parser);
+      outState.registerObject(pop);
+      outState.registerObject(rng);
+      // and feed the state to state savers
+      // save state every 100th  generation
+      eoCountedStateSaver stateSaver1(20, outState, "generation");
+      // save state every 1 seconds
+      eoTimedStateSaver    stateSaver2(1, outState, "time");
+      // Don't forget to add the two savers to the checkpoint
+      checkpoint.add(stateSaver1);
+      checkpoint.add(stateSaver2);
+      // and that's it for the (control and) output
+
+
+ + + + +
+ +  /////////////////////////////////////////
+  // the algorithm
+  ////////////////////////////////////////
+  // Easy EA requires
+  // stopping criterion, eval, selection, transformation, replacement
+  eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace);
+  // Apply algo to pop - that's it!
+  gga(pop);
+  
+
+
+ + + + +
+ +  // Print (sorted) intial population
+  pop.sort();
+  cout << "FINAL Population\n" << pop << endl;
+
+
+ + + + +
+ +}
+// A main that catches the exceptions
+int main(int argc, char **argv)
+{
+      try
+      {
+              main_function(argc, argv);
+      }
+      catch(exception& e)
+      {
+              cout << "Exception: " << e.what() << '\n';
+      }
+      return 1;
+}
+
+
Back to Lesson 3 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+
Last +modified: Sun Apr 28 06:42:44 2002 + + + diff --git a/deprecated/eo/tutorial/html/beige009.jpg b/deprecated/eo/tutorial/html/beige009.jpg new file mode 100644 index 000000000..594c01d8e Binary files /dev/null and b/deprecated/eo/tutorial/html/beige009.jpg differ diff --git a/deprecated/eo/tutorial/html/binary_value.html b/deprecated/eo/tutorial/html/binary_value.html new file mode 100644 index 000000000..45f3e35a1 --- /dev/null +++ b/deprecated/eo/tutorial/html/binary_value.html @@ -0,0 +1,57 @@ + + + + + + binary_value.h + + +Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+binary_value.h

+ + + + + +
#include <eo> +
//----------------------------------------------------------------------------- +
/** Just a simple function that takes binary +value of a chromosome and sets +
     the fitnes. +
     @param _chrom A +binary chromosome  +
*/
+ + + + + +
double binary_value(const vector<bool>& +_chrom) +
{ +
 double sum = 0; +
 for (unsigned i = 0; i < _chrom.size(); +i++) +
     sum += _chrom[i]; +
 return sum; +
}
+ +
Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Wed Nov +29 09:03:09 2000 + + diff --git a/deprecated/eo/tutorial/html/debut.html b/deprecated/eo/tutorial/html/debut.html new file mode 100644 index 000000000..2c6c8d305 --- /dev/null +++ b/deprecated/eo/tutorial/html/debut.html @@ -0,0 +1,21 @@ + + + + TITRE + + + +Tutorial main page - +Algorithm-Based +page - Component-Based - Programming +hints - EO documentation +
+
+ + +
+

TITRE

+
+ + +

diff --git a/deprecated/eo/tutorial/html/eoBottomUp.html b/deprecated/eo/tutorial/html/eoBottomUp.html new file mode 100644 index 000000000..b35d40262 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoBottomUp.html @@ -0,0 +1,77 @@ + + + + + + EO - The Component-Based approach + + +Tutorial main page - +Algorithm-Based + - Component-Based - Programming +hints - EO documentation +
+


+
+

+EO - Component-Based approach

+ +


Congratulations - You have chosen the component-based approach!  +From here you will be allowed to browse into the different components of +an Evolutionary Algorithm, and to see how to program your favorite using +the EO library. + +

+Table of Content

+ +
+

+ +

Yes, this is the table of content of this part +of the EO tutorial. If you don't already know what this symbolic + representation of an EA means, you should try here. Otherwise, click on the figure +to go directly to the corresponding section of the tutorial. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+


+
Tutorial main page - Algorithm-Based + - Component-Based - Programming +hints - EO documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Mon Oct 30 07:28:36 CET 2000 + + diff --git a/deprecated/eo/tutorial/html/eoCheckPoint.html b/deprecated/eo/tutorial/html/eoCheckPoint.html new file mode 100644 index 000000000..3b905eed6 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoCheckPoint.html @@ -0,0 +1,150 @@ + + + + + + Variation Operators + + +General: Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
+
+
Local: Introduction +- Continuators - Combined +continuators - Checkpoints - Statistics +- Monitors - Updaters +
+
+
+

+CheckPointing

+What +is Checkpointing about? +
Evolutionary Algorithms are almost all timely ticked, the basic time +unit being what is called a generation. EO checkpointing mechanism allow +you to program things that you want to be done at the end of every generation. +This includes deciding to stop, outputing some statistics on the current +state of the algorithm,  updating some dynamical variables of your +algorithm, saving the population to disk, ... +

EO classes described in this page: +

    +
  • +Base classes: eoCheckPoint, eoContinue, +eoStat, eoSortedStat, eoMonitor, eoUpdater
  • + +
  • +Derived classes: eoCombinedContinue,
  • + +
  • +Related classes: eoGnuPlot1DMonitor, +eoGnuPlot1DSnapshotMonitor,
  • +
+ +
  +

+


Continuators: +

Continuators are functors that compute stopping critera. They receive +a population and return a boolean value which is set to false only when +some stopping vriterion is met. All algorithms in EO have a loop that goes +do{...}while(continuator(pop)which +means that the algorithm stops only when the continuator returns false. +

Interface:  The abstract class +for computing stopping conditions is eoContinue, +and the interface for its operator() is +

                           + +bool operator()(const eoPop<EOT>& +) +

which you could have guessed from the inheritance +diagram for class eoContinue, as +you see there that eoContinue derives +from class eoUF<const eoPop<EOT>&, +bool>. +

Using a continuator: +
You can find an first example of using a continuator in the code for +FirstBitEA +ior more sophisticated continue conditions in  Lesson2. +
If you want to find out how it is used inside an algorithm, go and +see for instance in eoSGA, the simplest EA within EO. +

Writing a +continuator: +
There are only two things to modify in the template +class definitions provided (apart from the name of the class you are +creating!) +

    +
  • +The constructor, where you pass to the object +any useful parameter (see the private data at end of class definition).
  • + +
  • +The operator() method, which performs the +computation of the actual test using the population plus any other parameter +passed at construct time. Don't forget to returnfalse +when the stopping criterion is met!
  • +
+Existing continuators: +Of +course you can find out all existing (non-virtual!) subclasses of eoContinue +by looking at its  inheritance +diagram. But you might find it more convenient to have them listed +here: +
    +
  • +
  • +
+ +


+


Combining +continuators: +

+


CheckPoints: +

Interface: +

Using a checkpoint: An eoCheckPoint +being an eoContinue, its usage is exactly the same. However, an eoCheckPoint +will actually do many more things than an eoContinue before returning its +boolean result as an eoContinue. +

Writing a +checkpoint: +
This is something you should never have to do. However, should you +feel you have to do it, please do - and send us both the reasons that lead +you to that (what is it you couldn't do with existing eoCheckPoint), and +the resulting code, of course. +
+


Statistics: +

Interface: +

Using statistics: +

Writing a statitic: +
+


Monitors: +

Interface: +

Using monitors: +

Writing a monitor: +

+


Updater: +

Interface: +

Using updaters: +

Writing an updater: +
  +

+


Local: Introduction +- Continuators - Combined +continuators - Checkpoints - Statistics +- Monitors - Updaters +
+
General: Algorithm-Based +- Component-Based - Programming +hints -EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Fri Dec. 8 2000  +
  + + diff --git a/deprecated/eo/tutorial/html/eoEngine.html b/deprecated/eo/tutorial/html/eoEngine.html new file mode 100644 index 000000000..367c94177 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoEngine.html @@ -0,0 +1,778 @@ + + + + + + Genetic Engine + + +General: Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
Local:
Introduction  +- Selection - Replacement +- General Replacement - Popular +evolution engines - Tournaments - Merge +- Reduce - HowMany - SurviveAndDie +
+
+

+Evolution Engine

+ +
+
Evolution +Engines +

The term evolution engine denotes +the different parts of an Evolutionary Algorithm that simulate the Darwinism: +

+

The fittest individuals are more likely to +reproduce and survive.

+ +

Darwinism takes place in two different phases of an EA, though in many +popular +variants, only one phase is activated. +

Selection is the Darwinistic choice of parents +that will be allowed to reproduce. +
Replacement takes place after reproduction, +and is the Darwinistic choice of those individuals that will survive, +i.e. become the parents of the next generation. +

Both selection and replacement will be discussed in turn, before some +helper classes that are used within selection and replacement procedures +are presented. +

+


Selection +

The very beginning of the generation loop is the selection phase, where +some individuals from the population are chosen to become the parents, +to be later modified by the variation operators and become the offspring. +This is the first step of the artificial Darwinism, +where the fittest individuals are allowed to reproduce. +
Conceptually, there are two distinct ways to choose the lucky ones: +one by one from the very same population (i.e. with replacement), which +means that at the extreme the same individual can be chosen every time; +or as a whole, in some sort of batch procedure. Of course, repeated selection +of one individual results in a batch selection! +

There are hence two basic EO classes for selection: eoSelectOne +and eoSelect, with different interfaces. +
+


+
eoSelectOne: The +interface +

The abstract class for selection of a single individual from a population +is eoSelectOne, and the interface for its +operator() +is +

+

const EOT & operator()(const eoPop<EOT>& +_parents)

+ +

which you could have guessed from the inheritance tree for class eoSelectOne., +as you see there that eoSelectOne derives +from class eoUF<const eoPop<EOT>&, +const EOT&>. +
This means that it takes 1 population +(without the right to modify it - see the const +keyword in argument) and returns a const reference to an individual (again, +the const keyword ensures +that nothing will happen to the individual in the population - remember +it returns a reference). +
+


+
eoSelectOne: Instances +
    +
  • +eoDetTournamentSelect uses +the (deterministic) tournament to choose one +individual. Its constructor has one parameter, the tournament size (integer +>= 2).
  • + +
  • +eoStochTournamentSelect uses +the binary stochastic tournament to choose +one individual. Its constructor has one parameter, the tournament rate +(real in [0.5,1]).
  • + +
  • eoProportionalSelect +is the original roulette wheel selection: +each parent is selected with a probability proportional to its fitness.
  • + +
  • +eoRandomSelect is the random +selection and should give bad results! At the moment, it selects one individual +uniformly, but it would be easy to use any probability distribution.
  • +
+ +
+
eoSelect: The +interface +

The abstract class for batch selection of a  whole set of individuals +from a population is eoSelect, and the interface +for its +operator() is +

+

void operator()(const eoPop<EOT>& +_source, eoPop<EOT>& _dest)

+ +

which you could have guessed from the inheritance tree for class eoSelect., +as you see there that eoSelect derives from +class +eoBF<const eoPop<EOT>&, eoPop<EOT>&, void>. +
This means that it takes 2 populations, +and fills the second one with individuals from the first one without modifying +it (see the const keyword). +This raises two questions: +

    +
  • +How does it know how many individuals to select?
  • + +
  • +How to use repeated selection of one individual (see above the eoSelectOne +class)?
  • +
+ +
+
eoSelect: HowMany +

There are two ways an  can derive the number of individuals it +has to select: either it is a fixed number, or it is some percentage of +the source population size (any positive real number). In both case, this +must be passed to the constructor. In most instances, however, the constructor +will accept a real number (double) and a boolean indicating whether this +real number should be used as an absolute integer or as a rate, thanks +to the eoHowMany class. +

Note: an eoSelect +can select more individuals than there are in the original population. +It is the job of the replacement to ensure +that the population size does not grow along the generations. +

+


eoSelectMany: Encapsulating +eoSelectOne +

It is clear that repeated selection of a single individual is a way +to do batch selection. This is why it is possible to encapsulate an object +of class eoSelectOne into an object of class +eoSelect +using the class eoSelectMany. Class eoSelectMany +is derived from class eoSelect and takes in +its constructor an eoSelectOne (plus the number +of individuals it should select, according to the eoHowMany +paradigm). +

Note: some procedures for selecting +a single individual require some pre-processing of the whole population +that takes place before any selection, and will be repeated identically +for every individual. The encapsulation of an  into an  allows +to call such technical processing only once through the use of method setup +of class . This method does nothing by default, but is mandatory +
+


+
eoSelect: Other +instances +
    +
  • +eoDetSelect selects individuals +deterministically, +i.e. starting from the best ones down to the worse ones. If the total number +to select is less than the size of the source populations, the best individuals +are selected once. If more individuals are needed after reaching the bottom +of the population, then the selection starts again at top. It the total +number required is N times that of the source size, all individuals are +selected exactly N times.
  • +
+No other instances of eoSelect that are not +encapsualtions of eoSelectOne procedures are +avaiable as of today (Jan. 4 2001). +
+
+
Replacement +

The replacement phase takes place after the birth +of all offspring through variation operators. This is the second +step of the artificial Darwinism, where the +fittest +individuals are allowed to survive. +
It can also be viewed on the algorithmic side as closing the generation +loop, i.e. building the population that will be the initial population +of next generation. That population will be built +upon the old parents and the new-born offspring. In all algorithms +that come up with EO, the population size +is supposed to be constant from one generation +to the next one - though nothing stops you from writing an algorithm with +varying population size. +
+


+
Replacement: The +interface +

The abstract class for replacement procedures is the functor class +eoReplacement, +and the interface for its operator() +is +

+

void operator()(eoPop<EOT>& _parents, +eoPop<EOT>& _offspring)

+ +

which you could have guessed from the inheritance tree for class eoReplacement., +as you see there that eoReplacement derives +from class eoBF<eoPop<EOT>&, eoPop<EOT>&, +void>. +
This means that it takes 2 populations +(called, for obvious anthropomorphic reasons, _parents and _offspring :-) +and is free to modify both, but the resulting population should be placed +in the first argument (usually called_parents) to close the loop and go +to next generation. +
+


+
Replacement: Instances +
    +
  • +eoGenerationalReplacement This +is the most straightforward replacement, called generational +replacement: all offspring replace all parents (used in Holland's +and Goldberg's traditional GAs).  It takes no argument, and supposes +that offspring and parents are of the same size (but does not check!).
  • + +
      +
  • +eoMergeReduce +This is one the basic types of replacement in EO. It has two major steps, +merging +both populations of parents and offspring, and reducing +this big population to the right size. It contains +two objects of respective types eoMerge +and eoReduce +and you can probably guess what each of them actually does :-)
  • + +
      +

      +
      +
      +

    Available instances of eoMergeReduce replacement +include +

      +
    • +eoCommaReplacement, one of +the two standard strategies in Evolution Strategies, +selects +the best offspring. It is an +eoMergeReduce(eoNoElitism, +eoTruncate).
    • + +
    • +eoPlusReplacement, the other +standard Evolution Startegies replacement, +where the best from offspring+parents +become the next generation. It is an eoMergeReduce(eoPlus, +eoTruncate).
    • + +
    • +eoEPReplacement, used in the +Evolutionary Programming historical algorithm, does an EP stochastic +tournament among parents + offspring. It is an eoMergeReduce(eoPlus, +eoEPReduce) and its constructor requires as argument T, +the size of the tournament (unsigned int).
    • +
    + +
  • +eoReduceMerge is another important +type of eoReplacement: the parents are first reduced, and then merged with +the offspring. Note that the parent population is reduced of the exact +number of offspring.
  • + +
    Though not mandatory, it is implicitely assumed that few offspring +have been generated. Hence, all derived replacement procedures of class +eoReduceMerge +are termed eoSSGAxxx, as they +are the ones to use in SteadyState Genetic Algorithm engine. This gives +the following instances of eoReduceMerge: +
      +
    • eoSSGAWorseReplacement +in which the worse parents are killed and replaced by all offsprings (no +additional argument needed);
    • + +
    • +eoSSGADetTournamentReplacement +in which parents to be killed are chosen by a (reverse) determinitic tournament. +Additional parameter (in the constructor) is the tournament size, an unsigned +int.
    • + +
    • +eoSSGAStochTournamentReplacement +in which parents to be killed are chosen by a (reverse) stochastic tournament. +Additional parameter (in the constructor) is the tournament rate, a double.
    • +
    + +
  • +eoSurviveAndDie +replacement strategies are a generalization of both the above that allows +strong elitist and eugenism in both the parent population and the offspring +population. The eoSurviveAndDie +building block takes one population, kills the worse and moves the best +to some safe place.  The corresponding replacements apply an eoSurviveAndDie +to the parents, another one to the offspring, and finally merges the remaining +parents and offspring before reducing the resulting population to the right +size. Available instances of eoSurviveAndDieReplacement +are limited todayto the eoDeterministicSaDReplacement, +the  that uses a deterministic MergeReduce.
  • + +
      +

      +
      +
      +

    Note: The basic use (and initial +motivation) for eoSurviveAndDie +takes 2 arguments, an eoMergeReduce and a number of surviving parents. +It starts by copying the best parents to the new populations, then merges +the remaining parents with the offspring before reducing to the number +of remaining seats in the new population.

+ +
+
Replacement: Adding +(weak) elitism +

You can add what is called weak elitism +to any replacement by encapsulating it into an eoWeakElitismReplacement +object. Weak elitism ensures that the overall best +fitness in the population will never decrease: +if the best fitness in the new population is less than the best fitness +of the parent population, then the best parent is added back to the new +population, replacing the worse. +

Within EO, this is very easy to add: +

First, declare your replacement functor (here, generational, but it +can be any replacement object): +
eoGenerationalReplacement<Indi> genReplace; +
Then wrap the weak elitism around it: +
eoWeakElitismReplacement<Indi> replace(genReplace); +
and use now replace as your replacement procedure within your algorithm. +

Note: of course, adding weak elitism to +an elitist replacement makes no sense - but will not harm either :-) +
+


+
Replacement: Test +file +

The file t-eoReplacement +in the test directory implements all +above replacement procedures within a very simple and easy-to-monitor Dummy +EO class. +

+


+
General +Replacement: eoReduceMergeReduce +

In an attempt to unify all the well-known replacements, plus most of +the less-known-though-often-used, the eoReduceMergeReduce +replacement has been designed, and supersedes all of the above instances. +
It allows to implement strong elistism +(i.e. some parents survive, whatever their fitness and that of the offspring), +as well as multiple weak elistism (the best parents are put back in the +next population if they outperform the best offspring). +

Basically, an eoReduceMergeReduce +starts by eventually preserving the (strong) elite parents, proceeds by +reducing both the parent and offspring populations, merges those populations, +and eventually reduces the resulting populations (augmented with the elite +parents) to the right size. Last, the weak elitism is taken care of if +necessary. +
The following image, taken from the graphical interface of EASEA, somehow +demonstrates the different parameters of an eoReduceMergeReduce. +
+


+
eoReduceMergeReduce: The  +interface +
Of course the interface is that of eoReplacement. Let's concentrate +on the constructor. +

The constructor takes 6 arguments: +

    +
  1. +eoHowMany elite determines +the number of parents to be treated as elite (actual behavior determined +by next parameter) using the eoHowMany behavior.
  2. + +
  3. +bool strongElitism tells whether +the elite above corresponds to strong (true) or false(weak) elitism.
  4. + +
    Note: the case of no elitism is +obtained by setting elite to 0 +
  5. +eoHowMany reducedParents gives +the number of parents remaining after reducing them
  6. + +
    Note: 0 means that no parent survive +(except the possible elite), as in eoCommaReplacement +
                +-1 is used inside eoSSGAReplacements +(one parent is killed to make room for the newborn) +
  7. +eoReduce<EOT> & reduceParents +indicates how the parents will be reduced (see available +instances).
  8. + +
  9. +eoHowMany reducedOffspring gives +the number of offspring remaining after reducing them
  10. + +
    Note: 0 is impossible (no evolution!!!) +
  11. +eoReduce<EOT> & reduceOffspring +indicates how the offspring will be reduced (see available +instances).
  12. + +
  13. +eoReduce<EOT> & reduceFinal +indicates how the merged reduced-parents/reduced-offspring will be reduced +(see available instances).
  14. + +
    Note: the number of individuals +remaining after that reduction is of course the original size of the population.
+All popular evolution engines use some replacement procedure that can be +viewed as an instance of an eoReduceMergeReduce. +
Moreover, a parser-based input +of a general  is proposed in file do/make_checkpoint.h. +
+
+
Popular +evolution engines +

The most popular evolution engines are listed below, together with the +way to use them in EO. If you don't find your particuler algorithm, please +send it to us, and we might include it here! In the following, P will denote +the number of individuals in the initial population. +

    +
  • +Generational Genetic Algorihtm: +popularized by Holland (75) and Goldberg (89), it uses
  • + +
    Number of offspring:  +P +
    Selection: Proportional +(the historical roulette wheel) when maximizing +a positive scalar fitness, ranking or +tournament (stochatic or deterministic) in all cases. +
    Replacement: Generational. +
    Remark: You could +use also the eoCommaReplacement, +with exactly the same result as there are as many offspring as we need +indiviudals in the next population. And using the eoSSGAWorseReplacement +would also give the same result, but would be very inefficient! +
    You can also add weak +elitism to preserve the best individual. +
  • +Steady-State Genetic Algorithm: +widely used in GA/GP community
  • + +
    Number of offspring:  +small (historically, 1) +
    Selection: tournament +(you can use ranking or proportional, but it will be rather inefficient). +
    Replacement: An +eoSSGAxxxReplacement. +
    Remark: You can +also use the eoPlusReplacement, but you divert from the original SSGA +
  • +(MU+Lambda)-Evolution Strategy: +The elitist ES strategy (Rechenberg 71 and Schwefel 81)
  • + +
    Number of offspring:  +Any +
    Selection: eoDetSelect +(batch deterministic). +
    Replacement: eoPlusReplacement +
    Remark: You could +also use eoEPReplacement, to smoothen the selective pressure during replacement, +thus getting close to EP evolution engine +
  • +(MU,Lambda)-Evolution Strategy: +The non-elitist ES strategy
  • + +
    Number of offspring:  +> P +
    Selection: eoDetSelect +(batch deterministic). +
    Replacement: eoCommaReplacement +
    Remark: You can +also add weak elitism to preserve the best individual +- though you'd probably use the plus strategy if you want (strong) elitism. +
  • +Evolutionary Programming: +The historical method of L. Fogel (65)
  • + +
    Number of offspring:  +P +
    Selection: eoDetSelect +(batch deterministic). Every individual reproduces exactly once. +
    Replacement: eoEPReplacement, +though one historical replacement was the determnistic replacement - i.e. +in EO the eoPlusReplacement). +
    Remark: Close to +an (P+P)-ES +
  • +You name it :-): +you can of course choose whatever combination you like - respecting a few +constraints and common-sense remarks. For instance, eoProportionalSelect +should be used only when maximizing a positive fitness, eoCommaReplacement +requires more offspring than parents, and, over all, existing EO algorithms +wirk with fixed size population - and it is your responsability to use +a cmbinatino of selection/replacement that fulfills this requirement (or +to create your own eoAlgo that handles varying size populations).
  • +
+ +
+
Tournaments +

Tournaments are an easy and quick way to select +individuals within a population based on simple comparisons. Though usually +based on fitness comparisons, they can use any comparison operator. +
In EO, there are two variants of tournaments used to select one single +individual, namely Deterministic Tournament +and Stochastic Tournament, +that are used in selection and in replacement procedures, and a global +tournament-based selection of a whole bunch of individuals, the EP +Tournament. Though the single-selection tournaments can +be repeated to select more than one individual, and the batch tournament +selection can be used to select a single individual, both uses are probably +a waste of CPU time. +

    +
  • +Deterministic +Tournament of size T returns the best of T uniformly chosen +individuals in the population. Its size T should be an integer >= 2. It +is implemented in the eoDetTournamentSelect +class, a sub-class of eoSelectOne, as well as in the eoDetTournamentTruncate +class that repeatidly removes from the population the "winner" of the inverse +tournament.  These objects use the C++ function determinitic_tournament +in  selectors.h.
  • + +
  • +Stochastic Tournament +of rate R first choses two individuals from the population, and selects +the best one with probability R (the worse one with probability 1-R). Real +parameter R should be in [0.5,1]. It is implemented in the eoStochTournamentSelect +class, a sub-class of eoSelectOne, as well as in the eoStochTournamentTruncate +class that repeatidly removes from the population the "winner" of the inverse +tournament.  These objects use the C++ function determinitic_tournament +in  selectors.h.
  • + +
    Note: A stochastic tournament with +rate 1.0 is strictly identical to a deterministic tournament of size 2. +
  • +EP Tournament +of size T is a global tournament: it works by assigning a score to all +individuals in the population the following way: starting with a score +of 0, each individual I is "opposed" T times to a uniformly chosen individual. +Everytime I wins, its score in incremented by 1 (and by 0.5 for every draw). +The individuals are then selected deterministically based on their scores +from that procedure. The EP Tournament +is implemented in the  eoEPReduce +truncation method used in the eoEPReplacement +procedure.
  • + +
    Note: whereas both the determinitic +and the stochastic tournament select one individual, the EP tournament +is designed for batch selection. Of course it could be used to select a +single individual, but at a rather high computational cost.
+ +


+


+
Merging +populations +

In replacement procedures, one frequently needs to merge two populations +(computed form old parents and new-born offspring). Classes derived from +the abstract class eoMerge are written for that purpose. +
+


+
eoMerge: interface +
The abstract class for merging procedures is the functor class +eoMerge, +and the interface for its operator() +is +
+

void operator()(const eoPop<EOT>& +_parents, eoPop<EOT>& _offspring)

+ +

which you could have guessed from the inheritance tree for class eoMerge, +as you see there that eoMerge derives from +
class eoBF<const eoPop<EOT>&, eoPop<EOT>&, +void>. +
This means that it takes 2 populations +and modifies the seond one by adding some individuals from the first one +(which is supposed to remain constant). +
+


+
eoMerge: instances +
Available instances of eoMerge objects +are eoPlus, that simply adds +the parents to the offspring, or eoElitism, +that adds only some of the (best) parents to the offspring. A special case +of eoElistism is eoNoElitism, +an eoMerge that does nothing. +

+


+
Reducing +populations +

The other useful component of replacement procedures, eoReduce, +kills +some individuals from a given population. +
+


+
eoReduce: interface +
The abstract class for reducing procedures is the functor class +eoReduce, +and the interface for its operator() +is +
+

void operator()(eoPop<EOT>& _parents, +unsigned int new_size)

+ +

which you could have guessed from the inheritance tree for class eoReduce, +as you see there that eoReduce derives from +
class eoBF<eoPop<EOT>&, unsigned +int, void>. +
An eoReduce shoud take a +population and shrink it to the required size. +
+


+
eoReduce: instances +
Available instances of eoReduce are +
    +
  • +eoTruncate, deterministically +kills the worse individuals, keeping only the required number. It starts +by sorting teh populations, and hence does modify +its order.
  • + +
  • +eoLinearTruncate, deterministically +kills the worse individuals, keeping only the required number. It does +so by repeatedly removing the worsr individual. Hence does not +modify its order, but takes longer time than eoTruncate +in case of many offspring.
  • + +
  • +eoEPReduce, uses the EP +stochastic tournament to reduce the population. It requires an additinal +argument, the tournament size.
  • + +
  • +eoDetTournamentTruncate uses +inverse deterministic tournament to repeatidly kill one individual until +the propoer size is reached. As eoLinearTruncate, +it might take some time in the case of many offspring. It requires the +size of the tournament (unsigned int) +as parameter in the constructor (default is 2).
  • + +
  • +eoStochTournamentruncate  +uses inverse stochastic tournament to repeatidly kill individuals from +the population. It requires the rate of the tournament (double) +as parameter in the constructor (default is 0.75).
  • +
+ +
+
eoHowMany: +Choosing a number of individuals +

Many classes in selection/replacement procedures will handle a number +of individuals that may either be fixed or be related to some argument-population +size. +
Of course, it is possible to write different classes that will only +differ by the way they compute the number of individuals they have to treat, +as it is done for selectors with the two classes eoSelectPerc +and eoSelectNumber (it could also have been +possible to have some pure abstrat class and implement the computation +of the number of individuals to treat in some derived classes). +
However, the class eoHowMany +allows one to handle in a single class three different behaviors when given +a poopulatio size as argument: +

    +
  • +return a given rate of the argument population size
  • + +
  • +return an absolute (unsigned) integer, whatever the argument population +size
  • + +
  • +return the argument population size minus a given number
  • +
+ +
+
eoHowMany: interface +
The class interface for its operator() +is +
+

unsigned int operator()(unsigned int _pop_size)

+ +

which you could have guessed from the inheritance tree for class eoHowMany, +as you see there that eoHowMany +derives from +
class eoUF<unsigned int, unsigned int>. +

It has 3 possible constructors, that determine its behavior: +

    +
  • +eoHowMany(double _rate, bool _interpret_as_rate += true) where _rate +is by default the fixed rate of behavior 1 above. However, if the boolean +second argument is false, the rate is transformed into a positive integer, +and is used for behavior 2 above
  • + +
  • +eoHowMany(int _combien): if +_combien +is positive, it is the absolute number of behavior 2 above, and if _combien +is negative, its absolute value is used to decrease the argument population +in behavior 3 above
  • + +
  • +eoHowMany(unsigned int _combien): +_combien +(positive!)  is the absolute number of behavior 2 above. Note +that this constructor is mandatory to avoid ambiguity, as an unsigned int +can be casted to either an int or a double.
  • +
+It is used in eoSelectMany (which supersedes +eoSelectPerc +and eoSelectNumber, but they are left there +for tutorial reasons!) as well as in many truncation +methods, and it is used a lot in the eoGeneralReplacement construct. +

+


+
Survive and +Die +
This class is highly politically incorrect: it implements strong elitism +and eugenism :-) +
It starts by killing the worse individuals from the source argument, +then appends the best ones to the destination argument and removes them +from the source argument. It is used in eoSurviveAndDieReplacement, +where the same dest is used successively for the parents and the offspring. +

eoSurviveAndDie: interface +
The class interface for its operator() +is +

+

void operator()(eoPop<EOT>& _source, +eoPop<EOT>& _dest)

+ +

which you could have guessed from the inheritance tree for class eoSurviveAndDie, +as you see there that eoSurviveAndDie +derives from class eoBF<eoPop<EOT>&, +eoPop<EOT>&, void>. +

Its constructor takes 3 argumenrts: +

+

eoHowMany(double _survive, double _die, +bool _interpret_as_rate = true)

+ +

to indicate how many (or what proportion, according to _interpret_as_rate) +of the source should be copied to the dest population, and how many (or +what proportion, according to _interpret_as_rate)  +should be erased from the source. +

+


Local: Introduction  +- Selection - Replacement +- General Replacement - Popular +evolution engines - Tournaments - Merge +- Reduce - HowMany - SurviveAndDie +
+
+
General: Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last +modified: Tue. Jan. 9 2001  + + diff --git a/deprecated/eo/tutorial/html/eoEval.html b/deprecated/eo/tutorial/html/eoEval.html new file mode 100644 index 000000000..4a90ac330 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoEval.html @@ -0,0 +1,34 @@ + + + + Evaluation + + + +Tutorial main page - +Algorithm-Based +page - Component-Based - Programming +hints - EO documentation +
+
+ +
+

Evaluation

+
+ + + +
+
+Tutorial main page - +Algorithm-Based +page - Component-Based - Programming +hints - EO documentation +
+
Marc Schoenauer
+ + +Last modified: Mon Nov 6 10:54:33 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoGeneration.html b/deprecated/eo/tutorial/html/eoGeneration.html new file mode 100644 index 000000000..39cfe3da0 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoGeneration.html @@ -0,0 +1,19 @@ + + + + Generation + + + +

Generation

+ + + +
+
Marc Schoenauer
+ + +Last modified: Mon Oct 30 19:29:29 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoInit.html b/deprecated/eo/tutorial/html/eoInit.html new file mode 100644 index 000000000..3a4df155c --- /dev/null +++ b/deprecated/eo/tutorial/html/eoInit.html @@ -0,0 +1,36 @@ + + + + Initialization + + +Tutorial main page - +Algorithm-Based +page - Component-Based - Programming +hints - EO documentation +
+
+ + +
+

+Initialization

+ + + + + +
+
+Tutorial main page - Algorithm-Based +page - Component-Based - Programming +hints - EO documentation +
+
+Marc Schoenauer
+ + +Last modified: Mon Nov 6 11:25:18 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoIo.html b/deprecated/eo/tutorial/html/eoIo.html new file mode 100644 index 000000000..14e0d37c1 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoIo.html @@ -0,0 +1,25 @@ + + + + Input / Output + + + +

Input / Output

+ +

+ +

Stopping criteria

+ +

+ +

Displaying statistics

+ +
+
Marc Schoenauer
+ + +Last modified: Tue Oct 31 18:32:22 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoLesson1.html b/deprecated/eo/tutorial/html/eoLesson1.html new file mode 100644 index 000000000..f88921015 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoLesson1.html @@ -0,0 +1,440 @@ + + + + + + Tutorial: Lesson 1 + + +Lesson 2 - +Tutorial +main page - +Algorithm-Based - Component-Based +- Programming hints -EO +documentation +
+
+
+

+Tutorial: Lesson 1

+This lesson will let you +
    +
  • +run your first Evolutionary Algorithm written within +EO Library, choosing between evolving bitstrings, +or evolving vectors of real numbers,
  • + +
  • +browse through the code of these algorithms, or
  • + +
  • +follow the guided tour.
  • +
+Later you will be asked to +
    +
  • +write your own fitness function,
  • + +
  • +check that EO let you separate the representation +from the evolution engine.
  • + +
  • +use different kinds of selection +procedures in the framework of a generational GA evolution +engine,
  • +
+ +

+ +
I want to run +an Evolutionary Algorithm +now

+You can choose to run a standard bitstring Genetic +Algorithm (as defined in Goldberg's book) or a standard real-valued +genetic algorithm, as proposed in Micahlewicz's book. +

If you have not already done what was recommended in the Tutorial +main page , do it NOW. Then go +to the Lesson1 sub-dir of the tutorial dir, and simply type at the system +prompt +

(myname@myhost) EOdir/Tutorial/Lesson1 % FirstRealGA +
or +
(myname@myhost) EOdir/Tutorial/Lesson1 % FirstBitGA +

and something should happen. +

+What is happening?

+At the moment, the FirstBitGA maximizes the +number of ones in the bitstring (also calls the OneMaxfunction, +whose solution is, as you can guess, +11111111), +and the FirstRealGA is maximizing (the default +action for EO is to maximize) the inverse of the sum (i.e. minimizing the +sum) of the square of its variables (also called the sphere +function, whose solution is ... all zeroes). +

And what you see on the screen when running one of these two programs +is, in each case, the initial and final population of an Evolutionary run, +one individual per line, its fitness first, then the number of items (bits +or real numbers) of the genotype, and the genotype itself. The final population +hopefully contains the solution in the discrete case, and is close to it +in the continuous case. +
+


Browsing +the code: +

Now you need to take a look at the program codes, either by browsing +alone through the  sources for FirstBitGA +and FirstRealGA, or by following the guided +tour below. You might prefer to go directly to the exercises. +

+ +
Guided tour:

+ +
    +
  • +General includes:Like +all C-like code, the file starts with include directives (Bit +- Real). Apart from standard includes, +the specific file to include is eo: +this is a file that contains the list of the all important representation-independent +EO files.
  • + +
      +
  • +Representation: +you then have to declare the type of individuals you will be handling. +All evolution-related objects you will need are templatized w.r.t. the +type of individuals.
  • + + + +
  • +Fitness function: +the code for the fitness function is included in the file. It must take +as argument a reference to an individual (at the moment).
  • + +
      +
    • +Bit This function simply computes +the number of ones of the bitstring (it's called the OneMax function). +The optimum is of course the all-ones bitstring.
    • + +
    • +Real This function simply computes +the inverse of the sum of the squares of all variables (also called the +sphere function). The optimum is of course the all-zeroes vector.
    • + +
       
    + +
  • +Parameters: +all parameters of the algorithm are declared here (Bit +- Real), and their values and +assigned. Of course, this means that you will need to recompile to change +these values - see Lesson 3 to get rid of that heavy requirement.
  • + +
      +
  • +Random seeding: +Random numbers play an important role in Evolutionary Algorithms. See in +EO +programming hints more details about how this is simulated in EO - +but as far as you are concerned now, remember that the global +Random Number Generator is called rng +and should be used everywhere you need a realization of a random variable +of known law. Moreover, this RNG requires a seed, +which is set here (Bit - Real): +every time you run the algorithm with the same +seed, you will get the same +result. Hence, to test the robustness of your +algorithm, you should run it with different seeds. This is rather time +consuming in the present programs, so we suggest that you wait until Lesson +3 to do so.
  • + +
      +
  • +Fitness function encapsulation: EO +is based on the notion of functors +- hence you now need to encapsulate your fitness function into a functor +object. This is what is done here (Bit +- Real).
  • + +
      +
  • +Initialization: +to initialize the population, first declare an empty object of class eoPop<Indi>, +which is basically an STL vector<Indi>, +then fill it with Indi's. And remember that +v.push_back +simply appends its argument at the end of STL +vector v.
  • + + + +
  • +Output: take +a snapshot at the initial population (Bit +- Real). Sort it first, so the best +individuals are first, and display it. Note that an eoPop has a << +method, which means that a simple os +<< pop streams the pop +onto the ostream os. +This is true for all objects of of class eoPrintable +(most EO objects) through the method printOn +(which is then called by the << +operator).
  • + +
      +
  • +Evolution engine: +The selection/replacement mechanism (Bit +- Real) is a simple generational +GA here: a simple selector, and a generational replacement. The eoDetTournamentSelect +has been chosen as a robust selection, and the generational replacement +(all parents are replaced by the offspring) is hard-coded in the eoSGA +algorithm.
  • + +
      +
  • +Variation operators: +in the simple algorithm considered here, individuals undergo crossover +and mutation. +In EO, these operators are (functor) +objects of class eoQuadOp +(binary operator that modifies both its arguments) and eoMonOp +(unary operator).  These operators are applied in turn to all selected +parents, according to user-defined probabilities.  These probabilities +are defined with all other parameters, and will +be passed to the eoSGA algorithm.  +For more details on these classes, go to the algorithm-based +corresponding pages, or to their respective documentation pages.
  • + +
      +
      +
    • +Bit The crossover eo1PtBitXover +is the standard 1-point crossover, and eoBitMutation +is the standard bit-flip mutation that randomly +flips all bits with a given probability P_MUT_PER_BIT.
    • + +
      Warning: the P_MUT_PER_BIT +probability is an internal parameter of the +eoBinMutation, +it is NOT the probability of mutation +at the individual level. EO corrects what can be viewed as an inconsistency +in Holland's original work, further used in Goldberg's book by separating +the probability of mutation for each individual (independent of the type +of mutation that will be applied) from the probability of flipping each +bit, which is specific of the bit-flip mutation.  Hence, to run the +same algorithm as Goldberg's SGA, the mutation probability (at individual +level) is 1, and the probability of flipping each bit is P_MUT_PER_BIT. +
    • +Real The crossover eoSegmentCrossover +is the standard segment crossover for real-valued +vectors, that chooses a point randomly on the segment between both parents +(also termed BLX-0). eoUniformMutation +is the uniform mutation for real-valued vectors +that chooses a new value for each variable uniformly on an interval centered +on the parent value. The width of the interval is an internal +parameter of the object, here called EPSILON.
    • + +
       
    + +
  • +Stopping criterion: +Specify a maximum number of generations +to run (Bit - Real): +the simplest of all stopping criteria at the moment, using an object of +a sub-class of class eoContinue.
  • + +
      +
  • +The algorithm: the +simple algorithm that is used here, called  eoSGA +requires +as parameters a selector, +a crossover and +the associated crossover rate, +a mutation and +the associated mutation rate, +and a stopping criterion. +Take a look at the corresponding +constructor +of the class eoSGA: +it only initializes its private data +with the parameters. Now look at the operator() +method - the one that is called in the code for FirstBitGA +or FirstRealGA - and you'll find +out that is is as simple as it sounds.
  • + +
      +
  • +Output: After +running the algorithm, output the sorted final population (Bit +- Real) - and look at the best +individual: this is the result of the algorithm.
  • + +
      +
  • +Main body: for +technical reasons (intercepting the exceptions), we need a main like this +one (Bit - Real)., +and you should not touch it unless you know what you are doing. Simply +note that this main calls the function main_function, which we have been +discussing up to now!
  • +
+ +

+ +
Exercise +1: maximize your own function

+This is very easy - if your search space is that of bitstring or of unbounded +real numbers. +
    +
  • +Go to the tutorial directory, and copy the +program you want to modify onto mytest.cpp.
  • + +
  • +Edit mytest.cpp +with any text editor:
  • + +
  • +Modify the fitness function itself (binary_value +in FirstBitGA,real_value +in  FirstRealGA)
  • + +
  • +Compile the program by typing make +mytest at system prompt
  • + +
  • +Run the new program by entering the command +mytest +at system prompt.
  • +
+ +

+ +
Exercise +2: check the differences between both programs

+Go and take a look at the code for these programs (Bit +- Real). Use the symbolic representation +of an Evolutionary Algorithm (you should understand that figure now, otherwise +go there and come back) to understand how each +part of the EA is coded. Try to spot the differences between both codes: +there are not so many! +
After you've tried that alone, take a look at the solution +:-) +

+ +
Exercise +3: change the selection procedure

+This is rather straightforward ... if you know what other types of selection +are available! +
At the moment, let's only consider only the following simple ones: +
    +
  • +You already know the tournament selection
  • + +
    Syntax:  eoDetTournamentSelect<Indi> +select(T_SIZE);   // T_SIZE in [2,POP_SIZE) +
  • +Try the well-known roulette wheel
  • + +
     Syntax:    eoProportionalSelect<Indi> +select; +
  • +Or the stochastic binary tournament
  • + +
    Syntax:  eoStochTournamentSelect<Indi> +select(RATE);     +// RATE in ]0.5,1] +
  • +and of course the random selection should +give bad results!
  • + +
    Syntax:  eoRandomSelect<Indi> +select;
+Note that all these classes of eoObjects are derived from the abstract +class +eoSelectOne. +To find out exactly how each procedure selects the individuals, read the +corresponding component-based page. +

+


Lessons learned: +
    +
  • +in EO, all actions are performed by functor +objects (this section is the last time in this tutorial that there +is a direct link to the EO Programming hints +page - though the link at top and bottom of all pages will remain there).
  • + +
  • +in EO, all object you will usually need to manipulate are templatized +w.r.t. the type of the individual you are handling.
  • + +
  • +The type of the individual is itself templatized +w.r.t. the type of fitness (double by default).
  • + +
  • +In EO (actually, in EC!) initialization and variation +operators are representation-dependent, while +the evolution engine is representation-independent +(well, like any rule, this one does have some exceptions).
  • + +
  • +Changing the fitness function, or the selection +procedure inside the generational GA evolution engine is straightforward.
  • + +
  • +remember, all solutions to exercises are in +the same sub-dir of dir Tutorial than the lesson itself (see here).
  • +
+ +
Lesson 2 - +Tutorial +main page - +Algorithm-Based - Component-Based +- Programming hints - EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Fri Nov 3 18:49:12 CET 2000 + + diff --git a/deprecated/eo/tutorial/html/eoLesson2.html b/deprecated/eo/tutorial/html/eoLesson2.html new file mode 100644 index 000000000..6b3cf4580 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoLesson2.html @@ -0,0 +1,357 @@ + + + + + + Tutorial: Lesson 2 + + + +Lesson 1 - +Lesson +3 - +Main page - +Algorithm-Based +- Component-Based - Hints +- EO +documentation +
+
+
+

+Tutorial Lesson 2: more encapsulations

+In this lesson, the same Evolutionary Algorithm will be rewritten in a +much more general context. +
First, look at the changes that have been done +to the algorithms. Then benefit from the new features by +
    +
  • +minimizing (and not only maximize) the fitness
  • + +
  • +combining several +operators of the same type
  • + +
  • +combining several +stopping criteria
  • + +
  • +use alternate selection/replacement +engines, deviating from the pure generational GA
  • +
+ +


Again, two basic algorithms are provided, namely FirstBitEA +and FirstRealEA. +
To compile and run them, go to the Lesson2 +sub-directory of the tutorial dir and simply type make. +Both examples should get compiled, and you can then run them by calling +their name from the system prompt. +

Note the slim difference in names, from GA +to EA: the behavior of these  EAs is +almost identical to that of their GA counterpart, at least with the default +settings that are provided. But their potentialities for easy modifications +are much larger, both in terms of variation operators +and of evolution engine (i.e. selection/replacement +mechanism).  +


Changes +

Browse through the code, and discover them one after the other: +

    +
  • +The fitness function +now +lies in a separate file +(Bit +- Real). But, more important, its +argument is a vector<bool> or a vector<double>, +and not an unknown type. This will allow to use the same file for any EO +object that is a sub-class of the corresponding STL vector class.
  • + +
      +

      +

    Note: Also, +a non-templatized fitness can be compiled +separately (not done here) into an object +file once and for all (remember +that templates forbid that). +
      +

  • +The encapsulation +of +the fitness (Bit +- Real) looks more complicated: you +have to declare 3 template arguments: the type of EO object it will be +applied to, the return type and the type of argument the function actually +requires.
  • + +
      +

      +

    Note: In the +previous files (Bit - Real) +, the last 2 types were deduced from the first (2nd argument = fitness +type of EO object, third = first). +
      +

  • +Both the above modifications makes it very easy to +minimize +rather than maximize a fitness function (see Exercise +1).
  • + +
      +
  • +The initialization +of the population is now encapsulatedinto +a separate initializer (based +on a boolean generator or a double-number +generator -see random_generators.h) +that is then used in the constructor of the population to build the individuals. +You can also use different initializers and call them in turn through the +call to pop.append() function +(see Exercise 2).
  • + +
      +

      +

    Note: Don't +forget to evaluate the population: +the eoPop has no idea of the eval function, so it has to be done from outside!!! +
      +

  • +You can now use +different +crossover +and +mutation +operatorsin the same algorithm, +choosing among them according to +relative +weights. The +class eoPropCombinedxxxOp, +where +xxx is either Mon (for mutations, of class eoMonOp) +or Quad (for crossovers, of class eoQuadOp), +is derived from the corresponding eoxxxOp class. When applying the eoPropCombinedxxxOp, +one of the eoxxxOp it contains is chosen by a roulette +wheel, according to their respective rates, and is applied to the arguments. +For more details on these classes, go to the algorithm-based +corresponding pages, or to their respective documentation pages.
  • + +
      +
    • +Bit
    • + +
      Three crossover +operators are available: the one-point +crossover is still there (class ), but now you also have the N-point +crossover eoBinNxOver +(the  number of points is 2 by default, but as always you can change +that in the constructor), and the Uniform +crossover eoBinUxOver +(where you can eventually twidle the choice from one parent to the other +by providing a probability in the constructore - defaulted to 0.5, which +amounts to symmetrical choice). +
      As for mutation +operators, apart from the eoBinMutation +(standard bitstring mutation flipping one bit with a given probability) +you can also use the eoDetBitFlip +that always filps the same number of bits (1 by default, but you can change +that in the constructor), randomly chosen in the bitstring. Even though +the average number of bits flipped is the same if the eoBinMutation +is +used with a rate of 1/N (N is the bitstring length) the +behavior of these mutation can be very different +on many problems. +
    • +Real
    • + +
      Two crossover +operators are available: the eoSegmentCrossover +chooses one point uniformly on the segment joining the parents, while the +eoHypercubeCrossover +performs a linear combination on each coordinate independently, which amount +to choosing the offspring uniformly in the hypercube whose diagonal is +the segment joining the parents. +
      As for mutation +operators, apart from the eoBinMutation +(standard bitstring mutation flipping one bit with a given probability) +you can also use the eoDetBitFlip +that always filps the same number of bits (1 by default, but you can change +that in the constructor), randomly chosen in the bitstring. And last but +not least, the normal mutation eoNormMutation modifies all coordinates +with a Gaussian noise, with standard deviation passed in the constructor.
    +Note: A third optional argument in +method add is a boolean (defaulted +to false). When true, the actual rates for all operators are displayed +on the screen as percentages: you don't have to input rates that sum up +to 1, all rates are scaled anyway. +

    Note: The +operators have to be encapsulated into an eoTransform +object (Bit - Real) +to be passed to the eoEasyEA algorithm. +The eoSGATransform is a simple +eoTransform +that does exactly the same thing than eoSGA: +each pair from the selected parents undergoes the crossover +operator with given probability, and all individuals (after crossover +eventually) undergo mutation with given probability. +The arguments to the eoSGATransform +are an eoQuadOp with its probability +and an eoMonOp with the associated +probability. +
      +

  • +You can use combinations +of +several stopping criteria by using an object of the class eoCombinedContinue +(Bit +- Real). Initialize it with an object +of class eoContinue, and +add +as many of other such objects as you wish. And as an eoCombinedContinue +is +an eoContinue, +simply pass it to the algorithm (Bit +- Real). To find out more, and +to get the list and syntax of existing eoContinue subclasses, check out +the corresponding component-based +page.
  • + +
      +
  • +The +full selection/replacement mechanism is +now in place through the eoEasyEA +algorithm.
  • + +
    This means that you can use different selectors. +which was already true in Lesson 1, but also different replacement +strategies (see Exercise 3) whereas generational +replacement was hard-coded in the algorithm eoSGA +used in Lesson1. +

    Beware that we have to encapsulate  (Bit +- Real) the eoDetTournament, +which is of class eoSelectOne (i.e. allows +to select one individual from a population, its operator() +returning a single individual) into an object of the eoSelectPerc +(perc stands for percentage) which allows to select a ... percentage of +a population (his operator()  +returns a population). This was done internally in the  constructor +of eoSGA  - see lesson1.

+ +
Exercise +1: minimizing +
Modify the algorithm so that it minimizes the +fitness. +
    +
  • +For the bitstring case, you only have to modify the +declaration +of the representation, using eoMinimizingFitness +instead of double. +But is that really all? Give it a try, look at the output, and do it right +the second time!!!
  • + +
  • +For the real-valued problem, you also need to modify +the file real_value.h so +that it returns the sum of squares instead of its inverse. And again there +is something else to modify...
  • +
+Exercise +2: initialization +
Use different initializers: for instance, on +the real-valued sphere function minimization, try to initialize half of +the population in [-2,-1] and the other half in [1,2], with and without +the segment and hypercube crossovers (and for large values of VEC_SIZE, +the size of the vectors). Amazing, isn't it! Explain that result. +

Exercise +3:  full selection/replacement +
You can now twiddle the number of offspring that +will be generated from the parents. But of course you need to adjust the +replacement to keep a constant population size. +

    +
  • +To modify the number +of offspring, use the second argument of the +encapsulator +(Bit - Real) +of the selector +of class eoSelectOne +into an eoSelectPerc object. For instance, try
  • + +
                    +eoSelectPerc<Indi> select(selectOne,2.0) +
    to generate twice as many offspring as there +are parents. +
    You can also use the other encapsulator that +takes as second argument an absolute number (e.g. if you want to generate +2 offspring whatever the population size): +
                    +eoSelectNumber<Indi> select(selectOne,2) +
    Or you can use the HowMany +paradigm and the eoSelectMany to +do either one depending on some command-line input (advanced). +
  • +To keep a constant population +size, you can use either the eoCommaReplacement +class, or the eoPlusReplacement. +The former selects the best offspring to replace the parents, the latter +selects the best among parents+offspring. Of course you cannot use eoCommaReplacement +if you have less offspring than parents!
  • + +
    Now if you use eoSelectRandom +as selector with a rate of +lambda, you end up with exactly the (mu+lambda) +or +(mu,lambda) strategies from Evolution +Strategies. +
  • +Question: what do you +get if you select 1 offspring only, and an eoPlusReplacement +strategy? Yes, you get almost the replace_worst Steady-State GA, though +rather inefficient, as you sort the population at every generation.
  • + +
  • +Hint: there are a few +Steady-State replacement strategies already there in EO. See the Replacement +page.
  • +
+Remember: all solutions +are in the same sub-directory of the Tutorial dir than the examples (i.e. +here Lesson2), and are described here. +

+


+
Lessons learned: +
    +
  • +How to write a fitness function that only +needs a genotype, not a full individual. Moreover you can compile it separately.
  • + +
    How to initialize the population using +random generators +
  • +How to use other evolution engine than the +simple generational GA.
  • + +
  • +How to combine different objects of the same kind into a single object +that you can use like a simple basic object (operators +and stopping criteria here).
  • +
+ +
Lesson 1 - +Lesson +3 - +Main page - +Algorithm-Based +- Component-Based - Hints +- EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Fri Nov 3 18:49:12 CET 2000 + + diff --git a/deprecated/eo/tutorial/html/eoLesson3.html b/deprecated/eo/tutorial/html/eoLesson3.html new file mode 100644 index 000000000..40c36e118 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoLesson3.html @@ -0,0 +1,565 @@ + + + + + + Tutorial: Lesson 3 + + +Lesson 2 - +Lesson +4 - +Main page - +Algorithm-Based +- Component-Based - Hints +- EO +documentation +
+
+
+

+Tutorial Lesson 3: input/output

+In this lesson, you will still use the same Evolutionary Algorithm, BUT +in a much more user-friendly way. You +will discover how to +
    +
  • +input parameters on the command-line or from a text +file
  • + +
  • +save the population to disk, together with every part +of the algorithm you could think of - so you can decide to reload +everything later to continue the same run, eventually with different parameters.
  • + +
  • +generate statistics on the populations, and output +them to the screen, text or graphic, or to a file (or to any other +device you might want to use).
  • +
+First, but you should now have done it without being told, go into the +Lesson3 +sub-dir of the tutorial dir and type +make. +This will compile the SecondBitEA +and SecondRealEA +programs. +

You can then either +

+ +


+


+
Changes +
As already said, the behavior of the algorithm +will be exactly the same as the previous one as far as optimization is +concerned. Only the input (of algorithm parameters) and output (of program +results) will be very different. +
Hence, the sections corresponding to the fitness +function, the initialization, the +variation +operators, the evolution engine +and the algorithm itself are +almost identical (apart from variable name changes). +
    +
  • +Fitness function: +there is an additional line +after the encapsulation of our binary_function +into an eoEvalFunc +object, which again encapsulate the eoEvalFunc +into an eoEvalFuncCounter. +As its name says, this object will, in addition to computing the fitness, +count the actual +number of evaluations: the fitness of non-modified individuals is of course +not recomputed - and this is taken care of by this object. Moreover, it +can be later used for displays +in eoMonitor objects, as done in the checkpoint +section.
  • + +
  • +The initialization +section has been extended to account for the possibility to re-load +a previously saved population. This is achieved +through an eoState object, if the corresponding program +parameter is set.
  • + +
  • +The +variation +operators and the evolution engine  +sections are similar to the ones in Lesson2
  • + +
  • +The parameter +section  is completely different from the previous one. All variables +corresponding to program parameters +are now read at run-time using an object of class eoParser.
  • + +
  • +The stopping criterion +section, has in fact now become the checkpoint section, as it involves +much more than just stopping criteria. See all details in the eoCheckpoint +paragraph below.
  • +
+ +
eoParser: +parameter input +
The first two examples of Lessons 1 and 2 had +a very crude way to set parameter values: they were hard-coded, and you +had to recompile the whole program to change a single value. We shall now +see now to set parameter values in a flexible way (though we're still looking +for volunteers to create a Graphical User Interface :-) +
Two base classes are used for that purpose: +
    +
  • +The eoValueParam +class, templatized by the type of the variable +you want to handle (i.e. iinteger, +double, yourPrivateClass, ...). In +this lesson, we will not go into details: e.g. we will not tell you that +the +eoValueParam +is actually a templatized sub-class of abstract class eoParam (oops, I +said it!), nor will we deal with parameters outside their use from an eoParser. +See the parameter section of the Component-Based tutorial, or wait until +lesson +4).
  • + +
  • +The eoParser +class, whose only purpose is the input of parameters. Read its +description if you are interested.
  • +
+ +
eoParser: +Modifying parameter values at run-time: +
Using an eoParser object, the parameter values +are read, by order of priority +
    +
  1. +from the command-line
  2. + +
  3. +from a text file
  4. + +
  5. +from the environment (forthcoming, if somebody insists)
  6. + +
  7. +from default values
  8. +
+The syntax of parameter reading is a keyword-based +syntax, now traditional in the Unix world: +
    +
  • +in EO, each parameter is designated by a (long) keyword, +and optionally by a short (1 character) keyword.
  • + +
      +
  • +the general syntax to modify parameter value at run-time is (either from +the command-line or in a text file)
  • + +
                 + +--longKeyword=value     +or     -cvalue    +if 'c' is the short keyword (though -c=value +also works) +
      +
  • +so, after compiling the executable for Lesson 3 (make +lesson3 at system prompt in Unix), you can try to type +in
  • + +
                  + +SecondBitEA +
    and see the algorithm run as before (OneMax optimized on 8-bits bitstrings). +But you can now type in +
                  + +SecondBitEA --vecSize=100 +
    and see the output of the optimization of OneMax on 100-bit bitstrings. +
      +
  • +Take a look at all available parameters by typing in
  • + +
                  + +SecondBitEA --help +
    or by going into the code: all parameter inputs have been grouped in +the +read_param function. +
      +
  • +After running the algorithm, a new file has been created, named SecondBitEA.status: +it contains the list of all actual parameters used, and can directly be +used as parameter input file: change the file name (e.g. to SecondBitEA.param), +edit it, change whichever parameter you want, and type in
  • + +
                    +SecondBitEA @SecondBitEA.param +
    and you will see all values that you defined into the file taken into +account. +
      +
  • +The priority remains to the command-line, +so you can still override the values in the parameter file by giving a +new value directly on the command-line.
  • +
+ +
eoParser: +Programming parameter input: +
The code of SeconBitEA provides examples of parameters reading. Lets +take the example of the random number +generator seed.  +Of course, you first need to declare +an eoParser object (it needs the standard argc and argv in its constructor). +
    +
  • +You must first declare a parameter +of type uint32 (32-bits integer). +The arguments are: default value, long keyword, comment (that will appear +in the help message and in the output "status" file if any) and optional +character keyword.
  • + +
  • +Then you must pass it to the parser +using the processParam method. The optional argument is a section name, +that will be used to make the output of the parser look clean and ordered.
  • + +
  • +Finally, you need to assign the +value to the variable seed. +Note that the value() method +of eoParam returns a reference, so you can eventually modify its value +somewhere else later (though of course this is not any useful for variable +seed!).
  • +
+There is however another way to achieve the same result in less lines of +code - with a different memory management. This is what is done in the +code for eoRealEA. The same parameter for the random +number generator seed +is read, but in one single line of code.  +The only difference is that now you cannot access the eoValueParam object +itself - but this is not often necessary. +
Be careful to ensure that the type of the default value in the call +to eoParameterLoader::createParam +method as this is the only way the compiler can desambiguate the template +(remember that eoParameterLoader is a +base class for eoParser. +
+
+
eoState: +saving and loadingYou might have +noticed in the  read_param +described above a new parameter +named load_name. +Now if you go to the init section of +the code, you will see an alternative way of initializing +the population: if load_name is an empty string, +then we do as in the preceding example and use an eoInitFixedLength object. +However, if a load_name name was entered, the population is read through +the inState.load(load_name) +instruction. Moreover, the comment says "Loading pop and +rng". +

This is made possible using the eoState +class. eoState +objects maintain references to eoObjects +that have both an input method (readFrom) +and an output method (printOn), +i.e. that derive from the base class eoPersistent. +You must first register +object into a state, and can then save them to a (text) file, and later +read them from that file using the load +method, as done here. +
Of course, you can call the save +method for an eoState +object anywhere in the code. But the checkpointing +mechanism offers you better ways to do that - and it's so easy .... +

Note that an eoState alos has another use in EO whan it comes to memory +management: it can be a repository of pointers that are not allocated within +obects - allowing to delete them by simply deleting the eoState (see Lesson +4). +
+


eoCheckpoint: +every generation I'd like to ... +
The checkpointing mechanism is a very powerful +construct to perform some systematic actions +every generation - like saving things +(using eoState objects described above), computing statistics +on the population, updating +dynamical parameters or displaying +information. +

eoCheckpoint +objects are eoContinue +objects that contain pointers to different +types of objects. When their operator() +method is called (i.e. every generation in the examples up to now), they +first call the operator() +methods of all object they contain, and then return their result as an +eoContinue +object (i.e. should we continue or stop). +
Programming: To +do something every generation, you simply need to add +an object whose operator() +does what you want to the eoState that you will use as continuator in the +algorithm. +
+


eoCheckpoint: +Stopping +
The eoContinue +part of an eoCheckpoint +is a single object, passed to the +constructor. If you want more that one stopping criterion, use an eoCombinedContinue +object as described in Lesson2. +
+
+
eoCheckpoint: Computing +statistics +
Statistics are computed using eoStat +objects, i.e. functor objects whose operator() +receives as argument a reference to a population as argument, and can hence +compute whatever is needed over that population. eoStat +objects are templatized +over the type of what they compute (e.g. double, +or pair<double>, +or ...). But looking at the inheritance +diagram of the eoStat +class, you find that eoStat +objects are also eoValueParam +objects. And this allows eoStat +to be used within eoMonitor +object, and hence displayed +to the user! +

Statistics: Available +instances +
Some widely used statistics are already available (and of course you +can build you own!). +

    +
  • +eoBestFitnessStat returns +the fitness value of the best individual in the population (of type FitnessType, +whatever this is).
  • + +
  • +eoAverageStat and eoSecondMomentStat +respectively return the average (type double, assumes that FitnessType +is castable to a double) and a pair made of the average and the standard +deviation (type pair<double>) +of the fitnesses in the populations.
  • + +
  • +eoDiversityStat returns the +diversity in the population: assuming that there is a distance function +defined among individuals, it returns the average inter-individuals distance. +See also Exercise 2.
  • +
+Statistics: Adding +to the checkpoint +
To compute more statistics when your algorithm is running, simply declare +the corresponding eoStat objects, and add +them to the eoCheckpoint you +use in the algorithm. But it hardly makes any sense if you don't monitor +those statistics (i.e. either displaying them on the screen, or storing +them into a file): see next section! +

Note: actually, there are 2 distinct +classes that compute and give access to statistics: eoStatand +eoSortedStat. +As its name indicate, the latter is used whenever computing the statistics +require a sorted population: not only this avoids to sort the population +many times, but also it avoids changing the order of the population at +all as eoSortedStat objects +work on a temporary vector of fitnesses . But as +far as their usage is concerned, its makes no difference. +
+


+
eoCheckpoint: Monitoring +eoParameters +
The eoMonitor +objects are used to display or store to a file a set of eoValueParam +objects. +

Monitors: Available +instances +
A few monitors are available in the EO distribution: +

    +
  • +eoStdoutMonitor displays its +parameters in text format on the screen. The +(optional) boolean value in the constructor modifies the output: when true +(the default), verbose output is used, with one line per parameter. When +false, parsimonious output displays one line for all parameters.
  • + +
  • +eoFileMonitor writes its parameters +in text format in a file. A file name is required +in the constructor, and an optional separator character can be added (default +is ' '). Note that the file is by default overwritten by next call to the +same program, unless you pass "true" as third (optional) boolean parameter, +which will result in appending to the file if it ever exists.
  • + +
  • +eoGnuplot1DMonitor displays +its parameters in graphical format on the screen +by calling the gnuplot program, +and as of today, only works in the Unix version of EO (as always, volunteers +are welcome to port that to MS Windows). It takes an optional filename +as input, as communication of data with gnuplot +is done through a file. If no filename is provided, the file will be erased +at the end of the run, while it is otherwise kept (though it will be overwritten +by next call to the same program).
  • +
+ +


Monitors: Adding +to the checkpoint +
To display something while the algorithm is running, you need to declare +an eoMonitor object, add +some objects (that must be eoValueParam +objects) to that monitor, and of course add +the monitor to the eoCheckpoint +you use in the algorithm. +
+


+
eoCheckpoint: Updating +things +
The last type of objects that  eoCheckpoint +can handle are eoUpdater +objects. You should simply encapsulate in an eoUpdater +anything you wish to do which does not fit into one of the above category. +Note that their operator() method +does not receive any argument. +

Updater: Available +instances: A few updaters are available in the EO distribution: +

    +
  • +eoIncrementor A simple updater +which maintains a counter (an eoValueParam +that needs to be created beforehand, and passed in the constructor). It +is incremented every time the operator() +method is called (every generation at the moment). You can of course also +give an increment in the constructor (1 by default).
  • + +
  • +eoCountedStateSaver +and eoTimedStateSaver can +be used to save some existing eoState +(see above) to a file regularly, either based on the +generation count (e.g. every 4 generations) or based on the clock (e.g. +every 5 seconds).
  • +
+Updater: Adding to +the checkpoint +
A very simple example of using an eoUpdater +is given in the code for SecondBitEA: First declare +an eoValueParam object, then +use +it to construct an eoIncrementor +that you must add to the eoCheckpoint +in order to activate its update. You can then use the parameter for your +purpose, for instance as a first coordinate for a monitor. +
Note also how to use the statesavers: first declare +a state, then register +whatever you think necessary to that state, then pass +the state to some state-saver - and don't forget to add +the statesavers to the current eoCheckpoint. +
+
+
Exercise 1: +
    +
  • +The code of SecondBitEA +display things in the current window in text format. Replace the eoFileMonitor +by an eoGnuplot1DMonitor +and watch the graphical output (Unix +systems with gnuplot +installed only, sorry).
  • + +
  • +Note that you must also replace the eoSecondMomentStat +by an eoAverageStat, +otherwise the standard deviations won't make any sense here.
  • + +
  • +Please try to understand why the average is always +0 before taking a look at the solution (file exercise1.cpp).
  • + +
  • +Then run
  • + +
              +exercise1 --vecSize=1000 --maxGen=1000 +
    to get a chance to see something happening before +the program ends!
+ +
Exercise 2: +
Write the eoDiversityStat +stat computation and test it. Thanks to send us the code! +
+
+
Exercise 3: +
Write the code for an eoGnuplotSecondStatMonitor +that would display the eoSecondMomentStat +(i.e. take into account the standard deviations and display them as error-bars. +
Again, send us the code afterwards, thanks :-) +
+
+
Lessons learned: +
    +
  • +Value of program parameters can be set at run-time +using the eoParser class.
  • + +
  • +Snapshots of the algorithms can easily +be saved (and restored) +thanks to the eoState class.
  • + +
  • +The eoCheckpoint mechanism +let you do things every generation +without modifying existing algorithms, by simply writing the necessary +code and encapsulating it into an object that eoCheckpoint +is aware of, that are at the moment the following:
  • + +
  • +computing statistics, displaying +parameters +(e.g. statistics),  saving the +(eo)State +of the program.
  • +
+In next lesson you will find out that many adaptive +techniques (the state-of-the-art in Evolutionary Computation) can easily +be programmed through the eoUpdater +construct. +
+
Lesson 2 - +Lesson +4 - +Main page - +Algorithm-Based +- Component-Based - Hints +- EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: None of your business! + + diff --git a/deprecated/eo/tutorial/html/eoLesson4.html b/deprecated/eo/tutorial/html/eoLesson4.html new file mode 100644 index 000000000..0ddab737f --- /dev/null +++ b/deprecated/eo/tutorial/html/eoLesson4.html @@ -0,0 +1,940 @@ + + + + + + Tutorial: Lesson 4 + + +Lesson 3 - +Lesson +5 - +Main page - +Algorithm-Based +- Component-Based - Hints +- EO +documentation +
+
+
User's guide: General +- Bitstring - Real - ES +- Programmer's guide: General +- Memory management - Parameters +
+
+
+

+Tutorial Lesson 4: ready-to-use fully operational EA

+In this lesson, you will still use the same Evolutionary Algorithm. But +this time you will have full control of all components +from the command-line or a parameter file.
+You can even use the algorithm decribed here without any other knowledge +of EO, just by writing your fitness function as a plain C++ function.

+ +Contents
+ + +

+


+
User's +guide +

As already said, the behavior of the algorithms +will be exactly the same as the previous one as far as optimization is +concerned. Only now you will be able to tune every component of the algorithms +(except the type of genotype) using run-time parameters. +
Also, as in previous lessons, most of the code +is representation-independent, i.e. is the same for both the binary genotypes +and the real-valued genotypes. This small user's guide reflects that, but +you can go directly to the binary or the real +parts if you wish. +

Warning: this +is a user guide, not a programming guide. In particular, the keywords +of the parameters are not +the names of +the underlying classes (though they should be similar in most cases). +

User's guide:Parameter +input The way to input parameters +has already be described in Lesson +3. To get a list of parameters, type the command with option --help +(or -h): with both testBit and testReal this will result in +

    +
  • +Printing the list of keywords on the standard output
  • + +
  • +Creating (or overwriting) a file name testBit.status +or testReal.status that contains the list of all recognized parameters +and has the format of an input parameter file.
  • +
+User's guide:The +status file +
This file will always contain the list of the +parameters that have been actually used by the last run of the program, +however thay have been entered (try testBit +-G1 and take a look a the +status file). The parameters that are commented out (a # character comments +out the rest of the line) in the file are those that were not specified +by the user. +
On the status file, the parameters are organized +in sections. Note, however, that this format is not mandatory in the param +file, as only the keywords +are processed. +

User's guide:Representation-independent +parameters +
In what follows, the fixed font colored text +is directly taken from the status file and is commented between the lines. +The presentation follows the status file format - only two sections are +representation-dependent (see the corresponding binary +or real sections). All other sections are presented +now: +

+


+
Section ###### +General ###### +
# --help=0 # -h : Prints +this message +
Boolean parameter of +absolutely no interest: tells whether or not help was requested. +

# --seed=988700289 # -S : +Random number seed +
Unsigned long parameter: +the seed for the Random Number Generator +If the parameter is absent, then time(0) is used, which indicates the number +of seconds since Jan. 1 1980, is used ... and stored in the status file, +of course, so you can repeat the same run by simply assigning that value +again. There is no default value ("true" random +seed). +

+


+

Section ###### +engine ###### +
In this section, one chooses all components of +the Evolution Engine (selection, replacemenet +and the like). +

# --popSize=20 # -P : Population +Size +
Integer parameter: +the size of the population (constant along evolution). And yes, this is +a representation independent parameter, as the population is created either +from a file or using an eoInit object - and only that object is representation-dependent. +
# --selection=DetTour(2) +# -S : Selection: Roulette, DetTour(T), StochTour(t) or Sequential(ordered/unordered) +
String parameter: +Name of selection procedure. Availabable +are the roulette wheel +(name Roulette, +fitness scaling coming soon); deterministic +tournament (name DetTour +with size - integer > 2 - in parentheses right after the name, use double +quotes on the command line);  stochastic +tournament (name StochTour +with probability - float in [0.5, 1] - in parentheses); sequential +(name +Sequential, +all individuals in turn), either from best to worst (option ordered +in parentheses), or in random ordered (option unordered); +and finally repeated independent uniform +choices  (name Random). +Default is DetTour(2). +

# --nbOffspring=100% # -O +: Nb of offspring (percentage or absolute) +
Integer or real-valued parameter: +this parameter indicates the amount of +offspring that will be generated from +the genitors every generation. However, this amount can be specified either +relative +to the population size, and it should then end with percent character (%), +or as an absolute +integer number (without the percent char). +
Indeed, you can either want, say 7 times more +offspring than parents (a rather common situation in Evolution Strategies), +in which case you give value 700% to nbOffspring +parameter; or you might want a single offspring whatever the population +size, like in Steady-State evolution engines, in which case you simply +enter value 1. Default is 100%. +

# --replacement=Comma # -R +: Replacement: Comma, Plus, EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t) +
String parameter: +Name of replacement procedure. Availabable are the ES +plus and comma deterministic replacement +strategies (named respectively Plus +and  Comma); +EP +stochastic tournament (name EPTour +with tournament size in parentheses); and the steady-state +replacement +procedures, at the moment only based on fitnesses, replacement being either +deterministic +(new born replace worst parent, name SSGAWorst),  +or based on a tournament  (name SSGADet +for deterministic tournament, size in parentheses, and SSGAStoch  +for stochastic tournament, probability in parentheses). Default +is Comma (which btw is also SGA generational +replacement whenever there are as many offspring +as parents). +

# --weakElitism=0 # -w : +Old best parent replaces new worst offspring *if necessary* +
Boolean parameter: +if true, weak elitism is added to the replacement procedure (i.e. if the +best fitness among the offspring is less than the best fitness, the best +parent replaces the worst offspring). Default +is false. +

+


+

Section ###### +Output ###### +
This first section on Output contains parameters +related to screen text output. +

# --useEval=1 # Use nb of +eval. as counter (vs nb of gen.) +
Boolean parameter: +whether or not you want the nb of evluations to be displayed and used as +counter in statistics outputs and plots. Default +is true. +

# --printBestStat=1 # Print +Best/avg/stdev every gen. +
Boolean parameter: +toggles screen output of indicated statistics. Default +is true. +

# --printPop=0 # Print sorted +pop. every gen. +
Boolean parameter: +adds a dump of the whole population to the screen every generation. Is +likely to generate huge +output! Default is false. +

# --printFDC=1 # Print FDC +coeff. every gen. +
Boolean parameter: +adds Fitness Distance Correlation to output every generation. Default +is false. +

+


+

Section ###### +Output - Disk ###### +
This second section on Output contains parameters +related to DISK output. +

# --resDir=Res # Directory +to store DISK outputs +
String parameter: All +DISK +output will be stored in a separate directory +-this is its name. If the directory does not exist, it is created. Note +that all graphical displays +will use that directory for their temporary files. Also all +job dump (see section Persistence +below) store their files there too. +

# --eraseDir=0 # erase files +in dirName if any +
Boolean parameter: +in order not to mix up files from different runs, it is mandatory to ensure +that the directory where all files will be stored is empty. However, if +this parameter is not set and the directory already exists, an exception +is thrown and the program stops. It it is set, all +files in the result directory are erased. +

# --fileBestStat=0 # Output +Best/avg/stdev to a file +
Boolean parameter: +if present, the best, average and standard deviation statistics are stored +in file resDir/best.xg. +Each line contains the generation number, eventualy the evaluation count +(depending on parameter useEval +then the statistics. Default is false. +
  +

+


+

Section ###### +Output - Graphical ###### +
This last section on Output contains parameters +related to graphical output (only available in Unix through gnuplot at +the moment). +

# --plotBestStat=0 # Plot +Best/avg Stat +
Boolean parameter: +toggles gnuplot output of best and average plots (Linux only at the moment). +Default +is false. +

# --plotFDCStat=0 # Plot +FDC scatter plot +
Boolean parameter: +toggles the Fitness Distance Correlation plot (Fitness vs distance to best). +Default +is false. +

# --plotHisto=0 # Plot histogram +of fitnesses +
Boolean parameter: +if on, gnuplot is used to plot the sorted population (fitness vs rank). +Gives a graphical idea of the diversity. Default +is false. +

+


+

Section ###### +Persistence ###### +
This section contains parameters handling job +dump and restart mechanism. +

# --Load= # -L : A save file +to restart from +
String parameter: +if present, the initial population (and the RNG) is read from indicated +file. That file must +come from a previous save (or must be in same format!), i.e. must contain +a popualtion, the RNG and all parameters. If no other parameter is modified, +using a previously saved population and RNG will give exactly the same +results than having run that previous run longer. And a way to be sure +to re-use the same parameters is to ... use that very save file as parameter +file, as it contains all actual parameters in the right format. +
Note that if not enough individuals are read, +the remaining are randomly initialized. No +default value. +

# --recomputeFitness=0 # +-r : Recompute the fitness after re-loading the pop.? +
Boolean parameter: +in case some individuals are read from a file, their fitness is read too. +If this one is true, it is nevertheless recomputed. Default +is false i.e. use fitnes that's in the file. +

# --saveFrequency=0 # Save +every F generation (0 = only final state, absent = never) +
Integer parameter: +interval between two dump to disk of the whole population (+RNG + parameters), +in a file named genNN.sav in the dirRes +directory, where NN is the generation number. If this prameter is present +(even with 0 or negative value), the final population will always be saved, +whatever the reason for stopping. Hence the only way to avoid all saves +is to omit the parameter (there is no default +value). +

# --saveTimeInterval=0 # +Save every T seconds (0 or absent = never) +
Integer parameter: +time interval between two population (+RNG + parameters) dumps to disks. +Files are names timeNN.sav. See pervious parameter description for ore +details. No default value. +

# --status=t-eoGA.status +# Status file +
String parameter: +name of the status file (that contains all parameters in the input format). +There is no way to avoid creating that file except recompiling ... or giving +the name /dev/null (Unix). Default value is ProgramName.status +

+


+

Section ###### +Stopping criterion ###### +
This section allows to decide when the algorithm +will stop. +

# --maxGen=100 # -G : Maximum +number of generations (0 = none) +
Integer parameter: maximum number of generations. +A value of 0 disables that stopping criterion. Default +is 100. +

# --steadyGen=100 # -s : +Number of generations with no improvement +
Integer parameter: +stops whenever that number of generations is passed without any improvement +of the best fitness in the population, provided the following minimum number +of generations has been done. No default value. +

# --minGen=0 # -g : Minimum +number of generations +
Integer parameter: the above steadyGen parameter +starts its job only after that minimum nuber of generations is passed. +No +default value. +

# --maxEval=0 # -E : Maximum +number of evaluations (0 = none) +
Integer parameter: +maximum number of generations. +No default +value. +

# --targetFitness=0 # -T +: Stop when fitness reaches +
Real-valued parameter: +the algorithm stops whenever the best fitness reaches that target. No +default value. +

# --CtrlC=0 # -C : Terminate +current generation upon Ctrl C +
Boolean parameter: +if true, Ctrl C only stops after the current generation as completed (eventually +dumping population to a file if some saver is active). This very useful +feature is only available in Unix at the moment. Default +is false. +
+


+

User's guide:Bistring +specific parameters +
The following describes the specific parameters that are available +in program BitEA to evolve genotypes that are bitstrings. +
The two representation-dependent sections are concerned repectively +with genotype initilization and variation operators. +

+


+

Section ######    +Genotype Initialization    ###### +
This section should allow input if all necessary +parameters for genitype initialization +

# --ChromSize=10 # -n : The +length of the bitstrings +
Integer parameter: +The bitstring initilization only requires the length of the chromosome. +

+


+

Section ######    +Variation Operators    ###### +
This section allows to tune the way the variation +operators will be applied to the individuals (in the strict limit of SGA +model at the moment, see below). +

# --operator=SGA # -o : Description +of the operator (SGA only now) +
String parameter: +Describes the way the operators are applied. At the moment, only +SGA is available. SGA sequentially +applies a (quadratic) crossover operator with probability pCross +and a mutation operator with probability  pMut. +Both these operators can in turn be proportional +combinations of simple operators of the +same arity. +

# --pCross=0.6 # -C : Probability +of Crossover +
Floating-point parameter: +The probability that a given couple of selected genitors is applied the +crossover operator. In SGA operator model, each couple of selected genitors +is applied the crossover operator with that probability (and remains unchanged +with probability 1-pCross. +Whenever a couple undergoes crossover, a choice is made upon available +crossover operators proportionaly to their +relative rates (see below). Default +is 0.6. +

# --pMut=0.1 # -M : Probability +of Mutation +
Floating-point parameter: +The probability that a given individual (resulting from a crossover or +a non-crossover operation, see above) is applied the mutation operator. +Whenever an individual undergoes mutation, a choice is made upon available +mutation operators proportionaly to their +relative rates (see below). Default +is 0.1. +

# --onePointRate=1 # -1 : +Relative rate for one point crossover +
Floating-point parameter: +Rate of aplication of the 1-point crossover relatively +to 2-point and uniform below (see pCross +parameter). Default is 1. +

# --twoPointRate=1 # -2 : +Relative rate for two point crossover +
Floating-point parameter: +Rate of aplication of the 2-point crossover relatively +to 1-point above and uniform below (see pCross +parameter). Default is 1. +

# --uRate=2 # -U : Relative +rate for uniform crossover +
Floating-point parameter: +Rate of aplication of the 1-point crossover relatively +to 1- and 2-point above (see pCross +parameter). Default is 2. +

# --pMutPerBit=0.01 # -b +: Probability of flipping 1 bit in bit-flip mutation +
Floating-point parameter: +When bit-flip mutation +is applied, each bit is flipped independently with probability  pMutPerBit. +

# --bitFlipRate=0.01 # -s +: Relative rate for bit-flip mutation +
Floating-point parameter: +Rate of aplication of the bit-flip mutation relatively +to one-Bit mutation below (see pMut +above). Default is 0.01 +(if all relative rates are equal, the choice is uniform among available +operators). +

# --oneBitRate=0.01 # -d +: Relative rate for deterministic bit-flip mutation +
Floating-point parameter: +Rate of aplication of the one-bit mutation relatively +to bit-flip mutation below (see pMut +above). One-bit mutation flips one and only one bit, uniformly chosen in +the individual. Default is 0.01 +(if all relative rates are equal, the choice is uniform among available +operators). +
  +

+


+

User's guide:Real-valued +specific parameters +
+To run your own real-valued application, write your fitness function +(see real_value.h
), +recompile, and run from the command line
+

RealEA @RealEA.param

+in order to use sensible parameters! (see Lesson 3 +for details on the parameter file). +But remember that Self-adaptive ES will work much better! +

+The following describes the specific parameters that are available +in programs RealEA +and ESEA +to evolve genotypes that are vector<double>. +
RealEA +implements what can be called a "real-coded GA", where everything is identical +to the bitstring case above (except initialization and operators that are +specific to vector<double> of course) and ESEA +implements the full Evolution-Strategy self-adaptive mutation mechanism +- together with specific ES crossover operators. The initialization section +for both programs are identical, but the operator sections are totally +different. See next paragraph for a description of ES +specific parameters. +

+


+

Section ######    +Genotype Initialization    ###### +
This section should allow input if all necessary +parameters for genitype initialization +

# --vecSize=10 # -n : The +number of variables +
Integer parameter: +The initilization requires the length of the vector<double>. +

# --initBounds=10[-1,1] # +-B : Bounds for uniform initialization +
Bounds parameter: +Bounds for uniform initialization of the real variables. The syntax for +this parameter given in the objectBounds +parameter description below. This argument is mandatory, furthermore the +given bounds must be bounded. +The +default is [-1,1] for all variables. +
Note that this parameter is independent of the objectBounds +parameter below. +

# --sigmaInit=0.3 # -s : +Initial value for Sigma(s) +
Floating-point parameter: +The initial value for all standard-deviation mutation strategy parameters. +Useless when no self-adaptive mutation mechanism is used. +

+


+

Section ######    +Variation Operators    ###### +
This section allows to tune the way the variation +operators will be applied to the individuals (in the strict limit of SGA +model at the moment, see below). +

# --objectBounds=10[-inf,+inf] +# -B : Bounds for variables +
Bounds parameter: +Bounds for object variables. The syntax for this parameter is a succession +of (optionally semi-colon separated) items of the form N[min,Max]where +the optional integer N +indicates how many variables have the given bounds. min +and Max +are either floating point numbers, or -inf +(resp. +inf) +to indicate unbounded direction. If not enough bounds are provided, the +remaining variables will have the same bounds as the last bounds given. +
This argument is mandatory, and +default +is [-inf,+inf], i.e. unbounded variables. +

Examples: +10[-1,1]is +equivalent to simply [-1,1] +or to the extended  [-1,1][-1,1][-1,1][-1,1][-1,1][-1,1][-1,1][-1,1][-1,1][-1,1]. +
And [-1,1];2[0,1];[-inf,10]results +in the first variable staying in [-1,1], the second and the third in [0,1] +and all remaining variables below 10. +

# --operator=SGA # -o : Description +of the operator (SGA only now) +
String parameter: +Describes the way the operators are applied. At the moment, only +SGA is available. SGA sequentially +applies a (quadratic) crossover operator with probability pCross +and a mutation operator with probability  pMut. +Both these operators can in turn be proportional +combinations of simple operators of the +same arity. +

# --pCross=0.6 # -C : Probability +of Crossover +
Floating-point parameter: +The probability that a given couple of selected genitors is applied the +crossover operator. In SGA operator model, each couple of selected genitors +is applied the crossover operator with that probability (and remains unchanged +with probability 1-pCross. +Whenever a couple undergoes crossover, a choice is made upon available +crossover operators proportionaly to their +relative rates (see below). Default +is 0.6. +

# --pMut=0.1 # -M : Probability +of Mutation +
Floating-point parameter: +The probability that a given individual (resulting from a crossover or +a non-crossover operation, see above) is applied the mutation operator. +Whenever an individual undergoes mutation, a choice is made upon available +mutation operators proportionaly to their +relative rates (see below). Default +is 0.1. +

# --alpha=0 # -a : bound +for combination factor in real crossover +
Floating-point parameter: +Bound for the choices of linear combination factors in both crossover belows +(similar to BLX-alpha notation). Default is +0 (i.e. combination factor are chosen in [0,1]). +

# --segmentRate=1 # -s : +Relative rate for segment crossover +
Floating-point parameter: +Rate of application of the segment crossover relatively +to hypercube and uniform crossovers (see pCross +parameter). Segment crossover generates offspring uniformly on the segment +joining both parents, i.e. constructs two linear combinations of the parents +with a random number uniformly drawn in [alpha,1+alpha]. +Default +is 1. +

# --hypercubeRate=1 # -A +: Relative rate for hypercube crossover +
Floating-point parameter: +Rate of application of the hypercube crossover relatively +to segment and uniform crossovers (see pCross +parameter). Hypercube crossover generates offspring uniformly on the hypercube +whose diagonal is the segment joining both parents, i.e. by doing linear +combinations of each variable independently (a random number in [alpha,1+alpha] +is drawn anew for each variable). Default +is 1. +

# --uxoverRate=1 # -A : Relative +rate for uniform crossover +
Floating-point parameter: +Rate of application of the segment crossover relatively +to hypercube and segment crossovers (see pCross +parameter). Uniform crossover simply exchanges values of variables, i.e. +uniformly picks up two other summits of the hypercube defined by the parents. +Default +is 1. +

# --epsilon=0.01 # -e : Half-size +of interval for Uniform Mutation +
Floating-point parameter: +The uniform and deterministic-uniform mutations will choose values of variable +X uniformly in [X-epsilon, +X+epsilon]. +Default +is 0.01. +

# --uniformMutRate=1 # -u +: Relative rate for uniform mutation +
Floating-point parameter: +Rate of aplication of the uniform mutation relatively +to determinitic uniform and the normal mutations (see pMut +above). Uniform mutation modifies all variables by choosing new values +uniformly on an interval centered on the old value of width 2*epsilon +(see above). Default is1. +

# --detMutRate=1 # -d : Relative +rate for deterministic uniform mutation +
Floating-point parameter: +Rate of aplication of the determinisitc-uniform mutation relatively +to uniform and normal mutations (see pMut +above). Deterministic-uniform mutation modifies one single variable uniformly +based on epsilon epsilon. +Default +is1. +

# --normalMutRate=1 # -d +: Relative rate for Gaussian mutation +
Floating-point parameter: +Rate of aplication of the normal mutation relatively +to two uniform mutations above (see pMut +above). Default is1. +

# --sigma=0.3 # -s : Sigma +(fixed) for Gaussian mutation +
Floating-point parameter: +The value of standard deviation for Gaussian mutation - fixed along evolution +(see the Evolution Strategy program below for self-adaptive mutations). +

+


+

User's guide:ES +with self-adative mutation parameters +
+To run your own SA-ES application, write your fitness function +(see real_value.h
), +recompile, and run from the command line
+

ESEA @ESEA.param

+in order to use sensible parameters! (see Lesson 3 +for details on the parameter file). +

+The following describes the specific parameters for program ESEA, +that implements the full Evolution-Strategy self-adaptive mutation mechanism +- together with specific ES crossover operators. The initialization section +is the same as the one for plain vector<double> above, so only the opeartor +sections will be described here. A new section is now concerned with deciding +what kind of self-adaptive mutation strategy will be applied - it has been +separated from the other variation operators because it has consequences +on the choice of the genotype. +
Warning: if you choose not to use +any self-adaptive mechanism (i.e. setting all parameters of this section +to false) you end up with ... an algorithm that is identical to RealEA +above (try it and take alook at the status file). +

+


+

Section ######     +ES mutation    ###### +
This section allows to decide which type of self-adaptive +mutation will be used. There are three available types: isotropic mutation, +using one standard deviation for each individual, that will be applied +to all variables; anisotropic mutation, where each individual carries as +many standard deviations as it has variables; and correlated mutation where +each individuals has its own full correlation matrix. +

# --Isotropic=1 # -i : Isotropic +self-adaptive mutation +
Boolean parameter: +If true, at least one self-adaptive parameter will be used for each individual. +Default +is true. +

# --Stdev=0 # -s : One self-adaptive +stDev per variable +
Boolean parameter: +If true, at least one self-adaptive parameter per variable will be used +for each individual. Default is false. +

# --Correl=0 # -c : Use correlated +mutations +
Boolean parameter: +If true, full correalted self-adaptive mutation will be used for each individual. +Default +is false. +

Note: The +default values result in an isotropic self-adaptive mutation to be chosen. +

+


+

Section ######    +Variation Operators    ###### +
Only the parameters that are specific to ESEA +are presented here - the objectBounds,operator,pCross +and pMut +are exactly the same as for RealEA +above. +

# --crossType=global # -C +: Type of ES recombination (global or standard) +
String parameter:  +Es crossover can involve only two parents - and it is then identical to +the standard +hypercube crossover describe for the RealEA +parameters above. But new parents can also be chosen anew for each variable +before doing the crossover for that variable - and this is called global +recombination. +

# --crossObj=discrete # -O +: Recombination of object variables (discrete or intermediate) +
String parameter:  +There are two possible crossovers in plain ES. The discrete +crossover simpy exchanges variables among the parents. It is similar to +the plain uniform crossover for real variables. The  crossover performs +a linear combination of parents;variables - it si similar to the hypercube +crossover described for  with alpah parameter set to 0. This parameter +allso to choose the type of crossover that will be applied to the object +variables (i.e. the origianl variables +of the problem). Default is discrete. +

# --crossStdev=intermediate +# -S : Recombination of mutation strategy parameters (intermediate or discrete) +
String parameter:  +This parameter allows to choose the type of crossover (see above) that +will be applied to the mutation strategy +parameters that are part of the genotype. +Default +is intermediate. +

# --TauLoc=1 # -l : Local +Tau (before normalization) +
Floating-point parameter: +The local factor for the mutation of the mutation strategy parameters (the +only one used when a single standard deviation is used). Default +is 1. +

# --TauGlob=1 # -g : Global +Tau (before normalization) +
Floating-point parameter: +The global factor for the mutation of the mutation strategy parameters +(only useful when more than one standard deviation are used). Default +is 1. +

# --Beta=0.0873 # -b : Beta +
Floating-point parameter: +The factor for the mutation of the rotation angles in the case of the full +correlated mutation. Default is 0.0873 +(following Schwefel). +

+


+
Programmer's +guide +

At the moment, you will have to browse in the source (colored!) code +(Bit - Real) almost by yourself, sorry. +

Note that the main file is now very slim, as it only contains calls +to some make_xxx +functions - these functions contain the actual code, very similar to the +code of Lesson3, except for the memory management, performed through an +eoState +object (notice that all make_xxx +calls have an eoState as second parameter). +

Programmer's guide: The +make_xxx files +

Interface: all make_xxx +files have as first two parameters an eoParser +and an eoState. +The eoParser +is be used within all functions to parse the command-line and/or a parameter +file in order to read any relevant user-parameter, while the eoState +is used here to store all pointers to be allocated inside the function +(see Programming hints for more +detailed explanations). +

There are 2 types of make_xxx +files: the ones that do depend on representation, defining the genotype +and +initialization +(make_genotype_xxx, +with xxx being the type of genotype) and variation operators (make_op_xxx), +and the one that are truly representation-independent (make_pop, +make_continue, make _checkpoint, make_algo and +make_run). +
The former are located in the directory corresponding to the actual +genotype (src/ga +for eoBit, src/es +for eoReal and all eoESxxx genotypes). The latter are in the directory +src/do. +

If you take a close look at the code of make_continue +for instance, you will first notice that ... the function declared there +is called do_make_continue +and is not the one you are calling in +the main file, though it has the same parameters as arguments. +
The explanation lies within the file make_continue_xxx.cpp +(with xxx = ga or real/es)which, as its color (and name)  should have +told you about, are representation-dependent: in fact the make_continue_xxx.cpp +files only instanciates the general <EOT> template into one of the possible +template for eoBit or eoReal/eoES - and this trick allows to compile +them separately! +

The other thing that you should notice is that the code there is very +similar to the code that was in Lesson 3,  regarding parameter reading +and type of object that are allocated - except for memory management. This +goes for all make_xxx +files - so the only thing you need to understand how it goes is to look +at the memory management section. +

Pros: you don't have to handle a +huge main function - and many of the make_xxx files can be directly used +in different applications (this is called modularity +:-))) +
More interesting, you can even compile +the make_xxx +files separately for a given target +template, and link them e.g. with your fitness function when it is ready +(remember that up to now you needed to compile everything altogether by +including the code into your mail fine). Indeed, if you do a global make, +you will notice that there are additional libraries compiled in src/ga +and src/es +... +

Cons: It makes the code a little +more complex to understand, first because of the indirection needed for +pre-compilation with a given template, and second because of the memory +management that this imposes. +
  +
  +

Programmer's +guide: Memory management +
As already said, all functions have an eoState +as second argument - and that object is used to store the functor objects +that were simply declared as variables of the main function up to now : +see Programming hints for more +detailed explanations and take a look at the code of make_continue +for instance, you will see the implementation of the memory management +in action. +

Programmer's +guide: Memory management +of eoParam objects +

It has been seen in Lesson 3 that parameters could be read from command-line +and/or a parameter file using an eoParser +object. However, the memory mangement problem also concerns EO parameter +objects (eoParam): +the way there are read in Lesson3 +makes them local variables of the function they are defined in. +
It is however possible to ask the eoParser +to hold them, as done for instance in eoContinue for the maximum number +of generations. Local declaration would amount to something like : +

eoValueParam<unsigned +int>& maxGenParam(100, "maxGen", "Maximum number of generations () += none)",'G'); +
 parser.processParam( +maxGenParam, "Stopping criterion" ); +
 unsigned maxGen = +maxGenParam.value(); +

while if you want the parser to hold those eoParam objects, you will +write something like +

eoValueParam<unsigned>& +maxGenParam = _parser.createParam(unsigned(100), "maxGen", "Maximum number +of generations () = none)",'G',"Stopping criterion"); +

and then use maxGenParam.value() +to get the value enterred by the user. In that case, you get a reference +to an eoParam object that is hold by the eoParser - and deleted whith it. +
Note that there are two important differences +between the arguments of the constructor of an eoParam object and the method +createParam of an eoParser object: first, you need to provide the additional +section parameter (used only when outputting the eoParser); second you +must +make sure that the first argument is of the correct type otherwise the +compiler will complain. +

Note that if you don't later need the eoParam, but simply its value, +you can even diretly write +

unsigned maxGen = _parser.createParam(unsigned(100), +"maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion").value(); +

Getting parameter values in different +functions: +

It is often useful (though probably very bad +programming style :-))) to be able to get the value of a user-defined +parameter in two different places of the code without passing it around +through many levels of call. You can then use the alternate function getORcreateParam +with exactly the same syntax than createParam. +
Be careful that the link between both parameters is made through their +longmanes (second argument), and that you must so hard-code +that name in two different places with of course exactly the same spelling!!! +
Examples can be found for instance +in the make_genotype_xxx files, for the sizes of the genotypes: it is often +the case that the definition of the optimization problem requires (or computes) +such size. The idea is then that you either read or compute that size, +then create a (dummy) parameter with the name that is used later in the +make_genotype file. For instance, for bitstrings, the make_genotype_ga.h +contains the following line defining the size of the bitstring +

  unsigned theSize = +_parser.getORcreateParam(unsigned(10), "chromSize", "The length of the +bitstrings", 'n',"Problem").value(); +

If you want to define that size earlier, you should write somewhere +before +
  +

  unsigned requiredSize  += ... ; +
 _parser.createParam(requiredSize, +"chromSize", "The length of the bitstrings", 'n',"Problem"); +

Of course, if that size is mandatory, you should NOT modify it at run-time +by entering anther value ! +

+


User's guide: General +- Bitstring - Real - ES +- Programmer's guide: General +- Memory management - Parameters +
+
Lesson +3 - +Lesson 5 - +Main +page - +Algorithm-Based - Component-Based +- Hints - EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: None of your business! + + diff --git a/deprecated/eo/tutorial/html/eoLesson5.html b/deprecated/eo/tutorial/html/eoLesson5.html new file mode 100644 index 000000000..fcb025784 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoLesson5.html @@ -0,0 +1,415 @@ + + + + + + Tutorial: Lesson 5 + + +Lesson 4 - +Lesson +6 - +Main page - +Algorithm-Based +- Component-Based - Hints +- EO +documentation +
+
+
+

+Tutorial Lesson 5: using your own genotype

+In this lesson, you will learn how to design and evolve your +own genotype structure. Note that 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 :-) +

The minimum code you'll have to write is first, of course, the code +for the genotype structure. Then, the representation-dependent +code: intialization procedure(s), +variation +operators (quadratic crossover, mutation operator), ... and evaluation +function - and that's it : we have prepared some template files and +the script create.sh that will take care of generating a few other files +to make your application complete. +

In what follows, we will suppose that you want to evolve some data structure, +and that you have enough programming skills to be able to write C code +for its random initilialization, its crossover, its mutation and the computation +of its fitness. +
The examples will be described supposing you want to evolve ... bitstings +to solve the OneMax problem (oh no!!!). +

+ +New May 2004 : A +second script, createSimple, + was added some time ago, that generates much simpler +set of files, and the stat.tmpl +file is now used to allow you to +compute and +print and +save-to-disk and +plot-on-line your +own statistics. +But you'll have to find out by yourself how those work, sorry, no +time. It should be easy by just looking at the code (in main file, and +in OneMaxEA.cpp +and the newly created +eoOneMaxStat.h.

+ +New May 2004 : In +the same simplified main file (e.g. OneMaxEA.cpp after running +./createsimple OneMax in +dir .../eo/tutorial/Templates), you +will also be able to use fitness sharing (together with roulette) as a +possible selector. + + +


Using +template files +
Follow this very simple procedure: +
    +
  • +choose a name for you application - +here OneMax will be used
  • + +
  • +go to the tutorial/Templates +dir
  • + +
           cd +pathWhereEOisInstalled/tutorial/Templates +
  • +run the create.sh script with +argument OneMax and second optional argument  a directory name (suppose +it's called APPLICATION here)
  • + +
              +./create.sh OneMax APPLICATION +
    This will create a directory tutorial/APPLICATION +
  • +Go to the APPLICATION directory
  • + +
              +cd ../APPLICATION +
    You should see the following files: +
        OneMaxEA.cpp           +the main main file, includes all other, to be compiled +
        Makefile               +with default target eoOneMaxEA +
        eoOneMax.h             +class eoOneMax, the genotype +
        eoOneMaxEvalFunc.h     + +class for the computation of fitness +
        eoOneMaxInit.h         +class for genotype initlialization +
        eoOneMaxMutation.h     +class for mutation +
        eoOneMaxQuadCrossover.h +class +for (quadratic) crossover +
        make_genotype_OneMax.h + +helper function that create the initializer +
        make_op_OneMax.h       +helper function that handles the rates of application of +the variation operators
    +    OneMaxLibEA.cpp        +another main file, for separate compilation of representation-independent +stuff +
        make_OneMaxEA.cpp      +the source for the representation-independent stuff +
      +
  • +Compile the whole application
  • + +
             +make +
    and you should have no error there and see a new executable file named +OneMaxEA. +You can run it and ... it will do nothing (what did you expect???).
    +
    +
  • +Now you should go and edit the files. The minimal  changes that you +will need are
  • + +
       in eoOneMax.h               +define your genotype +
       in eoOneMaxInit.h           +define the initialization of one genotype +
       in eoOneMaxMutation.h       + +define the mutation of one genotype +
       in eoOneMaxQuadCrossover.h  + +define the crossover of 2 genotypes
+Smooth application building: +
    +
  • +After editing a particular file, compile +the whole thing immediately (by running make) and +run the algorithm, to validate your code
  • + +
  • +In each file, start by only adding code between keyword-pairs START +and END
  • +
+We shall now take a look in turn at the 4 files mentionned above, then +describe rapidly the other files, especially the main files. +
+
Genotype +- and its pre-requisites: eoOneMax.h +

First thing is to write the code for the structure +of the genotype. This is done by filling in the template file +eoOneMax.h. +There are 4 places that you should consider filling in: +

    +
  • +Of course, the data that will build up +the genotype. The convention in EO is to have it at the end of the class +definition, and as private data.
  • + +
  • +The default constructor of an instance. +Note that you must provide a default constructor, +and that no other constructor will be called within EO code. you might +think you need some other constructor to initialize problem-specific data. +This should be rather done in the eoInit object used to randomly initialize +all individuals, or in the eoEvalFunc object, used to compute the fitness.
  • + +
  • +The printOn method, that writes the object +to a stream. You must +call the EO::printOn method that will take care of the fitness, +and then write the specific code for your data structure.
  • + +
  • +The readFrom method, that will read an +object from a stream. Again, you should call the +EO::readFrom method first to take care of the fitness.
  • + +
    Also note that readFrom will be generally called from an object that +will have been constructed through the default constructor. This is why +the EO objects that we provide always start printing structures with their +length...
+You can of course also add a destructor +if needed, and any other helper method. For instance, you will probably +consider adding accessors and setters +for the private data - unless you prefer to make everything public :-( +
See now an example of a comple eoOneMax.h +file. Note that this is the only "colored" completed file we will show, +you will have to go to the .../tutorial/OneMax +dir to browse all files at once. +
+
Initialization: +

Initializer: eoOneMaxInit.h +
You must provide an eoInit +object for your genotype, that is an object that will randomize +a genotype built by the default constructor of the EO class +(here, an eoOneMax object) . Here you must at least fill the +code for such randomization. +
But you might also need some parameters (e.g. the size of the bitstring +in eoOneMax): you should then pass +them through the constructor of the eoOneMaxInit class, and store +it in its private data. +
And of course you might need to add a destructor (no example here) +if you use complex data type in the object. +

Parameters: make_genotype_OneMax.h +
There is another file you will probably want to modify as far as initialization +is concerned, that is make_genotype_OneMax.h. +Such helper files are used for all components of advanced EO programs (see +Lesson 4). The main reason for that is to allow separate compilation of +such sub-components for known EO types, as this is done in the directories +src/ga and src/es. But a useful consequence is to make your code modular. +For instance, the make_genotype_OneMax.h +file takes care of all the preparation of all data regarding the eoInit +object - and returns to the main fonction a reference to an eoInit that +will later be used to initialize the whole +population in a representation-independent way. +
What you have to do in that file is to set values for all parameters +needed by the eoOneMaxInit class, for instance by reading them from the +parser: this allows later to modify them easily from the command-line. +Note however that an alternative could be to pass the parser to the constructor +of the eoOneMaxInit class, and to read all parameters there... +
Note: Remember that the make_xxx +files were first introduced to allow the user to compile sepearately most +of the code of standard Evolutionary Algorithm written in EO for bitstring +and real vector representations ( +
+


Evaluation: +eoOneMaxEvalFunc.h +

The eoOneMaxEvalFunc is +the object that will compute the fitness of an +eoOneMax object. You have to fill in the code +for the computation of the fitness value (there is no way that this +can be done automatically :-) Note that this code must  be run only +if the _eo.invalid() test +returns true, to avoid computing the fitness of an object that has not  +been modified and thus still holds a valid fitness value. After computing +the fitness, store it into the object by calling the fitness(FitnessType) +method. +
Should you need some specific data for that, the constructor +of the object is the place to get such data, and you should, again, +store it in some private data +of the class. +
+


Variation +Operators +
You can write as many crossover and mutation operators as you like. +However, we only provide the template files for quadratic +crossover and mutation, but +you could then easily write the equivalent code for binary crossover, or +general variation operator. +

Crossover: eoOneMaxQuadCrossover.h +
As usual, you must go and write the code +for the operator() that will perform the crossover, possibly modifying +both arguments. Don't forget to update the boolean +parameter that will report whether the genotypes have been modified +- allowing to recompute the fitness only of the ones that have actually +been modified. You can also have parameters +to the crossover by passing +them to the constructor, ans storing them in the private +data of the crossover object. +

Mutation: eoOneMaxMutation.h +
Here again, you must go and write the code for the operator() that +will perform the mutation, eventually modifying its arguments. Don't forget +to update the boolean parameter that +will report whether the genotype has been modified - allowing to recompute +the fitness only of the ones that have actually been modified. You can +also have parameters to the mutation +by passing them to the constructor, +ans storing them in the private data +of the mutation object. +

Parameters: make_op_OneMax.h +
First of all, if you intend to use only one +crossover operator and one mutation +operator, you have nothing to modify +in make_op_OneMax function, except maybe +reading user-defined parameters (copy the code from make_genotype_OneMax) +and passing them to the appropriate +operator constructor. +
As it is written now, it allows you enter a crossover probability Pcross +and a mutation probability Pmut, +and to build an eoGeneralOp that will call in sequence the eoOneMaxQuadCrossover +that is defined above with probability Pcross +and the eoOneMaxMutation also +defined above with probability Pmut.  +Beware that all allocated objects must be stored in the eoState otherwise +you will run into trouble (see EO Memory +Management explanations). +

However, everything is there (commented out) to allow you to use more +than one crossover and one mutation +- provided you write the code for them , of course. +

The code starts by defining an eoOneMaxQuadCrossoverobject, +then reads some application rate that is totally useless if you have only +one crossover, then creates an eoPropCombinedQuadOp +with this simple oeprator. The same story repeats for the mutation. Finally, +the eoGeneralOp +is created from those combined operators and the individulal level probabilities +Pcross +and  Pmut. +

In order to add a second crossover operator for instance (called eoOneMaxSecondCrossover +in the commented code) all you need to is +

    +
  • +Create the code for the new class  eoOneMaxSecondCrossover: +simply copy the eoOneMaxQuadCrossover.h +file into eoOneMaxSecondCrossover.h  +and change all names eoOneMaxQuadCrossover +to  eoOneMaxSecondCrossover (inlcluding +after the #ifdef statement!!!);
  • + +
  • +Uncomment the corresponding lines +in make_op_OneMax.h, possibly adding user-defined parameter reading
  • + +
  • +Repeat as many times as you have operators, using of course different names! +The same recommendations hold for mutations.
  • +
+In case you have more than one operator of a kind, then of course the relative +weights of application do make sense, allowing you to tune with command-line +parameters the proportion with which each operator that will be applied. +

+


Main +files: OneMaxEA.cpp +and OneMaxLibEA.cpp +

As a start, you should only (eventually) modify in OneMaxEA.cpp +the type of fitness you +will be handling, namely double +if you are maximizing, or eoMinimizingFitness +if you are minimizing. Then running +make will result in a perfectly +valid executable named OneMaxEA. +

The skeleton of the main file here mimics that of the main file in +Lesson4, +and uses the make_xxx separate +files construct: the part of an Evolutionary Algorithm related to the +evolution +engine is indepenent of the representation, +and can be directly used ... provided it is compiled with the right template +(remember everything in EO is templatized +over the EO objects it handles.  Main file OneMaxEA.cpp +is written so that it includes eveything - and thus everytime you run make +(or make OneMaxEA), you compile +the code for make_pop, make_continue and make_checkpoint that is defined +in the .../src/do directory. +

The basic construct is (for instance to build the evolution engine) +
  + + + + +
#include <do/make_algo_scalar.h> +
eoAlgo<Indi>&  make_algo_scalar(eoParser& +_parser, eoState& _state, eoEvalFunc<Indi>& _eval, eoContinue<Indi>& +_continue, eoGenOp<Indi>& _op) +
{ +
 return do_make_algo_scalar(_parser, +_state, _eval, _continue, _op); +
}
+First, include the code (from the do directory). Then define the make_xxx +function from the do_make_xxx function. +
Of course, such construct is stupid here, as you could perfectly call +directly the do_make_xxx function in the main. However, if you ever want +to do separate compilation of some parts, you will need such construct +(see Lesson4) so we have kept it here for +consistency reasons. +

Go in your application directory, and look at the differences between +both files and you'll see how this is handled in both cases. +

Reducing compilation time: +
However, we also provide another main file (OneMaxLibEA.cpp)that +only includes the code that is specific to your application, and is supposed +to be linked with another object file that will contain the code that is +representation independent (make_OneMax.cpp).  +This is done by running make OneMaxLibEA +on the command-line. +
For example, on a PentiumIII 400MHz with g++ 2.96, compiling OneMaxEA +takes about 33s, compiling both make_OneMax.o +and OneMaxLibEA takes about +54s but compiling only OneMaxLibEA +takes only 14s  make_OneMax.o +is up-to-date ... +

Hints: +
While developping the genotype structure itself in file eoOneMax.h, +you should use the OneMaxEA.cpp +file. But after the eoOneMax.h +file is frozen, you should use the eoOneMaxLibEA.cpp +file. Of course, both  resulting programs are strictly identical! +

+


Lesson +4 - +Lesson 6 - +Main +page - +Algorithm-Based - Component-Based +- Hints - EO +documentation +
+
+
+Marc Schoenauer
+ + + diff --git a/deprecated/eo/tutorial/html/eoOneMax.html b/deprecated/eo/tutorial/html/eoOneMax.html new file mode 100644 index 000000000..8f8cfb03e --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOneMax.html @@ -0,0 +1,209 @@ + + + + + + Templates/eoOneMax.h + + +Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+
+

+Templates/eoOneMax.h

+The places where you have to put some code are on pink +background.. Only the the character +colors have the usual meaning. +
+ + + + +
/** -*- mode: c++; c-indent-level: +4; c++-member-init-indent: 8; comment-column: 35; -*- +
The above line is usefulin Emacs-like editors +
*/ +
/* +
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 +
* Note that you MUST derive your structure +from EO<fitT> +
* but you MAY use some other already prepared +class in the hierarchy +
* 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  +
*              +a default constructor +
*              +IO routines printOn and readFrom +
* +
* Note that operator<< and operator>> +are defined at EO level +
* using these routines +
*/
+ + + + + +
template< class FitT> +
class eoOneMax: public EO<FitT> { +
public: +
  /** Ctor: you MUST provide +a default ctor. +
   * though such individuals will +generally be processed  +
   * by some eoInit object +
   */ +
 eoOneMax()  +
 { 
+ + + + + +
      +// START Code of default Ctor of an eoOneMax object +
      // +END    Code of default Ctor of an eoOneMax object
+ + + + + +
 } +

 virtual ~eoOneMax() +
 {

+ + + + + +
      +// START Code of Destructor of an eoEASEAGenome object +
      // +END    Code of Destructor of an eoEASEAGenome object
+ + + + + +
 } +

 virtual string className() const +{ return "eoOneMax"; } +
 

+ + + + + +
  /** printing... */ +
 void printOn(ostream& os) const +
 { +
      // +First write the fitness +
     EO<FitT>::printOn(os); +
     os << ' +';
+ + + + + +
      +// START Code of default output  +

/** HINTS +
* in EO we systematically write the sizes +of things before the things +
* so readFrom is easier to code (see below) +
*/ +

      // END    +Code of default output

+ + + + + +
     } +

  /** reading...  +
   * of course, your readFrom must +be able to read what printOn writes!!! +
   */ +
 void readFrom(istream& is) +
 { +
      // +of course you should read the fitness first! +
     EO<FitT>::readFrom(is);

+ + + + + +
      +// START Code of input +

/** HINTS +
* remember the eoOneMax object will come +from the default ctor +
* this is why having the sizes written out +is useful +
*/ +

      // END    +Code of input

+ + + + + +
 } +
 
+ + + + + +
private:     // +put all data here
+ + + + + +
      // +START Private data of an eoOneMax object +
      // +END    Private data of an eoOneMax object
+ + + + + +
}; +

#endif

+ +
Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Fri May +3 06:06:09 2002 + + diff --git a/deprecated/eo/tutorial/html/eoOneMaxEvalFunc.html b/deprecated/eo/tutorial/html/eoOneMaxEvalFunc.html new file mode 100644 index 000000000..4d6eefbff --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOneMaxEvalFunc.html @@ -0,0 +1,160 @@ + + + + + + Templates/eoOneMaxEvalFunc.h + + +Back to Lesson 5 +- Tutorial main page - Top-Down +page - Bottom-up page - Programming +hints - EO +documentation +
+
+
+

+Templates/eoOneMaxEvalFunc.h

+The places where you have to put some code are on pink +background.. Only the the character +colors have the usual meaning. +
+ + + + +
/** -*- 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 +

// include whatever general include you need +
#include <stdexcept> +
#include <fstream> +

// 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 +
*/

+ + + + + +
template <class EOT> +
class eoOneMaxEvalFunc : public eoEvalFunc<EOT> +
{ +
public: +
/// Ctor - no requirement
+ + + + + +
// START eventually +add or modify the anyVariable argument +
 eoOneMaxEvalFunc() +
  //  eoOneMaxEvalFunc( +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
+ + + + + +
 } +

  /** Actually compute the fitness +
   * +
   * @param EOT & _eo the EO +object to evaluate +
   *                                  +it should stay templatized to be usable  +
   *                                  +with any fitness type +
   */ +
 void operator()(EOT & _eo) +
 { +
      // +test for invalid to avoid recomputing fitness of unmodified individuals +
     if (_eo.invalid()) +
         +{ +
double fit;     +// to hold fitness value

+ + + + + +
      +// START Code of computation of fitness of the eoOneMax object +
// fit = blablabla +
      // +END    Code of computation of fitness of the eoOneMax object
+ + + + + +
_eo.fitness(fit); +
         +} +
 } +

private:

+ + + + + +
// START Private data +of an eoOneMaxEvalFunc object +
  //  varType anyVariable;    +// for example ... +
// END    Private data of +an eoOneMaxEvalFunc object
+ + + + + +
}; +
#endif
+ +
Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Fri May +3 06:14:25 2002 + + diff --git a/deprecated/eo/tutorial/html/eoOneMaxInit.html b/deprecated/eo/tutorial/html/eoOneMaxInit.html new file mode 100644 index 000000000..07475be6f --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOneMaxInit.html @@ -0,0 +1,153 @@ + + + + + + Templates/eoOneMaxInit.h + + +Back to Lesson 5 - +Tutorial main page - Top-Down +page - Bottom-up page - Programming +hints - EO +documentation +
+
+
+

+Templates/eoOneMaxInit.h

+The places where you have to put some code are on pink +background.. Only the the character +colors have the usual meaning. +
+ + + + +
/** -*- mode: c++; c-indent-level: +4; c++-member-init-indent: 8; comment-column: 35; -*- +
The above line is usefulin Emacs-like editors +
*/ +

/* +
Template for EO objects initialization in +EO +
============================================ +
*/ +

#ifndef _eoOneMaxInit_h +
#define _eoOneMaxInit_h +

// include the base definition of eoInit +
#include <eoInit.h> +

/**  +
*  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  +
*      atoms of +an eoVector you will need an eoInit<AtomType>) +
*/

+ + + + + +
template <class GenotypeT> +
class eoOneMaxInit: public eoInit<GenotypeT> +{ +
public: +
/// Ctor - no requirement
+ + + + + +
// START eventually +add or modify the anyVariable argument +
 eoOneMaxInit() +
  //  eoOneMaxInit( varType  +_anyVariable) : anyVariable(_anyVariable)  +
// END eventually add or modify the anyVariable +argument
+ + + + + +
 {
+ + + + + +
      // +START Code of Ctor of an eoOneMaxInit object +
      // +END    Code of Ctor of an eoOneMaxInit object
+ + + + + +
 } +

  /** initialize a genotype +
   * +
   * @param _genotype  generally +a genotype that has been default-constructed +
   *                                    +whatever it contains will be lost +
   */ +
 void operator()(GenotypeT & +_genotype) +
 {

+ + + + + +
      +// START Code of random initialization of an eoOneMax object +
      // +END    Code of random initialization of an eoOneMax object
+ + + + + +
     _genotype.invalidate();     +// IMPORTANT in case the _genotype is old +
 } +

private:

+ + + + + +
// START Private data +of an eoOneMaxInit object +
  //  varType anyVariable;    +// for example ... +
// END    Private data of +an eoOneMaxInit object
+ + + + + +
}; +

#endif

+ +
Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Fri May +3 06:17:21 2002 + + diff --git a/deprecated/eo/tutorial/html/eoOneMaxMutation.html b/deprecated/eo/tutorial/html/eoOneMaxMutation.html new file mode 100644 index 000000000..5181567ff --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOneMaxMutation.html @@ -0,0 +1,168 @@ + + + + + + eoOneMaxMutation.h + + +Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+
+

+eoOneMaxMutation.h

+The places where you have to put some code are on pink background. +Only the the character colors have the usual meaning. +
  + + + + + +
+/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
+The above line is useful in Emacs-like editors
+ */
+/*
+Template for simple mutation operators
+======================================
+*/
+#ifndef eoOneMaxMutation_H
+#define eoOneMaxMutation_H
+#include <eoOp.h>
+/**
+ *  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<class GenotypeT>
+class eoOneMaxMutation: public eoMonOp<GenotypeT>
+{
+public:
+  /**
+    * Ctor - no requirement
+    */
+
+
+ + + + +
+ +// START eventually add or modify the anyVariable argument
+  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
+
+
+ + + + +
+ +  }
+  /// The class name. Used to display statistics
+  string className() const { return "eoOneMaxMutation"; }
+  /**
+    * modifies the parent
+    * @param _genotype The parent genotype (will be modified)
+    */
+  bool operator()(GenotypeT & _genotype)
+  {
+      bool isModified;
+
+
+ + + + +
+ +      // 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
+
+
+ + + + +
+ +  }
+private:
+
+
+ + + + +
+ +// START Private data of an eoOneMaxMutation object
+  //  varType anyVariable;    // for example ...
+// END    Private data of an eoOneMaxMutation object
+
+
+ + + + +
+ +};
+#endif
+
+
Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+
Last +modified: Wed May 1 07:18:00 2002 + + + diff --git a/deprecated/eo/tutorial/html/eoOneMaxQuadCrossover.html b/deprecated/eo/tutorial/html/eoOneMaxQuadCrossover.html new file mode 100644 index 000000000..a91a653ea --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOneMaxQuadCrossover.html @@ -0,0 +1,168 @@ + + + + + + Templates/eoOneMaxQuadCrossover.h + + +Back to Lesson +5 - Tutorial main page - Top-Down +page - Bottom-up page - Programming +hints - EO +documentation +
+
+
+

+Templates/eoOneMaxQuadCrossover.h

+The places where you have to put some code are on pink +background.. Only the the character +colors have the usual meaning. +
+ + + + +
/** -*- mode: c++; c-indent-level: +4; c++-member-init-indent: 8; comment-column: 35; -*- +
The above line is usefulin Emacs-like editors +
*/ +
/* +
Template for simple quadratic crossover operators +
================================================= +
Quadratic crossover operators modify the +both genotypes +
*/ +

#ifndef eoOneMaxQuadCrossover_H +
#define eoOneMaxQuadCrossover_H +

#include <eoOp.h> +

/**  +
*  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<class GenotypeT>  +
class eoOneMaxQuadCrossover: public eoQuadOp<GenotypeT> +
{ +
public: +
  /** +
   * Ctor - no requirement +
   */
+ + + + + +
// START eventually +add or modify the anyVariable argument +
 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
+ + + + + +
 } +

  /// The class name. Used to +display statistics +
 string className() const { return +"eoOneMaxQuadCrossover"; } +

  /** +
   * eoQuad crossover - modifies +both parents +
   * @param _genotype1 The first +parent +
   * @param _genotype2 The second +parent +
   */ +
 bool operator()(GenotypeT& _genotype1, +GenotypeT & _genotype2)  +
 { +
     bool oneAtLeastIsModified;

+ + + + + +
      +// 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
+ + + + + +
 } +

private:

+ + + + + +
// START Private data +of an eoOneMaxQuadCrossover object +
  //  varType anyVariable;    +// for example ... +
// END    Private data of +an eoOneMaxQuadCrossover object
+ + + + + +
}; +

#endif

+ +
Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Fri May +3 07:47:13 2002 + + diff --git a/deprecated/eo/tutorial/html/eoOneMax_complete.html b/deprecated/eo/tutorial/html/eoOneMax_complete.html new file mode 100644 index 000000000..0c6c24680 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOneMax_complete.html @@ -0,0 +1,192 @@ + + + + + + Templates/eoOneMax_complete.h + + +Back to Lesson 5 +- Tutorial main page - Top-Down +page - Bottom-up page - Programming +hints - EO +documentation +
+
+
+

+Templates/eoOneMax_complete.h

+The user-defined code is on pink background.. +Only the the character colors have the +usual meaning. +

+ + + + +
/** -*- mode: c++; c-indent-level: +4; c++-member-init-indent: 8; comment-column: 35; -*- +
The above line is usefulin Emacs-like editors +
*/ +

/* +
Template for creating a new representation +in EO +
================================================ +
*/ +

#ifndef _eoOneMax_h +
#define _eoOneMax_h +
 

+ + + + + +
/**  +
* A simple example class for bitstring (is +NOT supposed to be used :-) +
*/
+ + + + + +
+ + + + + +
template< class FitT> +
class eoOneMax: public EO<FitT> { +
public: +
  /** Deafult Ctor: nothing to +be done */ +
 eoOneMax() {} +

 virtual string className() const +{ return "eoOneMax"; } +
 

+ + + + + +
  /** printing... */ +
     void printOn(ostream& +_os) const +
     { +
          +// First write the fitness +
         +EO<FitT>::printOn(_os); +
         +_os << ' ';
+ + + + + +
         +_os << b.size() << ' ' ; +
         +for (unsigned i=0; i<b.size(); i++) +
             +_os << b[i] << ' ' ;
+ + + + + +
     } +

  /** reading...  +
   * of course, your readFrom must +be able to read what printOn writes!!! +
   */ +
 void readFrom(istream& _is) +
 { +
      // +of course you should read the fitness first! +
     EO<FitT>::readFrom(_is);

+ + + + + +
     unsigned s; +
     _is >> s; +
     b.resize(s); +
     for (unsigned +i=0; i<s; i++) +
         +{ +
             +bool bTmp; +
             +_is >> bTmp; +
             +b[i] = bTmp; +
         +} 
+ + + + + +
 }
+ + + + + +
+ + + + + +
  // brute setting (we could +also have defined a Ctor from a vector<bool>) +
 void setB(vector<bool> & +_b) +
 { +
     b=_b; +
 } +

  // brute accessing (we could +also define operator[] ...) +
 const vector<bool> & B() +
 { +
     return b; +
 }

+ + + + + +
+
private:     // +put all data here
+ + + + + +
 std::vector<bool> b;
+ + + + + +
}; +

#endif

+ +


Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Sat May +4 06:02:46 2002 + + diff --git a/deprecated/eo/tutorial/html/eoOperators.html b/deprecated/eo/tutorial/html/eoOperators.html new file mode 100644 index 000000000..4de7b40fd --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOperators.html @@ -0,0 +1,818 @@ + + + + + + Variation Operators + + +General: Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
+
+
Local: Introduction +- Crossover - Mutation +- Combinations - General +Operators - Populators - General +combinations- Advanced operators +
+
+
+

+Variation Operators

+Variation +Operators +
Variation operators modify the gnotype of individuals, or, equivalently, +move them in the search space. In Evolutionary Algorithms, varitaion operators +are almost always stochastic, i.e. +they are based on random numbers, or equivalently, perform random modifications +of their arguments. Variation operators are classified depending on the +number of arguments they use and/or modify. +
    +
  • +Variation operators involving two individuals +are called crossover operators. They can either +modify one of the parents according to the material of the other parent, +or modify both parents. In EO, the former are called Binary operators and +the latter Quadratic operators.
  • + +
  • +Variation operators involving one single individual +are called mutation operators.
  • + +
  • +Straightforward extensions of these simple operators allow to combine them: +in +proportional combinations, one operator +is chosen among a given set of operators of same arity according to some +weights.
  • + +
  • +In EO you can also define and use variation operators that generate any +number of offspring from any number of parents (sometimes termed orgy +operators). They are called general operators.
  • + +
  • +However, the interface of such operators was designed for their use inside +general +combinations: you can use proportional combination, +in which one operator is chosen among a given set of operators of same +arity according to some weights, as for simple operators except that operators +of different arities can be mixed, but you can also use sequential +combinations, where different operators  are applied in +turn with given probability. But you can also embed any of such combinations +at any depth.
  • + +
  • +The price to pay for that is that you must use an instermediate class to +access the individuals, the eoPopulator class.
  • + +
  • +Thanks to that class, it also become easy to design advanced +operators, such as crossover operators where the mate is chosen according +to sexual preference rather than fitness-based +preferences.
  • +
+Implementation +

The basic idea of EO variation operators is that they operate on genotypes +only. Hence there should be generally no reference to anything related +to the fitness within a variation operator. However, whenever the genotype +of an individual has been modified, it will be necessary to recompute its +fitness before any selection process. This is why all +variation operator return a bool that indicates whether or not +the genotype argument has been modified or not. +

EO classes for variation operators: +

+ +
Simple +operators: Crossover +

The characteristic of crossover operators is that they involve two parents. +However, there are crossover operators that generate two parents, and some +that generate one parent only, and both types are available in EO. The +former type (2 --> 2) is termed quadratic crossover operator, and is implemanted +in the eoQuadOp class; the latter type +(2 --> 1) is termed binary operator and is implemanted in class eoBinOp. +Both classes are, as usual, templatized by the type of individual they +can handle (see documentation for eoBinOp +and eoQuadOp). +

Note: Whereas it is straightforward +to create a binary crossover operator from a quadratic one (by discarding +the changes on the second parent), the reverse might prove impossible (imagine +a binary crossover that simply merges the parents material: there is no +way to generate two new parents from that!). +

Interfaces: +
The general approach in EO about simple variation operators is to perform +in-place +modifications, i.e. modifying the arguments rather than generating +new (modified) individuals. This results in the following interfaces for +the functor objects eoBinOp and eoQuadOp: +

bool operator()(EOT & , const EOT &)         +for eoBinOp (note the const) +
bool operator()(EOT & , EOT & +)                       +for eoQuadOp +

which you could have guessed from the inheritance diagrams up to the +eoBF abstract class. You can also guess that only the first argument will +be modified by an oeBin object, while both arguments will be modified by +an eoQuad object. +

Using crossover operators: +
Directly applying crossover operators is straightforward from the interface +above: +
eoBinOpDerivedClass<Indi> myBinOp(parameters); +//  +use constructor to pass +
eoQuadOpDerivedClass<Indi> myQuadOp(parameters); +//  +any useful argument +
Indi eo1= ..., eo2= ...;   // +the candidates to crossover +
if (myBinOp(eo1, eo2)) +
   { ...               +// eo1 has been modified, not eo2 +
   } +
else ...               +// none has been modified +
if (myQuadOp(eo1, eo2)) +
   { ...               +// both eo1 and eo2 have been modified +
   } +
else ...               +// none has been modified +

However, you will hardly have to actually apply operators to individuals, +as operators are used within other classes, and are applied systematically +to whole sets of individuals (e.g. that have already been selected, in +standard generation-based evolutionary algorithms). +
Hence the way to use such operators will more likely ressemble this +if you are using for instance an SGA. See also the different ways that +are described below, encapsulating the operators into combined operators +objects. +

Writing a crossover +operator: +
There are three things to modify in the template class definitions +provided in the Templates directory for both binary +crossover and quadratic crossovers +(apart from the name of the class you are creating!) +

    +
  • +The constructor, where you pass to the object +any useful parameter (see the private data at end of class definition).
  • + +
  • +The operator() method, which performs the +actual crossover.
  • + +
  • +The return value, that should be true +as soon as at least one genotype has actually been modified. Otherwise, +the lazy fitness evaluation procedure in +EO might not know it should compute the fitness again and will keep the +old value.
  • +
+ +
Simple +operators: Mutation +
Mutation operators modify one single individual. The corresponding +EO class is called eoMonOp. and it +si as usual templatized by the type of individual it can handle (see documentation +for eoMonOp). +

Interfaces: +
The general approach in EO about simple variation operators is to perform +in-place +modifications, i.e. modifying the arguments rather than generating +new (modified) individuals. This results in the following interface for +the functor objects eoMonOp: +

bool operator()(EOT & ) +

which you could have guessed from the inheritance diagrams up to the +eoUF abstract class. +

Using mutation operators: +
Directly applying mutation operators is straightforward from the interface +above: +
eoMonOpDerivedClass<Indi> myMutation(parameters); +//pass parameters in constructor +
Indi eo = ...;           +// eo is candidate to mutation +
if (myMutation(eo)) +
   { ...    // +eo has been modified +
   } +
else      // +eo has not been modified +

However, you will hardly have to actually apply operators to individuals, +as operators are used within other classes, and are applied systematically +to whole sets of individuals (e.g. that have already been selected, in +standard generational evolutionary algorithms). +
Hence the way to use such operators will more likely ressemble this +if you are using for instance an SGA. See also the different ways that +are described below, encapsulating the operators into combined operators +objects. +

Writing a mutation +operator: +
There are only two things to modify in the template +class definitions provided in the Templates directory (apart from the +name of the class you are creating!) +

    +
  • +The constructor, where you pass to the object +any useful parameter (see the private data at end of class definition).
  • + +
  • +The operator() method, which performs the +actual crossover.
  • + +
  • +The return value, that should be true +as soon as the genotype has actually been modified.  Otherwise, the +lazy +fitness evaluation procedure in EO might not know it should compute +the fitness again and will keep the old value.
  • +
+ +
Combining +simple operators: proportional combinations +

The best thing to do is to go to the Lesson2 +of the tutorial, where everything is explained. You will find out how you +can use +
several mutations (respectiveley quadratic crossovers) as a single +operator: every time the operator is called, one of the available operators +is chosen by some roulette wheel selection using realtive weights. +

+


General +Operators +

General operators in EO are variation operators that are neither simple +mutations nor simple crossovers. They can involve any number of parents, +and create any number of offspring. Moreover, they can make use of different +ways to get the parents they will involve, e.g. they can use a different +selector for each of the parents they need to select. +

The corresponding EO class is called eoGenOp. +and it is as usual templatized by the type of individual it can handle +(see documentation for eoGenOp +:-) +

Interface: +
All the work a general operator is done within the apply() +method. WHy not in the usual operator() method? Because some memory management +are needed, that are performed in the base class itself - which then calls +the virtual apply() method. +The interface for a eoGenOp thus is +not deducible from its inheritance diagram, and actually is +

    void apply(eoPopulator<EOT>& +_plop) +

As you can see,the interface for eoGenOp +is based on that of another class, called eoPopulator. +An +eoPopulator +is a population, but also behaves like +an iterator over a population (hence +the name, Population-Iterator).  +However, please note that you should probably never use an eoGenOp alone, +but rather through objects of type eoOpContainer. +

This results in the following general interface for an eoGenOp: +It receives as argument an eoPopulator, +gets the individuals it needs using the operator*, +and must handle the positinning of the  using the ++operator +method (Warning: the operator++ +method is not defined, as recommended by many good-programming-style books). +

bool apply()(eoPopulator& +_pop) +
{ +
   EOT& parent1 = *_pop; +// +select the first parent +
   ++_plop;   // +advance once for each selected parents +
   ... +
   EOT& parentN = *_pop; +// +select the last parent +
       // +don't advance after the last one: _plop always +
            +// points to the last that has already been treated +

// do whatever the operator is supposed to +do +
} +

Warning: as said above, an eoPopulator +should always point to the last individual that has already been treated. +This is because it is intended to be used within a loop that looks like +(see e.g. eoBreeder +class): +

      eoSelectivePopulator<EOT> +popit(_parents, _offspring, select);    // eoSelect +is an eoSelectOne +
      while (_offspring.size() +< target) +
          +{ +
               +op(popit); +
              +++it; +
          +} +

What happens next? Well, it all +depends on how many parents and how many offspring your general op needs: +

    +
  • +If the number of generated offspring is equal +to the number of parents, the operator simply needs to modify them (they +are passed by reference, no useless copy takes place).
  • + +
  • +If the operator produces more offspring than there +were parents, it needs to insert them into the list using the insert +method of the class eoPopulator as +in the following:
  • + +
      +

      +

    void apply()(eoPopulator& +_pop) +
    { +
      // get the necessary number +of parents (see above) +
      ... +
      // Now create any supplementary offspring +
      EOT ofs1 = create_individual(...); +
      ... +
      EOT ofsK = create_individual(...); +
      // advance and inserts offspring in +_pop after parentN +
      ++_pop; +
      _pop.insert(ofs1); +
      ... +

      // invalidate the parents that +have been modified +
      parent1.invalidate(); +
      ... +
      parentN.invalidate(); +
    }   // over +

    Of course the size of the resulting population will grow - and you should +have a replacement procedure that takes care of that. +
      +

  • +The case where more parents are needed than offspring +will be created is a little more delicate: think about eoBinOp, +and try to imagine the reasons why no crossover of that class are used +in the first lessons of the tutorial, within the SGA framework.
  • + +
    There are two possibilities: +
      +
    • +If you think "generational", the first idea is to get the parents from +outside the curent list, so the total number of (intermediate) offspring +is always equal to the initial population size. By chance, the eoPopulatorhas +a handle on the initial population that was used to start the process, +and you can access it from inside the GenOp method. For instance
    • + +
        +

        +

      void apply()(eoPopulator& +_pop) +
      { +
        // get as many parents as you +will have offspring (see above) +
        ... +
        // get extra parents - use +private selector +
        const EOT& parentN+1 = select(_pop.source()); +
        ... +
        const EOT& parentM = select(_pop.source()); +
        // do whatever needs to be done +
        ... +
        // and of course invalidate fitnesses +of remaining modified parents +
        parent1.invalidate(); +
        ... +
        parentN.invalidate(); +
      } +
      where select is any selector you like. Note the +const: you are not allowed to modify an element of the original +population (but you could of course have copied it!). As usual, the select +selector was passed to the operator at construct time. This typically allows +one to use a different selector for one parent and the others, as demonstrated +here. +
        +

    • +If you don't care about the size of the offspring population (that is, +if that size os controlled elsewhere, e.g. in some external loop), you +can use the inbedded select method of the class eoPopulator. +For instance
    • + +
        +

        +

      void apply()(eoPopulator& +_pop) +
      { +
        // get as many parents as you +will have offspring (see above) +
        ... +
        // get extra parents - use +populator selector +
        const EOT& parentN+1 = _pop.select(); +
        ... +
        const EOT& parentM = _pop.select(); +
        // do whatever needs to be done +
        ... +
        // and of course invalidate fitnesses +of remaining modified parents +
        parent1.invalidate(); +
        ... +
        parentN.invalidate(); +
      }

    +
+Warning: if you use operators that +have different number of parents than offspring, you are deviating from +the simple generational approach. Be careful to have the proper replacement +procedure to take care of the population size: in most instances of algorithms +that come within EO, this is enforced (an exception is thrown if population +size varies from one genertaion to the other) but this might not be true +for all forthcoming EO algorithms. +

Using general operators: +
Directly applying general operators to given individuals is impossible +in EO, due to its interface. You need the help +of an individual dispenser of class eoPopulator. +But anyway general operators were thought to be used putely in eoOpContainer, +as described below. +

Writing a general +operator: +
There are many things to do to write a general operator - but the Templates +directory contains some sample tempaltes files to help you. It all depends +on whether you want more or less offspring than parents, and whetehr you +want the same selector for every parent or more specialized selectors. +

    +
  • +It you want more (or as many) offspring than +parents, you should use the moreOffspringGenOp.tmpl +template - if you want to use the same selector for all parents, the one +embedded in the argument eoPopulator. +Otherwise, you'll have to write your own operator based on an external +selector, as described in lessOffspringExternalSelectorGenOp.tmpl.
  • + +
  • +If you decide to have more parents than offspring, you can decide either +to get the extra parents using the eoPopulator  +own selector (see lessOffspringSameSelectorGenOp.tmpl, +or to use an external selector (passed at construct-time) as described +in lessOffspringExternalSelectorGenOp.tmpl.
  • + +
  • +Now you can modify the constructor, where +you pass to the object any useful parameter (see private data at end of +class definition). In case you need an external selector, you have to choose +it (or write it!) - it should be an eoSelectOne +object.
  • + +
  • +Finally, write the core of the operator in method apply(). +Remember you must use the argument eoPopulator +to +access the members of the population in turn (method +operator*), +you may use the initial population (method source()), +as well as the insert methods.
  • +
+ +
    Warning: in general operators, +you must not forget to invalidate the +fitness of any individual that has actually been modified. this implicitely +implies that general operators can only be applied to EO object (i.e. objects +with a fitness), and not to any type of structure. +
    It you don't invalidate the individual, the lazy +fitness evaluation procedure in EO will not know it should compute +the fitness again and will keep the old obsolete value.
+ +
The +populators: +
As has been said above, an +eoPopulator +mainly behaves like an iterator over +a population (hence the name, Population-Iterator). +

The basic +interface of an eoPopulator +(see also the documentation, +of course) is the following: +

    +
  • +Individuals are accessed through the operator*;
  • + +
  • +Basic iterator operations are available, like (pre)incrementation through +operator++, +position management through seekp +(returns the current position) and tellp +(go to a given position);
  • + +
  • +Individuals can also be inserted at +current position using the corresponding methods;
  • + +
  • +last but not least, as the individuals are returned by reference, it is +mandatory to ensure that they will not be moved around later: the memory +management  routine reserve +is called whenever there is a chance to add some individuals in the population +- i.e. in the eoGenOp base class operator() method.
  • +
+Moreover, a public method termed select,  +is used inside the object to get new parents for the following operator*, +and its implementation distinguishes two types of eoPopulator: +
    +
  • +The eoSeqPopulator gets new parents +from its source (the initial population). When the source is exhausted, +an exception if thrown. The idea of such pooulator is to start from a population +of already selected individuals.
  • + +
    The programmer should hence be very careful that the number of available +parents matches the requirements of the operators when using an eoSeqPopulator +object. +
  • +The eoSelectivePopulator , on the opposite, +always gets new parents using its private eoSelectOne +object (passed at construct time). Hence it can handle any number of parents +at will. The idea of such populator is to handle the whole breeding +process, i.e. selection and variation operators.
  • +
+An immediate consequence is that if you are not sure of the number of  +parents you will need in some operators (e.g. because of some stochastic +proportional selection ebtween operators that don't need the same number +of parents, then you must use an eoSelectivePopulator +to apply the variation operators to the population, and thus get exactly +the number of offspring you want. +

Example: An eoSelectivePopulator +is the main ingredient of the eoGeneralBreeder +operator() +method - a class that creates a population of offspring from the parents +applying an eoGenOp (usually an eoOpContainer) to all selected parents +in turn. +
+


General +Operator Containers: +
General operators in EO are meant to be used withing eoOpContainer +objects, that allow to combine them in a hierarchical and flexible way. +There are two ways to do that: the proportional +combination, similar to what has been described for simple operators +above, +and the sequential combination, which +amounts to apply all operators in turn to a bunch of individuals, each +operator being applied with a specific probability. +

Proportional combinations +
When called upon a population (through an eoPopulator +object), an eoProportionalOpContainer +enters the following loop: +

while there are individuals left in the list +

    +
  • +choose one of the included operators according to their relative rates +(by some roulette wheel random choice)
  • + +
  • +applies the chosen operator. The parents are dispensed to the operator +from the list on demand.
  • + +
  • +What happens next exactly depends on the type of operator, but basically, +some of the parents get modified, some might get removed from the list +and some new individual might get inserted on the list.
  • + +
  • +updates the list pointer (if needed) to the individual following the ones +that just have been modified/inserted/deleted.
  • +
+Sequential combinations +
When it is called upon a list of pending candidates, an +eoSequentialOpContainer +enters the following loop: +

mark the current position +
for all operators it contains, +

    +
  • +go to marked position
  • + +
  • +until current end of population +is reached do
  • + +
      +
    • +flip a coin according to the operator rate.
    • + +
        +
      • +If true, apply the operator to the parents. The current parents can be +modified, or some can be deleted from the list, or some offspring can be +inserted in the list.
      • + +
      • +If false, move the pointer over the required number of parents (i.e. don't +modify thoses parents)
      • +
      + +
    • +Next pending parent
    • +
    + +
  • +Next operator
  • +
+Warning: the way rate +will be used is highly dependent on the type of eoOpContainer +your are creating there: +
    +
  • +The rates for eoProportionalOpContainer +will be used in a roulette wheel choice among all operators. They can take +any value, the only important thing is their relative +values.
  • + +
  • +The "rates" for eoSequentialOpContainer actually +are probabilities, i.e. they will be +used in a coin-flipping to determine whether that particuler operator will +be applied to the next candidates at hand. They should be in +[0,1] (no error will happen if they are not, but the operator +will be applied systematically - this is equivalent of a rate equal to +1).
  • +
+Remark:The eoSGATransform presented in Lesson2 +can be viewed as a particular type of eoSequentialOpContainer. +It was not coded that way in order to provide a gradual introduction to +all concepts. +
Exercise: write the code to perform an +eoSGA using the eoOpContainer constructs. +

Adding operators to a container: +
The way to add an operator to an eoOpContainer +is the method +add. It is similar +to all other add methods in +other Combined things in eo (as the simple eoProportionalCombinedXXXop +described above, but also the eoCombinedContinue class or the eoCheckPoint +class). +
The syntax is straightforward, and it works with any of the operator +classes eoXXXOp, where XXX stands for +Mon, +Bin, Quad or +Gen: +

someOperatorType<Indi> myOperator; +
eoYYYOpContainer<Indi> myOpContainer; +
myOpContainer.add(myOperator, rate); // +rate: double whose meaning depends on YYY +

where YYY can be one of Proportional and Sequential. Note that before +being added to the container, all simple operators are wrapped into the +corresponding eoGenOp (see e.g. how an eoMonOpis +wrapped into an eoMonGenOp- or +how any operator +is handled by calling the appropriate wrapper). In particular, the +wrapper ensures that individuals who have been +modified are invalidated. +

Containers, +Selectors and Populators +
The way the eoOpContainer are applied +on a population using an eoPopulator +object. But, whereas the behavior of eoProportionalOpContainer +does not depend on the type of eoPopulator,(one +operator is chosen by roulette_wheel, and applied once before control is +given back to the caller), the main loop in method operator() +of +class eoSequentialOpContainer +iterates while (!_pop.exhausted()) +which is interpreted differently depending on the type +of eoPopulator: +

    +
  • +if the argument is an eoSelectivePopulator, +the default position of the eoPopulator, considered as a population iterator, +is at end of population. Individuals are added upon demand of an operator, +and in most cases all operators are applied once. This also depends, however, +on the arities of all operators:
  • + +
      +
    • +Consider an eoSequentialOpContainer +containing an eoQuadOp and an eoMonOp. The eoQuadOp first asks for two +parents and modifies them. The eoMonOp is then called starting from the +forst of thoses two modified individuals, and is hence applied twice, once +on each parent.
    • + +
    • +But consider now an eoSequentialOpContainer +containing an eoGenOp that takes one +parent and generates three offspring, followed by an eoQuadOp. +The eoGenOp will call the selector +to get the parent its need and will modify it and put 2 additional offspring +at end of the population. The eoQuadOp +will then be called on the first of the three outputs of the eoGenOp, +and hence will act upon the frist two of them. But at that point, the populator +iterator will point to the third of the individuals resulting from the +eoGenOp, +and the test _pop.exhausted() +will return false, so the eoQuadOp +will again be called. The second parent it needs will be given by a new +call to the embedded eoSelectOne of +the  and everything will go on smoothly, except that a total of 4 +offspring will have been generated by application of this particular eoSequentialOpContainer.
    • +
    + +
  • +if the argument is an eoSeqPopulator, +the position of the iterator starts from the beginning of an existing population +(the source populations), and hence when an  an eoSequentialOpContainer +is called, it goes through the whole remaining of the population (the test +_pop.exhausted() +only returns true at end of the source population).
  • + +
  • +From the above it is easy to see that passing an eoSeqPopulator +to an eoProportionalOpContainer that +contains an eoSequentialOpContainer, +though not technically forbiddden, will most produce something  totally +unpredictable, and hence should probably not be used without great care.
  • +
+ +
Advanced +general operators: +

It is sometimes useful to be able to use a selector from inside an operator +(a typical example is when you want to implement sexual +preferences, i.e. choose a mate for a first parent according +to some characteritics of that first parent). +
This is made possible in EO because the general operators have a handle +on the initial population through the method source() +of the argument eoPopulator they work on. Their apply() +method shoudl look like +

void apply()(eoPopulator& +_pop) +
{ +
  EOT & eo1 = *_pop; // get +(select if necessary) the first guy +
  EOT maBlonde = findBlonde(_pop.source()); +// +select mate +
  // do whatever the operator is supposed +to do, e.g +
  cross(eo1, maBonde);       +// cross is some embedded crossover +
  ... +
  // if you don't want to put maBlonde +into the offspring, +
  // stop here (and use a reference +to maBlonde above). Otherwise +
  maBonde.invalidate(); +
 ++_pop;    // +advance +
  _pop.insert(maBlonde);    +// and insert it +
} +

Where does that findBlonde +selector comes from? As usual, you have to attach it to the operator,  +in its constructor for instance, which should give something like: +

sexualSelectorType<Indi>  findBlonde; +
sexualOperatorType<Indi> yourBrainAndMyBeauty(cross, +findBlonde); +

+


Local: Introduction +- Crossover - Mutation +- Combinations - General +Operators - Populators - General +combinations- Advanced operators +
General: Algorithm-Based +- Component-Based - Programming +hints -EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Sat. Feb. 17 2002  +
  + + diff --git a/deprecated/eo/tutorial/html/eoOutput.html b/deprecated/eo/tutorial/html/eoOutput.html new file mode 100644 index 000000000..4e77cd2ea --- /dev/null +++ b/deprecated/eo/tutorial/html/eoOutput.html @@ -0,0 +1,19 @@ + + + + Output + + + +

Output

+ + + +
+
Marc Schoenauer
+ + +Last modified: Mon Oct 30 19:29:19 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoProgramming.html b/deprecated/eo/tutorial/html/eoProgramming.html new file mode 100644 index 000000000..64fca549f --- /dev/null +++ b/deprecated/eo/tutorial/html/eoProgramming.html @@ -0,0 +1,502 @@ + + + + + + EO Programming guide + + +General: Tutorial +main page - +Algorithm-Based - Component-Based +- Programming hints - EO +documentation +
+
Local: Templates +- +Functors - +STL Library - Random +numbers - EO programming style  - Memory +management +
+
+
+

+EO Programming guide

+ +
+
Templates +

Most EO code is written using templates. This allows to write generic +code, i.e. involving a class which doesn't have to be known when writing +the code -- but only when compiling it. In some sense this is similar to +naming variables in algebra: you can write a lot of equations involving +some variable $x$ without knowing even it if will be an integer or a float +(or a matrix or ...). The main basic type that is templatized in EO is +the fitness: an EO object is some object which has a fitness of some type +F that can be anything. The definition for that is (see EO.h) +

template<class F> class EO +

The idea is that, later in your code, you can define a class as follows +(see for instance  eoOneMax.h - or check Lesson 5 for more details). +

template<class F> class eoOneMax : public +EO<F> +
{ ... code for eoOneMax  }; +

and then use it in your application as +

eoOneMax<double> myeoBit; +

declares an object of type eoOneMax which has as fitness a double. +

Whereas the advantages +are obvious (writing generic reusable code instead +of having to rewrite the same pieces of code for different types), there +are some drawbacks: +namely, it makes some of the compiler error messages +hard to understand; and it forbids the compilation of most parts of EO +into an object library file, as the actual types are not known in advance. +

+


+
Functors +

Though EO is a library, it contains almost no functions per se! +
EO mainly contains functors, that are objects which have a method called +operator(). +Such objects are used  as if they were functions, but the big differences +are that +

    +
  • +functors are functions with private data
  • + +
  • +you can have different functors objects of the same class, i.e. you can +use at the same time the same functionality with different parameters
  • + +
  • +you can have a hierarchy of functors objects, which means that you have +a hierarchy of functions with defaults behaviors and specialized sub-functions
  • + +
  • +...
  • +
+Functors are so intimately linked to EO that a base class (eoFunctorBase) +has been designed to hold all functors. This base class is itself divided +into three derived class. These classes tell you immediately what kind +of arguments the operator() +method requires and what kind of result it produces. See EO +conventions, and the inheritance +diagram of class eoFunctorBase Also note that +if you create new functors, you should also derive from one of these classes, +as it is mandatory if you later use the EO memory management +mechanism. +
For a more complete introduction to functors, with detailed discussion, +go to the STL documentation +- as STL also heavily relies on functors, and the eoFunctorBase paradigm +is borrowed from there. +

Functors: Example: +

The following is a basic example of how to program and use a functor +object: First code the class: +

class MyFunctor +
{ ... +
    void operator()(ArgType +arg) +
       { +
            +// do what you have to do +
       } +
}; // end of class declaration +

Then use it  later in the code : +

ArgType myArgument; +
MyFunctor myFunctorInstance;    +// myFunctorInstance is an object of class MyFUnctor ... +
myFunctorInstance(myArgument);  +// calls operator() of myFunctorInstance acting on myArgument ... +
  +

Functors: The +three basic classes: +

Direct sub-classes of the root class , three classes +are defined to differentiate functors by the number of argument required +by their operator(). +These classes are templatized by the types of its arguments, and by its +return type. Hence, +
from the inheritance diagram of any functor class +in EO, you can immediately deduce the interface of their operator() +method. +
  +

    +
  • +eoF +is for arity-zero functors, i.e.  their operator() +method does not require any argument. It has a single template parameter, +the return type of the operator() +method. For instance,  eoMonitor  +are eoF's +that return an eoMonitor &.
  • + +
  • +eoUF +is for unary functors, i.e.  their operator() +method requires one argument. It has two template parameters, the type +of the argument and the return type of the operator() +method. For instance,  eoMonOp's +are eoUF's +that take as argument an EOT & +and return void +.
  • + +
  • +eoBF +is for binary functors, i.e.  their operator() +method requires two arguments. It has three template parameters, the types +of the arguments and the return type of the operator() +method. For instance,  eoBinOp's +are eoBF's +that take as arguments a const EOT +& and an EOT +&, and return void +.
  • +
+Now go back to the inheritance +diagram of class eoFunctorBase, +and guess the interface for all functors! +

Note: for +obvious simplicity reasons, we very often omit the reference to the operator(), +e.g. when we say above: +

    +
  • +eoMonOp's +are eoUF's +that take as argument an EOT & +and return void
  • +
+it actually means +
    +
  • +eoMonOp's +are eoUF's, +their operator() +method takes as argument an EOT & +and returns void.
  • +
+ +


+


+
A very brief +introduction to STL +

All EO heavily relies on STL, the Standard +Template Library. +
But you don't have to know more than a few words +of STL to use EO (like with "hello", "please" and "goodbye" you +can survive in a foreign country :-) and even to contribute to new EO features. +Moreover, while browsing through EO code, you will gradually learn how +to use STL, especially if you check at the SGI +STL Web site from time to time, where you can not only download STL, +but also browse in the Programmer's guide  for isntance from the Table +of Content. +

Anyway, you will only find here, in EO tutorial, the basics of STL that +you will need to understand most of EO code - and to guess what the parts +you don't understand are actually doing. Don't worry, I +don't +understand everything :-) +

STL provides the user with containers, +iterators +and algorithms. And you can access +(almost) all containers content using (almost) all iterators, or apply +(almost) all algorithms on (almost) all containers (of course the tricky +part is to instanciate the "almost" in the previous sentence :-) +

STL: Containers +
Containers are high level data types used to hold simpler data - the +most widely used example of a container is the vector +construct. +
The use of STL containers relieve the user from memory management. +

    +
  • +vector The +most widely used container is a one-dimensional array of items.
  • + +
    Data manipulation: suppose v +is an STL vector<AtomType>. +Then +
    v[i] +is the ith element of v, as in standard C arrays +
    v.size() +is the number of elements of v +
    v.push_back(atom) +appends the atom +at end of v, +provided of course that atom +is of type AtomType, +the size is automatically increased... +
    blabla insert, erase, ... +
  • +list +STL provides different types of list. The one used in EO is the simple +linked list named ... list. +As far as the user is concerned, simple lists are very similar to vectors, +and the data manipulation listed above for vectors can be applied to list.
  • + +
  • +pair
  • + +
    This simple container allows you to hold two +data types together. It is very handy for temporary data handling. Assuming +p is a pair<AtomType1, AtomType2>, +p.first +and p.second  +refer to the encapsulated data, of respective types AtomType1 +and +AtomType2 +
  • +Blabla
  • +
+There are many other types of containers that are not used in EO and that +we will not present here. +

STL: Iterators +
Iterators are accessors to the containers contents that provide unified +access to different containers. They are very similar to pointers, i.e. +you can increment them, compare them with one another, etc +

Some very useful iterators for vectors and lists are begin() +and end(), that refer to the first +and after-last items of a container. They allow loops to sweep all items +contained in a container as follows: +
STLcontainer myContain; +
STLcontainer::iterator it; +
for (it=myContain.begin(); it!=myContain.end(); +it++) +
{ +
// do what you have to do to +(*it) +the current item in the container +
} +

STL: Algorithms +
Algorithms are functions acting on containers - the most widely used +example of a STL algorithm are the different sorting +algorithms. +

    +
  • +sort, nth_element, are sorting +algorithms used in EO
  • + +
  • +copy is used to copy a range +of data designated by iterators
  • + +
  • +apply is used to perform the +same operation to many items designated by a range of iterators
  • + +
  • +Blabla - help wanted thanks...
  • +
+STL: Advantages +
The main and huge advantage of +using STL is that it handles (almost all) memory mangement automatically. +You can use any STL container the same way you would use a scalar basic +C++ type. And it does it in a (supposededly) optimized way. Of course, +the user is also responsible for performances: for instance, the insert() +method will take more time for vectors than for linked lists, while on +the opposite, the operator[] accessor will be faster for vectors. But both +will work anyway. +

STL: Drawbacks +
The main drawback I see in using STL is that it makes it +difficult +to use a debugger normally: whereas access to data is made simple +to the programmer, data structures are actually so complex, and debuggers +so willing to display everything that you get lines of template instantiation +when asking your debugger what is inside some container!
+However, here is a trick (thanks to Arnaud Quirin!) to actually print what is inside an STL vector with gdb (but it doesn't really work with complex structures like EO genotypes :-( :
+(gdb) print (*(&v))[i]
+$1 = (const double &) @0x934cad0: 0.69543264131061733
+ +

+


+
Random +numbers +

Evolutionary Algorithms make intensive use of random numbers. Random +numbers are simulated in computers by using pseudo-random +number generators (RNGs for short), i.e. functions that return series of +numbers who look random (w.r.t. some statistical criteria). +

To make sure the random number generator is as good as possible, and +to ensure reproducibility of the results across different platforms, EO +has its own RNG, the ``Mersenne Twister'' +random number generator MT19937 (thanks to Takuji +Nishimura, see eoRNG.h +comments). +

Though you can define and use as many RNGs as you wish in EO, the library +also provides you with a global RNG termed eo::rng. +Using that single RNG in all calls to random numbers allows one to be able +to reproduce a given run: +

    +
  • +as strange as it seems for a random algorithm, it is mandatory for debugging +purposes
  • + +
  • +random numbers are computed starting from a seed - starting from the same +seed will lead to the same series of pseudo-random numbers, and hence to +the same results of the algorithms. All examples in this tutorial will +use the RNG seeding procedure, see e.g. in Lesson1.
  • + +
  • +to simulate "true" random runs, you can just seed the RNG with a machine-clock +related number, e.g. calling time(0), as done for instance in Lesson3 +(and after).
  • +
+As RNGs produce, by definition, integers that are uniformly distributed +between 0 and some maximal number, EO provides you with random numbers +following different probability distribution +(e.g. floating point following normal +distribution). See the complete +list of RNG primitives. +

EO also provides random_generators +that can be used in STL call to generate series of random numbers, as in +eoPop +initializers. +

Note: the eo:: +prefix indicates that it is in a separate C++ namespace, to avoid collision +with possible variables that would also be named rng in some other library. +As early versions of EO (<= 9.1)  did not use a separate namespace +for rng, the compiler directive using eo::rng in eoRNG.h allows you to +use the name rng without the eo:: +prefix. However, the notation eo::rng +should be preferred and might become mandatory some day. +
+


+
EO conventions +and naming style +

A few naming conventions should help you to navigate more easily through +EO: +

    +
  • +The name of local variables should start with a lower case letter. Capital +letters should be used rather than underscore to separate words in names +(e.g. popSize rather than +pop_size).
  • + +
  • +The name of the arguments to a function should start with an underscore, +e.g.
  • + +
              void +myfunction(unsigned _popSize){...} +
  • +The initialization parameters of constructors should be named from the +names of the variables they are used to initialize, e.g.
  • + +
      +

      +
      +
      +

    class eoMyClass +
    { +
    public: +
      eoMyClass(unsigned _popSize):popSize(_popSize){...} +
       ... +
    private: +
       unsigned popSize; +
    }; +

  • +The names of classes should start with eo + an Uppercase letter (as eoMyClass +above).
  • + +
  • +The name of the EO template should be EOT. This allows quick understanding +of the inheritance diagrams for functors. and immediate +perception of the arguments and return types of the functors oeprator() +method (as in eoMonOp +or  eoBinOp).
  • + +
      +
  • +Blabla
  • +
+ +
+
EO memory +management +

Most of EO constructs are based on the encapsulation +of objects into other objects, and the embedded objects are passed through +the constructor of the embedding object. +
For instance, the construction of an algorithm requires a breeder (plus +many other things of course), the construction of a breeder usually requires +a selector, and in turn the construction of a selector requires some parameters. +This gives something resembling the following +

eoTournamentSelection<EOT>  select(tSize); +
eoBreeder<EOT> breed(select); +
eoEasyAlgo<EOT> algo( ..., breed, ...); +

Such a practice is no problem when doing everything +in a (large!) main function: all objects are local to that function, +but when the end of the function is also the end of the program. For instance, +all programs in Lesson1, Lesson2 +and Lesson3 of this tutorial are built that +way. +

It is however a big problem when you want to outsource some code in +other functions: indeed, the above sequence create objects that dissapear +when exiting the function, and thus cannot be used outside their defining +function. +

The solution is of course to use pointers, +which gives something like +

eoTournamentSelection<EOT>  *ptSelect += new eoTournamentSelection<EOT>(tSize); +
eoBreeder<EOT> *ptBreed = new eoBreeder<EOT>(*ptSselect); +
eoEasyAlgo<EOT> *ptAlgo = new eoEasyAlgo<EOT>( +..., *ptBreed, ...); +

and you can then use the dynamically allocated objects anywhere. But +the trouble with such a construct is that after exiting the function where +such objects are defined, you will never be able +to free this allocated memory, should you not need the objects +any nore. Whereas this is not in general a big problem (except of being +a very bad practice that will make you a very naughty programmer :-), it +will prevent any re-entrance of the resulting code, and for instance you +will not be able to use an evolutionary algorithm within another loop of +some outside code. +

The solution in EO us to use an eoFunctorStore +object to store such nowhere-belonging pointers: whenever you allocate +such a thing, store it into an eoState : deleting that state will delete +all the stored pointers - one eoState is thus the only object you have +to care of. +

The above pointer allocation sequence thus become +

eoTournamentSelection<EOT>  *ptSelect += new eoTournamentSelection<EOT>(tSize); +
state.storeFunctor(ptSelect); +
eoBreeder<EOT> *ptBreed = new eoBreeder<EOT>(*ptSelect); +
state.storeFunctor(ptBreed); +
eoEasyAlgo<EOT> *ptAlgo = new eoEasyAlgo<EOT>( +..., *ptBreed, ...); +
state.storeFunctor(ptAlgo); +

or, even more quickly (though less readably) +

eoTournamentSelection<EOT>  *ptSelect += +
               +state.storeFunctor(new eoTournamentSelection<EOT>(tSize)); +
eoBreeder<EOT> *ptBreed = +
               +state.storeFunctor(new eoBreeder<EOT>(*ptSelect)); +
eoEasyAlgo<EOT> *ptAlgo = +
               +state.storeFunctor(new eoEasyAlgo<EOT>( ..., *ptBreed, ...)); +

In both the above code, state is an eoFunctorStore +that is of course passed from outside the function +- and it's called state because in most cases it will actually be an eoState. +As its name says, an eoFunctorStore +can store any object that is an (derives from) eoFunctorBase +- hence all objects in EO that are used as functors should derive from +either eoF, eoUF or eBF. +

Examples of such constructs are shown in the make_xxx files described +in Lesson4. +
+


Local: Templates +- +Functors - +STL Library - Random +numbers - EO programming style  - Memory +management +
+
+
General: Tutorial +main page - Algorithm-Based - Component-Based +- Programming hints - EO +documentation +
+
+
Marc Schoenauer + + diff --git a/deprecated/eo/tutorial/html/eoRepresentation.html b/deprecated/eo/tutorial/html/eoRepresentation.html new file mode 100644 index 000000000..41a63f6df --- /dev/null +++ b/deprecated/eo/tutorial/html/eoRepresentation.html @@ -0,0 +1,19 @@ + + + + Representation + + + +

Representation

+ + + +
+
Marc Schoenauer
+ + +Last modified: Mon Oct 30 19:28:01 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoSGA.html b/deprecated/eo/tutorial/html/eoSGA.html new file mode 100644 index 000000000..2e2428701 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoSGA.html @@ -0,0 +1,157 @@ + + + + + + eoSGA.h + + +Back to Lesson 1 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+
+

+eoSGA.h

+ + + + + +
//----------------------------------------------------------------------------- +
// eoSGA.h +
//----------------------------------------------------------------------------- +
#ifndef _eoSGA_h +
#define _eoSGA_h +
#include <eoOp.h> +
#include <eoContinue.h> +
#include <eoPop.h> +
#include <eoSelectOne.h> +
#include <eoSelectPerc.h> +
#include <eoEvalFunc.h> +
#include <eoAlgo.h> +
#include <apply.h> +
/** The Simple Genetic Algorithm, following +Holland and Goldberg  +
*  Needs a selector (class eoSelectOne) +a crossover (eoQuadratic,  +
*      i.e. a 2->2 +operator) and a mutation with their respective rates,  +
*      of course +an evaluation function (eoEvalFunc) and a continuator  +
*      (eoContinue) +which gives the stopping criterion. Performs full +
*      generational +replacement. +
*/  +
template <class EOT> +
class eoSGA : public eoAlgo<EOT> +
{ +
public : +
 // added this second ctor as +I didn't like the ordering of the parameters +
 // in the one above. Any objection +:-) MS +
eoSGA( +
       eoSelectOne<EOT>& +_select, +
       eoQuadraticOp<EOT>& +_cross, float _crate, +
       eoMonOp<EOT>& +_mutate, float _mrate, +
       eoEvalFunc<EOT>& +_eval, +
       eoContinue<EOT>& +_cont) +
     : cont(_cont),  +
       mutate(_mutate),  +
       mutationRate(_mrate), +
       cross(_cross), +
       crossoverRate(_crate), +
       select(_select), +
       eval(_eval) +{}
+ + + + + +
 void operator()(eoPop<EOT>& +_pop) +
 { +
    eoPop<EOT> offspring; +
    do { +
         +select(_pop, offspring); +
         +unsigned i; +
         +for (i=0; i<_pop.size()/2; i++)  +
             +{   // generates 2 offspring from two parents +
                 +if ( rng.flip(crossoverRate) )  +
                   +{  +
                       +cross(offspring[2*i], offspring[2*i+1]); +
                   +} +
             +} +
         +for (i=0; i < _pop.size(); i++)  +
             +{ +
                 +if (rng.flip(mutationRate) )  +
                     +{ +
                         +mutate(offspring[i]); +
                     +} +
             +} +
         +_pop.swap(offspring); +
         +apply<EOT>(eval, _pop); +
     } while (cont(_pop)); +
 } +
 
+ + + + + +
private : +
 eoContinue<EOT>& cont; +
 eoMonOp<EOT>& mutate; +
 float mutationRate; +
 eoQuadraticOp<EOT>& cross; +
 float crossoverRate; +
 eoSelectPerc<EOT> select; +
 eoEvalFunc<EOT>& eval;
+ + + + + +
}; +
#endif
+ +
Back to Lesson 1 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
+
+Marc Schoenauer
+ +
Last modified: Sun Nov +19 19:36:21 2000 + + diff --git a/deprecated/eo/tutorial/html/eoSelect.html b/deprecated/eo/tutorial/html/eoSelect.html new file mode 100644 index 000000000..9de6bb612 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoSelect.html @@ -0,0 +1,19 @@ + + + + Selection + + + +

Selection

+ + + +
+
Marc Schoenauer
+ + +Last modified: Mon Oct 30 17:51:55 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoStop.html b/deprecated/eo/tutorial/html/eoStop.html new file mode 100644 index 000000000..14e0d37c1 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoStop.html @@ -0,0 +1,25 @@ + + + + Input / Output + + + +

Input / Output

+ +

+ +

Stopping criteria

+ +

+ +

Displaying statistics

+ +
+
Marc Schoenauer
+ + +Last modified: Tue Oct 31 18:32:22 CET 2000 + + + diff --git a/deprecated/eo/tutorial/html/eoTopDown.html b/deprecated/eo/tutorial/html/eoTopDown.html new file mode 100644 index 000000000..f589f0aa0 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoTopDown.html @@ -0,0 +1,111 @@ + + + + + + EO - The Algorithm-Based approach + + +Tutorial main +page +- +Algorithm-Based - Component-Based +- Programming hints - EO +documentation +
+
+
+

+EO - The Algorithm-Based approach

+ +


Congratulations - You have chosen the algorithm-based approach!  +This means that you want to start from something that already works, and +gradually learn about the more complex constructs. We have prepared a series +of "lessons" for you. +

    +
  • +Lesson 1 - a gentle introduction to the EO +way: your first steps into EO representations +using a simple generational GA. Please, spend +the necessary time on that one, since all basic constructs presented +there are used throughout EO.
  • + +
  • +Lesson 2 - encapsulate, +encapsulate, and try more sophisticated selection/replacement +mechanisms, as well as multiple  operators
  • + +
  • +Lesson 3 - The same algorithms, but with improved +input/outputs: user-friendly input (i.e. without +the need to recompile!) of algorithm parameters, +and checkpointing (display +of on-line statistics, save +and +restore +populations, +restart stopped runs, +...).
  • + +
  • +Lesson 4 - The same algorithms - again! - +but now fully operational: every component +of the algorithm can be defined on the command-line, +except the type of genotype; moreover, you now have a full library, i.e. +everything except your fitness function is already +compiled.
  • + +
  • +Lesson 5 (new) +- Use your own representation. Thanks +to template files and a little script in Unix, +or the Application template in MSVC++, you +can easily define a new genotype and run an Evolutionary Algorithm that +will intantly benefit from the power of all EO +Evolution Engines (including easy user-parameter +input presented in Lesson 4). You simply need to gradually fill +in the shell-files that the script will generate for you.
  • + + +


    Current version (May. 5, 2002) stops here, but ... +

    From there on, you don't need to follow the lesson order any more: you +can go directly to any lesson and experiment. Of course, you will need +to bring together the different pieces to write exactly what you want - +but only because we had no idea of what you exactly want :-) +

      +
    • +Lesson 6 (forthcoming) - More about checkpointing: +write your first adaptive mechanism, +and find out how easy it is to update +and monitor dynamic +parameters
    • + +
    • +Lesson 7 - More general operators: +e.g. binary, n-ary, or even specific mate selection (your brain and my +beauty)! Add your own to the basic algorithm using the template files.
    • + +
    • +Lesson 8 - Use predefined generic representations. +The eoFixedLength and eoVariableLength +super classes allow quick definition of new genotypes that handle identical +Atoms, together with generic variation operators.
    • +
    +Of course, in each lesson, you have links to the corresponding Component-Based +page. ( ... Well, to tell you the truth, as of today, this is not exactly +true :-) +
    +
    +
    Tutorial main page - Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
    +
    +
    +Marc Schoenauer
    + +
    Last modified: Tue Dec 19 +2000  + + diff --git a/deprecated/eo/tutorial/html/eoTutorial.html b/deprecated/eo/tutorial/html/eoTutorial.html new file mode 100644 index 000000000..1dbef8bd2 --- /dev/null +++ b/deprecated/eo/tutorial/html/eoTutorial.html @@ -0,0 +1,286 @@ + + + + + + Tutorial EO + + +Algorithm-Based - Component-Based +- Programming hints - EO +documentation +
    +
    Welcome to EO, the Evolving Objects library, +and to
    + +
    +

    +EO Tutorial

    + +
    Important notice - December 2006 +

    +The code that is proposed in this tutorial should not +be used +as a basis for any comparison with any original method on any benchmark problem. +It is an illustration of what you can achieve with EO, but reaching state-of-the-art results +requires more work. In particular, if you want to compare your evolutionary +algorithm with a good performing algorithm in parameteric optimisation, +do not +use ESEA in Lesson4, +but go to the test directory, type +make t-eoCMAES and use the resulting t-eoCMAES. But as of today, +the latest algorithms (and comparative results) +are better found on Nikolaus Hansen Web page +and on his "Comparison of Evolutionary Algorithms on a Benchmark Function Set" page).
    +
    +
    + +
    Version 0.98a - December 2004 +
    + +
      +
    • New - +Well, in fact, nothing really new, +but some people advised us to announce from the very beginning that +if you are looking for a ready-to-use +(except for the fitness) fully tunable Evolutionary +Algorithm evolving real values or bitstring, you can +go directly to +Lesson 4 after just reading +this page, and maybe the Programming +hints (link on top of each page too).
      + +In fact, there is something new: EO's automatic configuration and +build process has been cleaned up and upgraded. For consistency, the +same automatically-built Makefiles have been created in the +tutorial directories. The good-old manually-created files are +still there, now named +Makefile.simple. +Moreover, when you compile the whole library (typing make in the main EO dir), all lessons of the tutorial gets compiled, too. +
    • +
      + +
      Version 0.98 - May 2004
      + +
    • Lesson 5 + has been improved: some of +the empty template files in dir +.../eo/tutorial/Templates +have been simplified, and file stat.tmpl +has been added, allowing you to +compute and +print and +save-to-disk and +plot-on-line your +own statistics. +The magic script is now (see Lesson5) createSimple.
      + +The same simplified main file in +dir .../eo/tutorial/Templates) +also allows you to use +fitness sharing + (together with roulette wheel) as a possible selector.
      + +Unfortunately, the HTML file for Lesson5 and the corresponding +html-ized code are not yet updated - time is missing +(volunteers welcome).

      +
    • + +
      May 2002
      +
    • +
      +Thanks to Sébastien +Cahon (LIFL, Lille)
      + +
    +
    +
    Welcome to EO tutorial/on-line documentation.
    +

    About this tutorial

    +First, please note that this tutorial is not supposed +to be printed and read off-line, as it takes full advantage +of hyper-text links between the different parts, and with the technical +documentation. +This tutorial can be used in 2 different ways: algorithm-based and component-based. +
      +
    • +Algorithm-Based means you start from a very +simple, ready-to-run algorithm, and gradually modify it, making +it both more powerful and more complex.
    • + +
    • +Component-Based means you start by examining +the +components of an EA one by one, down to +the level of complexity you feel comfortable with, and then build the whole +algorithm using those components you need (or the one you are mastering). +Such approach might be viewed as going through a simplified user guide, +too.
    • +
    +However, it is strongly recommended +that you take some time on the first lesson of the Algorithm-Based approach +to get familiar with the basic concepts that are used throughout EO. Anyway, +as of today, December 19, the Component-Based is only very sparsely written +:-) +

    +


    Links and Related +documents +
      +
    • +There are of course a few (very few) programming +hints that you should know.
    • + +
    • +THe EO documentation - automatically +generated from the comments in the code - is very helpful to get an idea +of the inheritance diagrams of EO classes, +and to quickly reach some specific part of the code.
    • + +
      The top page of each class documentation is for instance the inheritance +diagram of the class, and you'll learn a lot by simply looking at it. +
    • +For those who wish to get deeper in STL (Standard Template Library), you +might visit the well documented SGI +STL Web site. But don't forget you'll find the very basic minimum in +EO programming hints.
    • + +
    • +And, last but not least, we assume you know approximately that an Evolutionary +Algorithm looks like this, but otherwise you can try this very +brief introduction (not written yet, Jan. 2001, sorry).
    • +
    + +


    +


    Colors and navigation: +

    You will see this diagram in quite many places, as for instance at the +top of all examples - usually it will be clickable and will help you navigate +among the different parts of an EO program. See the brief +introduction to Evolutionary Computation for a detailed explanation. +

    +

    + +

    But in the text itself, colors are important, +as they will be used throughout this tutorial to clearly mark which part +of the algorithm we are discussing. So please keep in mind that, whereas +orange +is for emphasis, +

      +
    • +Yellowish is for representation, +i.e. the choice of the genotype
    • + +
    • +Magenta is for the stochastic +operators that are representation-dependent, +i.e. initialisation and variation operators +(crossover, mutation +and the like).
    • + +
    • +Green is for the implementation of Darwinism, +i.e. the way the individuals are selected +for reproduction and survive.
    • + +
    • +Red is for evaluation, i.e. the computation +of the fitness of all individuals
    • + +
    • +Blue is for interactions of the user and the +program, as for instance choice of stopping criterion, +on-line display of nice statistics or initial +choice +of all program parameters.
    • + +
    • +Brown is for everything that is NOT part of +any of the above, i.e. random number generator, or basic C++/STL syntax +.
    • + +
    • +Note that pink will be used to describe the +syntax of compile orders (i.e. at the operating system level, see e.g. +below).
    • + +
    • +Last, but not least, all +links into EO documentation will use the Helvetica typeface, like this +line you are now reading.
    • +
    + +
    This tutorial is +not +
      +
    • +A course on Evolutionary Computation. You can find such things on the Internet, +maybe you can start here.
    • + +
    • +An interface that would allow you to build your Evolutionary Programs by +a few clicks; such a thing does exist, is called EASEA, +and is complementary to this tutorial as it helps the user to build some +simple EO programs from simple description. But there are things that EASEA +cannot do, and you will have to do it yourself and will need to increase +your knowledge about EO for that - hence this tutorial.
    • + +
    • +A coffee machine - though you might want to spend some time here when you're +tired of everything else, to improve your knowledge of EO slowly and gradually +rather than when you have something urgent to code :-)
    • +
    + +
    Before +you start +

    You should of course have downloaded and installed the whole EO +library (how did you get this file if not???). +If you are using a recent version of EO (0.9.3+), all tutorial Lessons +should have been compiled when installing the library, and you can now +proceed with Lesson1.
    +
    Otherwise, we'll assume that you are now in the tutorial directory, and that +your prompt looks something like +

    (myname@myhost) EOdir/tutorial % +

    so you should now type in +

    make Lesson1 +

    and see something like +

    (myname@myhost) +EOdir/tutorial % make Lesson1 +
    c++ -DPACKAGE=\"eo\" -DVERSION=\"0.9.1\" +-I. -I../../src -Wall -g -c FirstBitGA.cpp +
    c++ -Wall -g -o FirstBitGA FirstBitGA.o +../../src/libeo.a ../../src/utils/libeoutils.a +
    c++ -DPACKAGE=\"eo\" -DVERSION=\"0.9.1\" +-I. -I../../src -Wall -g -c FirstRealGA.cpp +
    c++ -Wall -g -o FirstRealGA FirstRealGA.o +../../src/libeo.a ../../src/utils/libeoutils.a +

    and two now executable files should have appeared in the subdirectory +Lesson1, namely FirstBitGA +and FirstRealGA (see First +lesson to know more about these two ready-to-run programs). If this +doesn't work, please go back to the main EO directory and run the installation +program. +

    You should also test that you can access the EO documentation in the +menu line below: you might not need to go there immediately, but just in +case you make rapid progress ... This menu bar should be on all pages of +this tutorial, allowing you to navigate easily. +

    Last, but not least: EO is improving only  from the good will of +contributors. This is also true for this tutorial: If you find anything +that you think could be improved, you are welcome to e-mail +me. +

    +

    Enjoy! +


    Algorithm-Based +- Component-Based - Programming +hints - EO +documentation
    + +
    +
    +Marc Schoenauer
    + +
    +Last +modified: Wed Feb 22 2006  + + diff --git a/deprecated/eo/tutorial/html/make_genotype_OneMax.html b/deprecated/eo/tutorial/html/make_genotype_OneMax.html new file mode 100644 index 000000000..3920e5548 --- /dev/null +++ b/deprecated/eo/tutorial/html/make_genotype_OneMax.html @@ -0,0 +1,160 @@ + + + + + + Templates/make_genotype_OneMax.h + + +Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
    +
    +
    +

    +Templates/make_genotype_OneMax.h

    +The places where you have to put some code are on pink +background.. +Only the the character colors have the usual meaning. +
      + + + + + +
    + +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
    + +//-----------------------------------------------------------------------------
    + +// 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
    +      version 2 of the License, or (at your option) any later version.
    +      This library is distributed in the hope that it will be useful,
    +      but WITHOUT ANY WARRANTY; without even the implied warranty of
    +      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    +      Lesser General Public License for more details.
    +      You should have received a copy of the GNU Lesser General Public
    +      License along with this library; if not, write to the Free Software
    +      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    +      Contact: todos@geneura.ugr.es, http://geneura.ugr.es
    +                        Marc.Schoenauer@inria.fr
    +                        mkeijzer@dhi.dk
    + */
    + +//-----------------------------------------------------------------------------
    +#ifndef _make_genotype_h
    +#define _make_genotype_h
    +#include <eoOneMax.h>
    +#include <eoOneMaxInit.h>
    +   +// also need the parser and param includes
    +#include <utils/eoParser.h>
    +#include <utils/eoState.h>
    + +/*
    + * This fuction does the create an eoInit<eoOneMax>
    + *
    + * 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
    + * allows to choose the type of genotype at run time (see in es dir)
    + *
    + * It returns an eoInit<EOT> 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
    + *                  that is ***not properly initialized***
    +*/
    +
    +
    + + + + +
    + +template <class EOT>
    +eoInit<EOT> & do_make_genotype(eoParser& _parser, eoState& _state, EOT)
    +{
    +
    +
    + + + + +
    + +   +// 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();
    +
    +
    + + + + +
    + +   +// Then built the initializer - a pointer, stored in the eoState
    +  eoInit<EOT>* init = new eoOneMaxInit<EOT> +/* ( param ) */ ; ;
    +
    +
    + + + + +
    + +   +// Eventually by passing the parameters you need
    +  //  eoInit<EOT>* init = new eoOneMaxInit<EOT> +/* ( param ) */ ; ;
    +
    +
    + + + + +
    + +   +// store in state
    +  _state.storeFunctor(init);
    +   +// and return a reference
    +  return *init;
    +}
    +#endif
    +
    +
    Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
    +
    +Marc Schoenauer
    +
    Last +modified: Fri May 3 07:10:52 2002 + + + diff --git a/deprecated/eo/tutorial/html/make_op_OneMax.html b/deprecated/eo/tutorial/html/make_op_OneMax.html new file mode 100644 index 000000000..a108fb14f --- /dev/null +++ b/deprecated/eo/tutorial/html/make_op_OneMax.html @@ -0,0 +1,351 @@ + + + + + + Templates/make_op_OneMax.h + + +Back to Lesson 5 +- Tutorial main page - Top-Down +page - Bottom-up page - Programming +hints - EO +documentation +
    +
    +
    +

    +Templates/make_op_OneMax.h

    +The places where you have to put some code are on pink +background.. Only the the character +colors have the usual meaning. +

    + + + + +
    // -*- mode: c++; c-indent-level: +4; c++-member-init-indent: 8; comment-column: 35; -*- +

    //----------------------------------------------------------------------------- +
    // 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 +
         version 2 of the +License, or (at your option) any later version. +
         This library is +distributed in the hope that it will be useful, +
         but WITHOUT ANY +WARRANTY; without even the implied warranty of +
         MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU +
         Lesser General Public +License for more details. +
         You should have +received a copy of the GNU Lesser General Public +
         License along with +this library; if not, write to the Free Software +
         Foundation, Inc., +59 Temple Place, Suite 330, Boston, MA  02111-1307  USA +
         Contact: todos@geneura.ugr.es, +http://geneura.ugr.es +
                           +Marc.Schoenauer@inria.fr +
                           +mkeijzer@dhi.dk +
    */ +
    //----------------------------------------------------------------------------- +

    #ifndef _make_op_OneMax_h +
    #define _make_op_OneMax_h +

    // the operators +
    #include <eoOp.h> +
    #include <eoGenOp.h> +
    #include <eoCloneOps.h> +
    #include <eoOpContainer.h> +
    // combinations of simple eoOps (eoMonOp +and eoQuadOp) +
    #include <eoProportionalCombinedOp.h> +

    /** definition of mutation:  +
    * class eoOneMaxMonop MUST derive from eoMonOp<eoOneMax> +
    */ +
    #include "eoOneMaxMutation.h" +

    /** definition of crossover (either as eoBinOp +(2->1) or eoQuadOp (2->2):  +
    * class eoOneMaxBinCrossover MUST derive +from eoBinOp<eoOneMax> +
    * OR  +
    * class eoOneMaxQuadCrossover MUST derive +from eoQuadOp<eoOneMax> +
    */ +
    // #include "eoOneMaxBinOp.h" +
    // OR +
    #include "eoOneMaxQuadCrossover.h" +

      // also need the parser and +state includes +
    #include <utils/eoParser.h> +
    #include <utils/eoState.h> +

    /////////////////// variation operators /////////////// +
    // canonical (crossover + mutation) only +at the moment // +

    /* +
    * 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  +
    *      about the +genotypes, the init has it all (e.g. bounds, ...) +
    *      Simply do  +
    *              +EOT myEO; +
    *              +_init(myEO); +
    *      and myEO +is then an ACTUAL object +
    * +
    * As usual, the template is the complete +EOT even though only the fitness +
    * is actually templatized here: the following +only applies to eoOneMax +
    */

    + + + + + +
    template <class EOT> +
    eoGenOp<EOT> & do_make_op(eoParameterLoader& +_parser, eoState& _state, eoInit<EOT>& _init) +
    { +
      // this is a temporary version, +while Maarten codes the full tree-structured +
      // general operator input +
      // BTW we must leave that simple +version available somehow, as it is the one +
      // that 90% people use! +

          ///////////////////////////// +
          // +Variation operators +
          //////////////////////////// +
          // +read crossover and mutations, combine each in a proportional Op +
          // +and create the eoGenOp that calls crossover at rate pCross  +
          // +then mutation with rate pMut +

          // the +crossovers +
          ///////////////// +

          // here +we can have eoQuadOp (2->2) 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  +
         +eoQuadOp<Indi> *cross = new eoOneMaxQuadCrossover<Indi> /* (varType  +_anyVariable) */; +
          // +store in the state +
         _state.storeFunctor(cross); +

      // read its relative rate in +the combination +
         double cross1Rate += _parser.createParam(1.0, "cross1Rate", "Relative rate for crossover 1", +'1', "Variation Operators").value(); +

      // and create the combined operator +with this one +
     eoPropCombinedQuadOp<Indi> *propXover +=  +
         new eoPropCombinedQuadOp<Indi>(*cross, +cross1Rate); +
      // and of course stor it in +the state +
         _state.storeFunctor(propXover); +
     

    + + + + + +
          +// Optional: A second(and third, and ...)  crossover  +
          //    +of course you must create the corresponding classes +
          // +and all ***MUST*** derive from eoQuadOp<Indi> +

      /* Uncomment if necessary - +and replicate as many time as you need +
             +cross = new eoOneMaxSecondCrossover<Indi>(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);  +
     */ +
      // if you want some gentle +output, the last one shoudl be like +
      //  propXover.add(*cross, +crossXXXRate, true); +
     

    + + + + + +
    +
      // the mutation: same story +
      //////////////// +
      // you can have more than one +- combined in a proportional way +

      // for each mutation,  +
      // - define the mutator object +
      // - read its rate from the +parser +
      // - add it to the proportional +combination +

      // a first mutation  +
    eoMonOp<Indi> +*mut = new eoOneMaxMutation<Indi> /* (varType  +_anyVariable) */; +
     _state.storeFunctor(mut); +
      // its relative rate in the +combination +
     double mut1Rate = _parser.createParam(1.0, +"mut1Rate", "Relative rate for mutation 1", '1', "Variation Operators").value(); +
      // and the creation of the +combined operator with this one +
     eoPropCombinedMonOp<Indi> *propMutation += new eoPropCombinedMonOp<Indi>(*mut, mut1Rate); +
     _state.storeFunctor(propMutation); +
     

    + + + + + +
          +// Optional: A second(and third, and ...)  mutation with their rates +
          //    +of course you must create the corresponding classes +
          // +and all ***MUST*** derive from eoMonOp<Indi> +

      /* Uncomment if necessary - +and replicate as many time as you need +
             +mut = new eoOneMaxSecondMutation<Indi>(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);  +
     */ +
      // if you want some gentle +output, the last one shoudl be like +
      //  propMutation.add(*mut, +mutXXXRate, true); +

      // end of crossover and mutation +definitions +
     

    + + + + + +
    +
    // from now on, you do not need to modify +anything +
    // though you CAN add things to the checkpointing +(see tutorial) +

      // now build the eoGenOp: +
      // 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  +
      //                                              +a QuadCopy and our crossover +
      //                  +with proba pMut, our mutation +

      // but of course you're free +to use any smart combination you could think of +
      // especially, if you have +to use eoBinOp rather than eoQuad Op youùll have +
      // to modify that part +

      // +First read the individual level parameters +
         eoValueParam<double>& +pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", +'C', "Variation Operators" ); +
          // +minimum check +
         if ( (pCrossParam.value() +< 0) || (pCrossParam.value() > 1) ) +
             +throw runtime_error("Invalid pCross"); +

         eoValueParam<double>& +pMutParam = _parser.createParam(0.1, "pMut", "Probability of Mutation", +'M', "Variation Operators" ); +
          // +minimum check +
         if ( (pMutParam.value() +< 0) || (pMutParam.value() > 1) ) +
             +throw runtime_error("Invalid pMut"); +

      // the crossover - with probability +pCross +
     eoProportionalOp<Indi> * propOp += new eoProportionalOp<Indi> ; +
     _state.storeFunctor(propOp); +
     eoQuadOp<Indi> *ptQuad = new +eoQuadCloneOp<Indi>; +
     _state.storeFunctor(ptQuad); +
     propOp->add(*propXover, pCrossParam.value()); +// +crossover, with proba pcross +
     propOp->add(*ptQuad, 1-pCrossParam.value()); +// +nothing, with proba 1-pcross +

      // now the sequential +
     eoSequentialOp<Indi> *op = new +eoSequentialOp<Indi>; +
     _state.storeFunctor(op); +
     op->add(*propOp, 1.0); // always +do combined crossover +
     op->add(*propMutation, pMutParam.value()); +// +then mutation, with proba pmut +

      // that's it - return a reference +
     return *op; +
    } +

    #endif

    + +


    Back to Lesson 5 - Tutorial +main page - Top-Down page - Bottom-up +page - Programming hints - EO +documentation +
    +
    +Marc Schoenauer
    + +
    Last modified: Fri May +3 08:06:20 2002 + + diff --git a/deprecated/eo/tutorial/html/real_value.html b/deprecated/eo/tutorial/html/real_value.html new file mode 100644 index 000000000..a5ec17852 --- /dev/null +++ b/deprecated/eo/tutorial/html/real_value.html @@ -0,0 +1,56 @@ + + + + + + real_value.h + + +Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - +EO documentation +
    +
    +
    + + + + +
    #include <vector> +
    //----------------------------------------------------------------------------- +
    /** Just a simple function that takes an +vector<double> and sets the fitnes  +
         to the sphere function. +Please use doubles not float!!! +
         @param _ind A floatingpoint +vector  +
    */
    + + + + + +
    double real_value(const std::vector<double>& +_ind) +
    { +
     double sum = 0; +
     for (unsigned i = 0; i < _ind.size(); +i++) +
             +sum += _ind[i] * _ind[i]; +
     return -sum; +
    }
    + +
    Back to Lesson 2 - Tutorial +main page - Algorithm-Based - Component-Based +page - Programming hints - EO +documentation +
    +
    +Marc Schoenauer
    + +
    Last modified: Wed Nov +29 08:58:50 2000 + + diff --git a/deprecated/eo/tutorial/index.html b/deprecated/eo/tutorial/index.html new file mode 100644 index 000000000..81b87972b --- /dev/null +++ b/deprecated/eo/tutorial/index.html @@ -0,0 +1,26 @@ + + + + + + Tutorial EO + + + +
    +
    +

    +EO Tutorial

    +Welcome to EO - the Evolving Objects library. +

    But you are not in the right place! +
    You should better try to go to the html directory, for instance by +clicking here. +

    +


    +
    +Marc Schoenauer
    + +
    Last +modified: Fri Nov 28 CET 2000  + + diff --git a/edo/AUTHORS b/edo/AUTHORS new file mode 100644 index 000000000..d66d82bf8 --- /dev/null +++ b/edo/AUTHORS @@ -0,0 +1,35 @@ +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group + +Authors: + +N:Johann Dréo +P:nojhan +E:johann.dreo@thalesgroup.com +D:2010-07-01 +C:original design and code + +N:Caner Candan +P: +E:caner.candan@thalesgroup.com +D:2010-07-01 +C:original design and code + +As of 2011-01-25, Thales SA disclaims all copyright interest in the Evolving Distribution Objects (EDO) framework. diff --git a/edo/CMakeLists.txt b/edo/CMakeLists.txt new file mode 100644 index 000000000..8bb80abc8 --- /dev/null +++ b/edo/CMakeLists.txt @@ -0,0 +1,50 @@ + +IF(EDO_USE_LIB STREQUAL "uBLAS") + FIND_PACKAGE(Boost ) + IF( Boost_FOUND ) + INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIRS} ) + ADD_DEFINITIONS( -DWITH_BOOST ) + ELSE() + MESSAGE( "ERROR: You asked for Boost::uBLAS but it has not been found." ) + SET(IS_FATAL 1) + ENDIF() +ELSEIF( EDO_USE_LIB STREQUAL "Eigen3" ) + # FIXME FindEigen3.cmake does not work + #find_package(Eigen3) + #include_directories(EIGEN3_INCLUDE_DIR) + SET( EIGEN3_FOUND 1) + SET( EIGEN3_INCLUDE_DIR "/usr/include/eigen3/" ) + + IF( EIGEN3_FOUND ) + INCLUDE_DIRECTORIES( ${EIGEN3_INCLUDE_DIR} ) + ADD_DEFINITIONS( -DWITH_EIGEN ) + ELSE() + MESSAGE( "ERROR: You asked for Eigen3 but it has not been found." ) + SET(IS_FATAL 1) + ENDIF() + +ELSE() + # FIXME ideally, we would have a minimal implementation with STL vectors… + MESSAGE( "You must set EDO_USE_LIB to either 'uBLAS' or 'Eigen3'." ) + SET(IS_FATAL 1) +ENDIF() + + +###################################################################################### +### Include subdirectories +###################################################################################### + +add_subdirectory(doc) +add_subdirectory(src) + +if(ENABLE_CMAKE_TESTING) + add_subdirectory(test) +endif(ENABLE_CMAKE_TESTING) + +if(ENABLE_CMAKE_EXAMPLE) + if(${CMAKE_VERBOSE_MAKEFILE}) + message("EDO examples:") + endif(${CMAKE_VERBOSE_MAKEFILE}) + add_subdirectory(application) +endif(ENABLE_CMAKE_EXAMPLE) + diff --git a/edo/COPYING b/edo/COPYING new file mode 100644 index 000000000..d4537832c --- /dev/null +++ b/edo/COPYING @@ -0,0 +1,502 @@ + 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 + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +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 + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +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 +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +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 + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +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 + + 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 +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you 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.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/edo/NEWS b/edo/NEWS new file mode 100644 index 000000000..9c3ee2d28 --- /dev/null +++ b/edo/NEWS @@ -0,0 +1,10 @@ +* current release: + +* release 1.3.0 (2011-07-24) + - alternative implementation of the multi-normal operators using the Eigen3 library + +* release 0.0 (2011-09-15) + - basic design for estimation of distribution algorithms and, more generally for randomized search heuristics + - continuous EDA example + - EDA using multi-normal distribution, implementation using the boost::ublas library + diff --git a/edo/Packaging.cmake b/edo/Packaging.cmake new file mode 100644 index 000000000..d5104c512 --- /dev/null +++ b/edo/Packaging.cmake @@ -0,0 +1,74 @@ +###################################################################################### +### 1) Check dependencies +###################################################################################### + +IF (NOT DEFINED PROJECT_NAME OR + NOT DEFINED PROJECT_VERSION_MAJOR OR + NOT DEFINED PROJECT_VERSION_MINOR OR + NOT DEFINED PROJECT_VERSION_PATCH OR + NOT DEFINED PROJECT_VERSION) + MESSAGE(FATAL_ERROR "Be sure you have defined PROJECT_NAME and PROJECT_VERSION*.") +ENDIF() + +###################################################################################### + + +###################################################################################### +### 2) Set up components +###################################################################################### + +SET(CPACK_COMPONENTS_ALL libraries) +SET(CPACK_ALL_INSTALL_TYPES Full) + +SET(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "Distribution Objects") +SET(CPACK_COMPONENT_LIBRARIES_DESCRIPTION "Distribution Objects library") +SET(CPACK_COMPONENT_LIBRARIES_GROUP "Devel") +SET(CPACK_COMPONENT_LIBRARIES_INSTALL_TYPES Full) + +###################################################################################### + + +###################################################################################### +### 3) Set up general information about packaging +###################################################################################### + +# For more details: http://www.cmake.org/Wiki/CMake:Component_Install_With_CPack + +#cpack package information +SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README") +SET(CPACK_PACKAGE_DESCRIPTION "Distribution Objects") +SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING") +SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Distribution Objects") +SET(CPACK_PACKAGE_VENDOR "Thales") +SET(CPACK_PACKAGE_CONTACT "caner.candan@thalesgroup.com") +SET(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) +SET(CPACK_STRIP_FILES ${PROJECT_NAME}) +SET(CPACK_SOURCE_STRIP_FILES "bin/${PROJECT_NAME}") +SET(CPACK_PACKAGE_EXECUTABLES "${PROJECT_NAME}" "${PROJECT_NAME}") +SET(CPACK_PACKAGE_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") +SET(CPACK_PACKAGE_VERSION_MINOR "${PROJECT_VERSION_MINOR}") +SET(CPACK_PACKAGE_VERSION_PATCH "${PROJECT_VERSION_PATCH}") +SET(CPACK_PACKAGE_INSTALL_DIRECTORY "${PROJECT_NAME} ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}") + +###################################################################################### + + +###################################################################################### +### 4) Set up debian packaging information +###################################################################################### + +SET(CPACK_DEBIAN_PACKAGE_DEPENDS "libstdc++6, libgcc1, libc6, libxml2, libmpich2-1.2, eo, mo") + +SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") +SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") + +###################################################################################### + + +###################################################################################### +### 5) And finally, include cpack, this is the last thing to do. +###################################################################################### + +INCLUDE(CPack) + +###################################################################################### diff --git a/edo/README b/edo/README new file mode 100644 index 000000000..4217a844e --- /dev/null +++ b/edo/README @@ -0,0 +1,57 @@ +This package contains the source code for EDO. + +# Step 1 - Configuration +------------------------ +Rename the "install.cmake-dist" file as "install.cmake" and edit it, inserting the FULL PATH +to your ParadisEO distribution. +On Windows write your path with double antislash (ex: C:\\Users\\...) + + +# Step 2 - Build process +------------------------ +ParadisEO is assumed to be compiled. To download ParadisEO, please visit http://paradiseo.gforge.inria.fr/. +Go to the DO/build/ directory and lunch cmake: +(Unix) > cmake .. +(Windows) > cmake .. -G"Visual Studio 9 2008" + +Note for windows users: if you don't use VisualStudio 9, enter the name of your generator instead of "VisualStudio 9 2008". + + +# Step 3 - Compilation +---------------------- +In the edo/build/ directory: +(Unix) > make +(Windows) Open the VisualStudio solution and compile it, compile also the target install. +You can refer to this tutorial if you don't know how to compile a solution: http://paradiseo.gforge.inria.fr/index.php?n=Paradiseo.VisualCTutorial + + +# Step 4 - Execution +--------------------- +A toy example is given to test the components. You can run these tests as following. +To define problem-related components for your own problem, please refer to the tutorials available on the website : http://paradiseo.gforge.inria.fr/. +In the edo/build/ directory: +(Unix) > ctest +Windows users, please refer to this tutorial: http://paradiseo.gforge.inria.fr/index.php?n=Paradiseo.VisualCTutorial + +In the directory "application", there are several directory such as eda which instantiate EDA solver. + +(Unix) After compilation you can run the binary "build/eda" and see results. Parameters can be modified from command line. + +(Windows) Add argument "eda.param" and execute the corresponding algorithms. +Windows users, please refer to this tutorial: http://paradiseo.gforge.inria.fr/index.php?n=Paradiseo.VisualCTutorial + + +# Documentation +--------------- +The API-documentation is available in doc/html/index.html + + +# Things to keep in mind when using EDO +---------------------------------------- +* By default, the EO random generator's seed is initialized by the number of seconds since the epoch (with time(0)). It is available in the status file dumped at each execution. Please, keep in mind that if you start two run at the same second without modifying the seed, you will get exactly the same results. + +* Execution times are measured with the boost:timer, that measure wallclock time. Additionaly, it could not measure times larger than approximatively 596.5 hours (or even less). See http://www.boost.org/doc/libs/1_33_1/libs/timer/timer.htm + +* The q-quantile computation use averaging at discontinuities (in R, it correspond to the R-2 method, in SAS, SAS-5). For more explanations, see http://en.wikipedia.org/wiki/Quantile#Estimating_the_quantiles_of_a_population and http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html + +* You can send a SIGUSR1 to a process to get some information (written down in the log file) on the current state of the search. diff --git a/edo/application/CMakeLists.txt b/edo/application/CMakeLists.txt new file mode 100644 index 000000000..88462c0a7 --- /dev/null +++ b/edo/application/CMakeLists.txt @@ -0,0 +1,14 @@ +###################################################################################### +### 1) Where do we go now ?!? +###################################################################################### + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/common + ) + +ADD_SUBDIRECTORY(common) # Rosenbrock and Sphere +#ADD_SUBDIRECTORY(eda_sa) +ADD_SUBDIRECTORY(eda) +ADD_SUBDIRECTORY(cmaes) + +###################################################################################### diff --git a/edo/application/cmaes/CMakeLists.txt b/edo/application/cmaes/CMakeLists.txt new file mode 100644 index 000000000..3fb2b0466 --- /dev/null +++ b/edo/application/cmaes/CMakeLists.txt @@ -0,0 +1,37 @@ +project(cmaes) + + +#find_package(Eigen3 REQUIRED) +#include_directories(EIGEN3_INCLUDE_DIR) +include_directories( ${EIGEN3_INCLUDE_DIR} ) +#message( "MESSAGE:" ${EIGEN3_INCLUDE_DIR} ) + +#find_package(Boost 1.33.0) +include_directories(${Boost_INCLUDE_DIRS}) +link_directories(${Boost_LIBRARY_DIRS}) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EDO_SRC_DIR}/src) +link_directories(${EO_BIN_DIRS}/${LIB}) +link_directories(${EDO_BIN_DIRS}/${LIB}) + +# set(RESOURCES +# ${PROJECT_NAME}.param +# ) +# +# foreach(file ${RESOURCES}) +# execute_process( +# COMMAND ${CMAKE_COMMAND} -E copy_if_different +# ${CMAKE_CURRENT_SOURCE_DIR}/${file} +# ${EDO_BIN_DIR}/${file} +# ) +# endforeach(file) + +#file(GLOB SOURCES *.cpp) + +set(EXECUTABLE_OUTPUT_PATH ${EDO_BIN_DIR}) + +add_executable(${PROJECT_NAME} main.cpp) +target_link_libraries(${PROJECT_NAME} eo eoutils edoutils ${Boost_LIBRARIES}) + diff --git a/edo/application/cmaes/main.cpp b/edo/application/cmaes/main.cpp new file mode 100644 index 000000000..ed7f10a44 --- /dev/null +++ b/edo/application/cmaes/main.cpp @@ -0,0 +1,156 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#include +//#include + +#include + +#include +#include +#include +#include + +#include + +#include "Rosenbrock.h" +#include "Sphere.h" + + +typedef eoReal RealVec; +typedef edoNormalAdaptive< RealVec > Distrib; + + +int main(int ac, char** av) +{ + eoParser parser(ac, av); + + eoState state; + // Letters used by the following declarations: + unsigned long max_eval = parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion").value(); // E + unsigned int dim = parser.createParam((unsigned int)10, "dimension-size", "Dimension size", 'd', "Problem").value(); // d + + double mu = dim / 2; + + edoNormalAdaptive distribution(dim); + + eoSelect< RealVec >* selector = new eoRankMuSelect< RealVec >( mu ); + state.storeFunctor(selector); + + edoEstimator< Distrib >* estimator = new edoEstimatorNormalAdaptive( distribution ); + state.storeFunctor(estimator); + + eoEvalFunc< RealVec >* plainEval = new Rosenbrock< RealVec >(); + state.storeFunctor(plainEval); + + eoEvalFuncCounterBounder< RealVec > eval(*plainEval, max_eval); + + eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); + state.storeFunctor(gen); + + + eoInitFixedLength< RealVec >* init = new eoInitFixedLength< RealVec >( dim, *gen ); + state.storeFunctor(init); + + + // (1) Population init and sampler + // Generation of population from do_make_pop (creates parameters, manages persistance and so on...) + // ... and creates the parameters: L P r S + // this first sampler creates a uniform distribution independently from our distribution (it does not use edoUniform). + eoPop< RealVec >& pop = do_make_pop(parser, state, *init); + + // (2) First evaluation before starting the research algorithm + apply(eval, pop); + + // Prepare bounder class to set bounds of sampling. + // This is used by edoSampler. + edoBounder< RealVec >* bounder = + new edoBounderRng< RealVec >( RealVec(dim, -5), RealVec(dim, 5), *gen); // FIXME do not use hard-coded bounds + state.storeFunctor(bounder); + + // Prepare sampler class with a specific distribution + edoSampler< Distrib >* sampler = new edoSamplerNormalAdaptive< RealVec >( *bounder ); + state.storeFunctor(sampler); + + // stopping criteria + // ... and creates the parameter letters: C E g G s T + eoContinue< RealVec >& eo_continue = do_make_continue(parser, state, eval); + + // population output + eoCheckPoint< RealVec >& pop_continue = do_make_checkpoint(parser, state, eval, eo_continue); + // keep the best solution found so far in an eoStat + // thus, if the population's best individual fitness decreases during the search, we could + // still keep the best found since the beginning, while avoiding the bias of elitism on the sample + eoBestIndividualStat best_indiv; + pop_continue.add( best_indiv ); + + // distribution output + edoDummyContinue< Distrib >* dummy_continue = new edoDummyContinue< Distrib >(); + state.storeFunctor(dummy_continue); + + edoCheckPoint< Distrib >* distribution_continue = new edoCheckPoint< Distrib >( *dummy_continue ); + state.storeFunctor(distribution_continue); + + eoReplacement< RealVec >* replacor = new eoCommaReplacement< RealVec >(); + state.storeFunctor(replacor); + + // Help + Verbose routines + make_verbose(parser); + make_help(parser); + + // Some stuff to display helper when we are using -h option + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + eoPopLoopEval popEval( eval ); + + // CMA-ES algorithm configuration + edoAlgo< Distrib >* algo = new edoAlgoAdaptive< Distrib > + (distribution, popEval, *selector, *estimator, *sampler, *replacor, + pop_continue, *distribution_continue ); + + // Use the best solution of the random first pop to start the search + // That is, center the distribution's mean on it. + distribution.mean( pop.best_element() ); + + // Beginning of the algorithm call + try { + eo::log << eo::progress << "Best solution after random init: " << pop.best_element().fitness() << std::endl; + do_run(*algo, pop); + + } catch (eoEvalFuncCounterBounderException& e) { + eo::log << eo::warnings << "warning: " << e.what() << std::endl; + } + + // use the stat instead of the pop, to get the best solution of the whole search + std::cout << best_indiv.value() << std::endl; + + return 0; +} diff --git a/edo/application/common/CMakeLists.txt b/edo/application/common/CMakeLists.txt new file mode 100644 index 000000000..f9ddc8cdc --- /dev/null +++ b/edo/application/common/CMakeLists.txt @@ -0,0 +1,15 @@ +PROJECT(common) + +SET(RESOURCES + gplot.py + ggobi.py + boxplot_eda_n_edasa.py + ) + +FOREACH(file ${RESOURCES}) + EXECUTE_PROCESS( + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/${file} + ${EDO_BIN_DIR}/${file} + ) +ENDFOREACH(file) diff --git a/edo/application/common/Rosenbrock.h b/edo/application/common/Rosenbrock.h new file mode 100644 index 000000000..c21a8ccea --- /dev/null +++ b/edo/application/common/Rosenbrock.h @@ -0,0 +1,42 @@ +#ifndef _Rosenbrock_h +#define _Rosenbrock_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +template < typename EOT > +class Rosenbrock : public eoEvalFunc< EOT > +{ +public: + typedef typename EOT::AtomType AtomType; + + virtual void operator()( EOT& p ) + { + if (!p.invalid()) + return; + + p.fitness( _evaluate( p ) ); + } + +private: + AtomType _evaluate( EOT& p ) + { + AtomType r = 0.0; + + for (unsigned int i = 0; i < p.size() - 1; ++i) + { + r += p[i] * p[i]; + } + + return r; + } +}; + +#endif // !_Rosenbrock_h diff --git a/edo/application/common/Sphere.h b/edo/application/common/Sphere.h new file mode 100644 index 000000000..1e73b3eaf --- /dev/null +++ b/edo/application/common/Sphere.h @@ -0,0 +1,42 @@ +#ifndef _Sphere_h +#define _Sphere_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +template < typename EOT > +class Sphere : public eoEvalFunc< EOT > +{ +public: + typedef typename EOT::AtomType AtomType; + + virtual void operator()( EOT& p ) + { + if (!p.invalid()) + return; + + p.fitness( _evaluate( p ) ); + } + +private: + AtomType _evaluate( EOT& p ) + { + AtomType r = 0.0; + + for (unsigned int i = 0; i < p.size() - 1; ++i) + { + r += p[i] * p[i]; + } + + return r; + } +}; + +#endif // !_Sphere_h diff --git a/edo/application/common/boxplot_eda_n_edasa.py b/edo/application/common/boxplot_eda_n_edasa.py new file mode 100755 index 000000000..a4086a677 --- /dev/null +++ b/edo/application/common/boxplot_eda_n_edasa.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +from pylab import * +#from pprint import pprint + +FILE_LOCATIONS = 'EDA_ResPop/list_of_files.txt' + +data = [] + +locations = [ line.split()[0] for line in open( FILE_LOCATIONS ) ] +#pprint( locations ) + +for cur_file in locations: + fitnesses = [ float(line.split()[0]) for line in open( cur_file ).readlines()[1:-1] ] + data.append( fitnesses[1:] ) + +#pprint( data ) + +boxplot( data ) + +# FILE_LOCATIONS = 'EDASA_ResPop/list_of_files.txt' + +# data = [] + +# locations = [ line.split()[0] for line in open( FILE_LOCATIONS ) ] +# #pprint( locations ) + +# for cur_file in locations: +# fitnesses = [ float(line.split()[0]) for line in open( cur_file ).readlines()[1:-1] ] +# data.append( fitnesses[1:] ) + +# #pprint( data ) + +# boxplot( data ) + +show() diff --git a/edo/application/common/ggobi.py b/edo/application/common/ggobi.py new file mode 100755 index 000000000..2e9341830 --- /dev/null +++ b/edo/application/common/ggobi.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python + +from pprint import * +import sys, os + +if __name__ == '__main__': + + # parameter phase + + if len(sys.argv) < 2: + print 'Usage: %s [FILE]' % sys.argv[0] + sys.exit() + + filename = sys.argv[1] + + lines = open(filename).readlines() + + # formatting phase + + try: + results = [ x.split() for x in lines[1:-1] ] + except IOError, e: + print 'Error: %s' % e + sys.exit() + + # dimension estimating phase + + popsize = int(lines[0].split()[0]) + dimsize = int(results[0][1]) + + # printing phase + + print 'popsize: %d' % popsize + print 'dimsize: %d' % dimsize + + print + pprint( results ) + + # cvs converting phase + + i = 1 + for x in results: + x.insert(0, '"%d"' % i) + i += 1 + + header = ['""', '"fitness"', '"dimsize"'] + + for i in range(0, dimsize): + header.append( '"dim%d"' % i ) + + results.insert(0, header) + + # cvs printing phase + + file_results = '\n'.join( [ ','.join( x ) for x in results ] ) + + print + print file_results + + try: + open('%s.csv' % filename, 'w').write(file_results + '\n') + except IOError, e: + print 'Error: %s' % e + sys.exit() + + # ggobi plotting phase + + os.system('ggobi %s.csv' % filename) diff --git a/edo/application/common/gplot.py b/edo/application/common/gplot.py new file mode 100755 index 000000000..55e95cb01 --- /dev/null +++ b/edo/application/common/gplot.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python + +"""plot.py -- Plot EDA-SA results file""" + +import os, time, math, tempfile +import numpy + +try: + import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils +except ImportError: + # kludge in case Gnuplot hasn't been installed as a module yet: + import __init__ + Gnuplot = __init__ + import PlotItems + Gnuplot.PlotItems = PlotItems + import funcutils + Gnuplot.funcutils = funcutils + +import optparse, logging, sys + +LEVELS = {'debug': logging.DEBUG, + 'info': logging.INFO, + 'warning': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL} + +def logger(level_name, filename='plot.log'): + 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) + +def parser(parser=optparse.OptionParser()): + parser.add_option('-v', '--verbose', choices=LEVELS.keys(), default='warning', help='set a verbose level') + parser.add_option('-f', '--files', help='give some input sample files separated by comma (cf. gen1,gen2,...)', default='') + parser.add_option('-r', '--respop', help='define the population results containing folder', default='./ResPop') + parser.add_option('-o', '--output', help='give an output filename for logging', default='plot.log') + parser.add_option('-d', '--dimension', help='give a dimension size', default=2) + parser.add_option('-m', '--multiplot', action="store_true", help='plot all graphics in one window', dest="multiplot", default=True) + parser.add_option('-p', '--plot', action="store_false", help='plot graphics separetly, one by window', dest="multiplot") + parser.add_option('-w', '--windowid', help='give the window id you want to display, 0 means we display all ones, this option should be combined with -p', default=0) + parser.add_option('-G', '--graphicsdirectory', help='give a directory name for graphics, this option should be combined with -u', default='plot') + parser.add_option('-g', '--graphicsprefixname', help='give a prefix name for graphics, this option should be combined with -u', default='plot') + parser.add_option('-t', '--terminal', action="store_true", help='display graphics on gnuplot windows', dest="terminal", default=True) + parser.add_option('-u', '--png', action="store_false", help='display graphics on png files', dest="terminal") + + options, args = parser.parse_args() + + logger(options.verbose, options.output) + + return options + +options = parser() + +def wait(str=None, prompt='Press return to show results...\n'): + if str is not None: + print str + raw_input(prompt) + +def draw2DRect(min=(0,0), max=(1,1), color='black', state=None, g=None): + if g == None: g = Gnuplot.Gnuplot() + if state != None: state.append(g) + + xmin, ymin = min + xmax, ymax = max + + cmd = 'set arrow from %s,%s to %s,%s nohead lc rgb "%s"' + + g(cmd % (xmin, ymin, xmin, ymax, color)) + g(cmd % (xmin, ymax, xmax, ymax, color)) + g(cmd % (xmax, ymax, xmax, ymin, color)) + g(cmd % (xmax, ymin, xmin, ymin, color)) + + return g + +def draw3DRect(min=(0,0,0), max=(1,1,1), state=None, g=None): + if g == None: g = Gnuplot.Gnuplot() + if state != None: state.append(g) + + # TODO + + return g + +def getSortedFiles(path): + assert path != None + + if options.files == '': + + filelist = os.listdir(path) + filelist.sort() + + else: + + filelist = options.files.split(',') + + checkFileErrors(path, filelist) + + return filelist + +def checkFileErrors(path, filelist): + for filename in filelist: + for line in open('%s/%s' % (path, filename)): + if '-nan' in line: + logging.warning("checkFileErrors: %s/%s file contains bad value, it is going to be skipped" % (path, filename)) + filelist.remove(filename) + break + +def plotXPointYFitness(path, fields='3:1', state=None, g=None): + if g == None: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXPointYFitness')) + + if state != None: state.append(g) + + g.title('Fitness observation') + g.xlabel('Coordinates') + g.ylabel('Fitness (Quality)') + + files=[] + for filename in getSortedFiles(path): + files.append(Gnuplot.File(path + '/' + filename, using=fields, + with_='points', + #title='distribution \'' + filename + '\'' + title="" + ) + ) + + if len(files) > 0: + g.plot(*files) + + return g + +def plotXYPointZFitness(path, fields='4:3:1', state=None, g=None): + if g == None: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYPointZFitness')) + + if state != None: state.append(g) + + g.title('Fitness observation in 3-D') + g.xlabel('x-axes') + g.ylabel('y-axes') + g.zlabel('Fitness (Quality)') + + files=[] + for filename in getSortedFiles(path): + files.append(Gnuplot.File(path + '/' + filename, using=fields, + with_='points', + #title='distribution \'' + filename + '\'' + title="" + ) + ) + + if len(files) > 0: + g.splot(*files) + + return g + +def plotXYPoint(path, fields='3:4', state=None, g=None): + if g == None: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYPoint')) + + if state != None: state.append(g) + + g.title('Points observation in 2-D') + g.xlabel('x-axes') + g.ylabel('y-axes') + + files=[] + for filename in getSortedFiles(path): + files.append(Gnuplot.File(path + '/' + filename, using=fields, + with_='points', + #title='distribution \'' + filename + '\'' + title="" + ) + ) + + if len(files) > 0: + g.plot(*files) + + return g + +def plotXYZPoint(path, fields='3:4:5', state=None, g=None): + if g == None: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYZPoint')) + + if state != None: state.append(g) + + g.title('Points observation in 3-D') + g.xlabel('x-axes') + g.ylabel('y-axes') + g.zlabel('z-axes') + + files=[] + for filename in getSortedFiles(path): + files.append(Gnuplot.File(path + '/' + filename, using=fields, + with_='points', + #title='distribution \'' + filename + '\'' + title="" + ) + ) + + if len(files) > 0: + g.splot(*files) + + return g + +def plotParams(path, field='1', state=None, g=None): + if g == None: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'plotXYZPoint')) + + if state != None: state.append(g) + + g.title('Hyper-volume comparaison through all dimensions') + g.xlabel('Iterations') + g.ylabel('Hyper-volume') + + g.plot(Gnuplot.File(path, with_='lines', using=field, + title='multivariate distribution narrowing')) + + return g + +def plot2DRectFromFiles(path, state=None, g=None, plot=True): + if g == None: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s_%s.png\'' % (options.graphicsprefixname, 'plot2DRectFromFiles')) + + if state != None: state.append(g) + + g.title('Rectangle drawing observation') + g.xlabel('x-axes') + g.ylabel('y-axes') + + x1,x2,y1,y2 = 0,0,0,0 + + colors = ['red', 'orange', 'blue', 'green', 'gold', 'yellow', 'gray'] + #colors = open('rgb.txt', 'r').readlines() + colors_size = len(colors) + i = 0 # for color + + for filename in getSortedFiles(path): + line = open(path + '/' + filename, 'r').readline() + + fields = line.split(' ') + + if not fields[0] == '2': + print 'plot2DRectFromFiles: higher than 2 dimensions not possible to draw' + return + + xmin,ymin,xmax,ymax = fields[1:5] + #print xmin,ymin,xmax,ymax + + cur_color = colors[i % colors_size] + + draw2DRect((xmin,ymin), (xmax,ymax), cur_color, g=g) + + g('set obj rect from %s,%s to %s,%s back lw 1.0 fc rgb "%s" fillstyle solid 1.00 border -1' + % (xmin,ymin,xmax,ymax,cur_color) + ) + + if plot: + if float(xmin) < x1: x1 = float(xmin) + if float(ymin) < y1: y1 = float(ymin) + if float(xmax) > x2: x2 = float(xmax) + if float(ymax) > y2: y2 = float(ymax) + + #print x1,y1,x2,y2 + + i += 1 + + #print x1,y1,x2,y2 + + if plot: + g.plot('[%s:%s][%s:%s] -9999 notitle' % (x1, x2, y1, y2)) + + return g + +def main(): + gstate = [] + + n = int(options.dimension) + w = int(options.windowid) + r = options.respop + + if not options.terminal: + try: + os.mkdir(options.graphicsdirectory) + except OSError: + pass + + if options.multiplot: + g = Gnuplot.Gnuplot() + + if not options.terminal: + g('set terminal png') + g('set output \'%s/%s_%s.png\'' % (options.graphicsdirectory, options.graphicsprefixname, 'multiplot')) + + g('set parametric') + g('set nokey') + g('set noxtic') + g('set noytic') + g('set noztic') + + g('set size 1.0, 1.0') + g('set origin 0.0, 0.0') + g('set multiplot') + + g('set size 0.5, 0.5') + g('set origin 0.0, 0.5') + + if n >= 1: + plotXPointYFitness(r, state=gstate, g=g) + + g('set size 0.5, 0.5') + g('set origin 0.0, 0.0') + + if n >= 2: + plotXPointYFitness(r, '4:1', state=gstate, g=g) + + g('set size 0.5, 0.5') + g('set origin 0.5, 0.5') + + if n >= 2: + plotXYPointZFitness(r, state=gstate, g=g) + + g('set size 0.5, 0.5') + g('set origin 0.5, 0.0') + + if n >= 2: + plotXYPoint(r, state=gstate, g=g) + elif n >= 3: + plotXYZPoint(r, state=gstate, g=g) + + g('set nomultiplot') + + else: + + if n >= 1 and w in [0, 1]: + plotXPointYFitness(r, state=gstate) + + if n >= 2 and w in [0, 2]: + plotXPointYFitness(r, '4:1', state=gstate) + + if n >= 2 and w in [0, 3]: + plotXYPointZFitness(r, state=gstate) + + if n >= 3 and w in [0, 4]: + plotXYZPoint(r, state=gstate) + + if n >= 2 and w in [0, 5]: + plotXYPoint(r, state=gstate) + + # if n >= 1: + # plotParams('./ResParams.txt', state=gstate) + + # if n >= 2: + # plot2DRectFromFiles('./ResBounds', state=gstate) + # plotXYPoint(r, state=gstate) + + # g = plot2DRectFromFiles('./ResBounds', state=gstate, plot=False) + # plotXYPoint(r, g=g) + + if options.terminal: + wait(prompt='Press return to end the plot.\n') + +# when executed, just run main(): +if __name__ == '__main__': + logging.debug('### plotting started ###') + + main() + + logging.debug('### plotting ended ###') diff --git a/edo/application/eda/CMakeLists.txt b/edo/application/eda/CMakeLists.txt new file mode 100644 index 000000000..9966cb6f8 --- /dev/null +++ b/edo/application/eda/CMakeLists.txt @@ -0,0 +1,33 @@ +project(eda) + +find_package(Boost 1.33.0) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +include_directories(${Boost_INCLUDE_DIRS}) +link_directories(${Boost_LIBRARY_DIRS}) + +include_directories(${EO_SRC_DIR}/src) +include_directories(${EDO_SRC_DIR}/src) +link_directories(${EO_BIN_DIR}/${LIB}) +link_directories(${EDO_BIN_DIR}/${LIB}) + +set(RESOURCES + ${PROJECT_NAME}.param + ) + +foreach(FILE ${RESOURCES}) + execute_process( + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/${FILE} + ${EDO_BIN_DIR}/${FILE} + ) +endforeach(FILE) + +file(GLOB SOURCES *.cpp) + +set(EXECUTABLE_OUTPUT_PATH ${EDO_BIN_DIR}) + +add_executable(${PROJECT_NAME} ${SOURCES}) +target_link_libraries(${PROJECT_NAME} eo eoutils edoutils ${Boost_LIBRARIES}) + diff --git a/edo/application/eda/eda.param b/edo/application/eda/eda.param new file mode 100644 index 000000000..9aceb2306 --- /dev/null +++ b/edo/application/eda/eda.param @@ -0,0 +1,7 @@ +--rho=0 # -p : + Caner Candan +*/ + +#include +// #include + +#include + +#include +#include +#include +#include + +#include + +#include "Rosenbrock.h" +#include "Sphere.h" + + +typedef eoReal EOT; +typedef edoNormalMulti< EOT > Distrib; + + +int main(int ac, char** av) +{ + eoParser parser(ac, av); + + // Letters used by the following declarations: + // a d i p t + + std::string section("Algorithm parameters"); + + eoState state; + + // Instantiate all needed parameters for EDA algorithm + double selection_rate = parser.createParam((double)0.5, "selection_rate", "Selection Rate", 'R', section).value(); // R + + eoSelect< EOT >* selector = new eoDetSelect< EOT >( selection_rate ); + state.storeFunctor(selector); + + edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >(); + state.storeFunctor(estimator); + + eoEvalFunc< EOT >* plainEval = new Rosenbrock< EOT >(); + state.storeFunctor(plainEval); + + unsigned long max_eval = parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion").value(); // E + eoEvalFuncCounterBounder< EOT > eval(*plainEval, max_eval); + + eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); + state.storeFunctor(gen); + + unsigned int dimension_size = parser.createParam((unsigned int)10, "dimension-size", "Dimension size", 'd', section).value(); // d + + eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( dimension_size, *gen ); + state.storeFunctor(init); + + + // (1) Population init and sampler + // Generation of population from do_make_pop (creates parameters, manages persistance and so on...) + // ... and creates the parameters: L P r S + // this first sampler creates a uniform distribution independently from our distribution (it does not use edoUniform). + eoPop< EOT >& pop = do_make_pop(parser, state, *init); + + // (2) First evaluation before starting the research algorithm + apply(eval, pop); + + // Prepare bounder class to set bounds of sampling. + // This is used by edoSampler. + edoBounder< EOT >* bounder = + new edoBounderRng< EOT >( EOT(dimension_size, -5), EOT(dimension_size, 5), *gen); // FIXME do not use hard-coded bounds + state.storeFunctor(bounder); + + // Prepare sampler class with a specific distribution + edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder ); + state.storeFunctor(sampler); + + // stopping criteria + // ... and creates the parameter letters: C E g G s T + eoContinue< EOT >& eo_continue = do_make_continue(parser, state, eval); + + // population output + eoCheckPoint< EOT >& pop_continue = do_make_checkpoint(parser, state, eval, eo_continue); + + // distribution output + edoDummyContinue< Distrib >* dummy_continue = new edoDummyContinue< Distrib >(); + state.storeFunctor(dummy_continue); + + edoCheckPoint< Distrib >* distribution_continue = new edoCheckPoint< Distrib >( *dummy_continue ); + state.storeFunctor(distribution_continue); + + // eoEPRemplacement causes the using of the current and previous + // sample for sampling. + eoReplacement< EOT >* replacor = new eoEPReplacement< EOT >(pop.size()); + state.storeFunctor(replacor); + + // Help + Verbose routines + make_verbose(parser); + make_help(parser); + + // Some stuff to display helper when we are using -h option + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + // population output (after helper) + // + // FIXME: theses objects are instanciated there in order to avoid a folder + // removing as edoFileSnapshot does within ctor. + edoPopStat< EOT >* popStat = new edoPopStat; + state.storeFunctor(popStat); + pop_continue.add(*popStat); + + edoFileSnapshot* fileSnapshot = new edoFileSnapshot("EDA_ResPop"); + state.storeFunctor(fileSnapshot); + fileSnapshot->add(*popStat); + pop_continue.add(*fileSnapshot); + + // distribution output (after helper) + edoDistribStat< Distrib >* distrib_stat = new edoStatNormalMulti< EOT >(); + state.storeFunctor(distrib_stat); + + distribution_continue->add( *distrib_stat ); + + // eoMonitor* stdout_monitor = new eoStdoutMonitor(); + // state.storeFunctor(stdout_monitor); + // stdout_monitor->add(*distrib_stat); + // distribution_continue->add( *stdout_monitor ); + + eoFileMonitor* file_monitor = new eoFileMonitor("eda_distribution_bounds.txt"); + state.storeFunctor(file_monitor); + file_monitor->add(*distrib_stat); + distribution_continue->add( *file_monitor ); + + eoPopLoopEval popEval( eval ); + + // EDA algorithm configuration + edoAlgo< Distrib >* algo = new edoAlgoStateless< Distrib > + (popEval, *selector, *estimator, *sampler, *replacor, + pop_continue, *distribution_continue ); + + // Beginning of the algorithm call + try { + do_run(*algo, pop); + + } catch (eoEvalFuncCounterBounderException& e) { + eo::log << eo::warnings << "warning: " << e.what() << std::endl; + + } catch (std::exception& e) { + eo::log << eo::errors << "error: " << e.what() << std::endl; + exit(EXIT_FAILURE); + } + return 0; +} diff --git a/edo/application/eda_sa/CMakeLists.txt b/edo/application/eda_sa/CMakeLists.txt new file mode 100644 index 000000000..5cfb550fc --- /dev/null +++ b/edo/application/eda_sa/CMakeLists.txt @@ -0,0 +1,27 @@ +PROJECT(eda_sa) + +FIND_PACKAGE(Boost 1.33.0) + +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + +INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) +LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) + +SET(RESOURCES + ${PROJECT_NAME}.param + ) + +FOREACH(file ${RESOURCES}) + EXECUTE_PROCESS( + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/${file} + ${EDO_BIN_DIR}/${file} + ) +ENDFOREACH(file) + +FILE(GLOB SOURCES *.cpp) + +SET(EXECUTABLE_OUTPUT_PATH ${EDO_BIN_DIR}) + +ADD_EXECUTABLE(${PROJECT_NAME} ${SOURCES}) +TARGET_LINK_LIBRARIES(${PROJECT_NAME} edo edoutils ${EO_LIBRARIES} ${MO_LIBRARIES} ${Boost_LIBRARIES}) diff --git a/edo/application/eda_sa/eda_sa.param b/edo/application/eda_sa/eda_sa.param new file mode 100644 index 000000000..9aceb2306 --- /dev/null +++ b/edo/application/eda_sa/eda_sa.param @@ -0,0 +1,7 @@ +--rho=0 # -p : +#include + +#include + +#include +#include +#include +#include + +#include + +#include "Rosenbrock.h" +#include "Sphere.h" + + +typedef eoReal EOT; +typedef edoNormalMulti< EOT > Distrib; + + +int main(int ac, char** av) +{ + eoParser parser(ac, av); + + // Letters used by the following declarations: + // a d i p t + + std::string section("Algorithm parameters"); + + // FIXME: default value to check + double initial_temperature = parser.createParam((double)10e5, "temperature", "Initial temperature", 'i', section).value(); // i + + eoState state; + + + //----------------------------------------------------------------------------- + // Instantiate all needed parameters for EDASA algorithm + //----------------------------------------------------------------------------- + + double selection_rate = parser.createParam((double)0.5, "selection_rate", "Selection Rate", 'R', section).value(); // R + + eoSelect< EOT >* selector = new eoDetSelect< EOT >( selection_rate ); + state.storeFunctor(selector); + + edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >(); + state.storeFunctor(estimator); + + eoSelectOne< EOT >* selectone = new eoDetTournamentSelect< EOT >( 2 ); + state.storeFunctor(selectone); + + edoModifierMass< Distrib >* modifier = new edoNormalMultiCenter< EOT >(); + state.storeFunctor(modifier); + + eoEvalFunc< EOT >* plainEval = new Rosenbrock< EOT >(); + state.storeFunctor(plainEval); + + unsigned long max_eval = parser.getORcreateParam((unsigned long)0, "maxEval", "Maximum number of evaluations (0 = none)", 'E', "Stopping criterion").value(); // E + eoEvalFuncCounterBounder< EOT > eval(*plainEval, max_eval); + + eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); + state.storeFunctor(gen); + + + unsigned int dimension_size = parser.createParam((unsigned int)10, "dimension-size", "Dimension size", 'd', section).value(); // d + + eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( dimension_size, *gen ); + state.storeFunctor(init); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // (1) Population init and sampler + //----------------------------------------------------------------------------- + + // Generation of population from do_make_pop (creates parameters, manages persistance and so on...) + // ... and creates the parameters: L P r S + + // this first sampler creates a uniform distribution independently from our distribution (it does not use doUniform). + + eoPop< EOT >& pop = do_make_pop(parser, state, *init); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // (2) First evaluation before starting the research algorithm + //----------------------------------------------------------------------------- + + apply(eval, pop); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // Prepare bounder class to set bounds of sampling. + // This is used by doSampler. + //----------------------------------------------------------------------------- + + edoBounder< EOT >* bounder = new edoBounderRng< EOT >(EOT(pop[0].size(), -5), + EOT(pop[0].size(), 5), + *gen); + state.storeFunctor(bounder); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // Prepare sampler class with a specific distribution + //----------------------------------------------------------------------------- + + edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder ); + state.storeFunctor(sampler); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // Metropolis sample parameters + //----------------------------------------------------------------------------- + + unsigned int popSize = parser.getORcreateParam((unsigned int)20, "popSize", "Population Size", 'P', "Evolution Engine").value(); + + moContinuator< moDummyNeighbor >* sa_continue = new moIterContinuator< moDummyNeighbor >( popSize ); + state.storeFunctor(sa_continue); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // SA parameters + //----------------------------------------------------------------------------- + + double threshold_temperature = parser.createParam((double)0.1, "threshold", "Minimal temperature at which stop", 't', section).value(); // t + double alpha = parser.createParam((double)0.1, "alpha", "Temperature decrease rate", 'a', section).value(); // a + + moCoolingSchedule* cooling_schedule = new moSimpleCoolingSchedule(initial_temperature, alpha, 0, threshold_temperature); + state.storeFunctor(cooling_schedule); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // stopping criteria + // ... and creates the parameter letters: C E g G s T + //----------------------------------------------------------------------------- + + eoContinue< EOT >& eo_continue = do_make_continue(parser, state, eval); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // population output + //----------------------------------------------------------------------------- + + eoCheckPoint< EOT >& pop_continue = do_make_checkpoint(parser, state, eval, eo_continue); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // distribution output + //----------------------------------------------------------------------------- + + edoDummyContinue< Distrib >* dummy_continue = new edoDummyContinue< Distrib >(); + state.storeFunctor(dummy_continue); + + edoCheckPoint< Distrib >* distribution_continue = new edoCheckPoint< Distrib >( *dummy_continue ); + state.storeFunctor(distribution_continue); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // eoEPRemplacement causes the using of the current and previous + // sample for sampling. + //----------------------------------------------------------------------------- + + eoReplacement< EOT >* replacor = new eoEPReplacement< EOT >(pop.size()); + + // Below, use eoGenerationalReplacement to sample only on the current sample + + //eoReplacement< EOT >* replacor = new eoGenerationalReplacement< EOT >(); // FIXME: to define the size + + state.storeFunctor(replacor); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // Some stuff to display helper when we are using -h option + //----------------------------------------------------------------------------- + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + // Help + Verbose routines + + make_verbose(parser); + make_help(parser); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // population output (after helper) + // + // FIXME: theses objects are instanciate there in order to avoid a folder + // removing as edoFileSnapshot does within ctor. + //----------------------------------------------------------------------------- + + edoPopStat< EOT >* popStat = new edoPopStat; + state.storeFunctor(popStat); + pop_continue.add(*popStat); + + edoFileSnapshot* fileSnapshot = new edoFileSnapshot("EDASA_ResPop"); + state.storeFunctor(fileSnapshot); + fileSnapshot->add(*popStat); + pop_continue.add(*fileSnapshot); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // distribution output (after helper) + //----------------------------------------------------------------------------- + + edoDistribStat< Distrib >* distrib_stat = new edoStatNormalMulti< EOT >(); + state.storeFunctor(distrib_stat); + + distribution_continue->add( *distrib_stat ); + + // eoMonitor* stdout_monitor = new eoStdoutMonitor(); + // state.storeFunctor(stdout_monitor); + // stdout_monitor->add(*distrib_stat); + // distribution_continue->add( *stdout_monitor ); + + eoFileMonitor* file_monitor = new eoFileMonitor("eda_sa_distribution_bounds.txt"); + state.storeFunctor(file_monitor); + file_monitor->add(*distrib_stat); + distribution_continue->add( *file_monitor ); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // EDASA algorithm configuration + //----------------------------------------------------------------------------- + + edoAlgo< Distrib >* algo = new edoEDASA< Distrib > + (*selector, *estimator, *selectone, *modifier, *sampler, + pop_continue, *distribution_continue, + eval, *sa_continue, *cooling_schedule, + initial_temperature, *replacor); + + //----------------------------------------------------------------------------- + + + //----------------------------------------------------------------------------- + // Beginning of the algorithm call + //----------------------------------------------------------------------------- + + try + { + do_run(*algo, pop); + } + catch (eoEvalFuncCounterBounderException& e) + { + eo::log << eo::warnings << "warning: " << e.what() << std::endl; + } + catch (std::exception& e) + { + eo::log << eo::errors << "error: " << e.what() << std::endl; + exit(EXIT_FAILURE); + } + + //----------------------------------------------------------------------------- + + return 0; +} diff --git a/edo/build_gcc_linux_debug b/edo/build_gcc_linux_debug new file mode 100755 index 000000000..ea754f9bd --- /dev/null +++ b/edo/build_gcc_linux_debug @@ -0,0 +1,7 @@ +#!/usr/bin/env sh + +mkdir -p debug +cd debug +cmake -DCMAKE_BUILD_TYPE=Debug -DWITH_EIGEN=1 .. +make +cd .. diff --git a/edo/build_gcc_linux_eigen_debug b/edo/build_gcc_linux_eigen_debug new file mode 100755 index 000000000..ea754f9bd --- /dev/null +++ b/edo/build_gcc_linux_eigen_debug @@ -0,0 +1,7 @@ +#!/usr/bin/env sh + +mkdir -p debug +cd debug +cmake -DCMAKE_BUILD_TYPE=Debug -DWITH_EIGEN=1 .. +make +cd .. diff --git a/edo/build_gcc_linux_release b/edo/build_gcc_linux_release new file mode 100755 index 000000000..a1a0f53b9 --- /dev/null +++ b/edo/build_gcc_linux_release @@ -0,0 +1,9 @@ +#!/usr/bin/env sh + +mkdir -p release +cd release +cmake -DWITH_EIGEN=1 .. +#cmake -DWITH_BOOST=1 .. + +make +cd .. diff --git a/edo/cmake/modules/FindEO.cmake b/edo/cmake/modules/FindEO.cmake new file mode 100644 index 000000000..8bf3ac130 --- /dev/null +++ b/edo/cmake/modules/FindEO.cmake @@ -0,0 +1,100 @@ +# File: FindEO.cmake +# CMAKE commands to actually use the EO library +# Version: 0.0.1 +# +# The following variables are filled out: +# - EO_INCLUDE_DIRS +# - EO_LIBRARY_DIRS +# - EO_LIBRARIES +# - EO_FOUND +# +# Here are the components: +# - PyEO +# - es +# - ga +# - cma +# +# You can use FIND_PACKAGE( EO COMPONENTS ... ) to enable one or several components. +# + +# Default enabled components +SET(EO_LIBRARIES_TO_FIND eo eoutils) + +# Use FIND_PACKAGE( EO COMPONENTS ... ) to enable modules +IF(EO_FIND_COMPONENTS) + FOREACH(component ${EO_FIND_COMPONENTS}) + STRING(TOUPPER ${component} _COMPONENT) + SET(EO_USE_${_COMPONENT} 1) + ENDFOREACH(component) + + # To make sure we don't use PyEO, ES, GA, CMA when not in COMPONENTS + IF(NOT EO_USE_PYEO) + SET(EO_DONT_USE_PYEO 1) + ELSE(NOT EO_USE_PYEO) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} PyEO) + ENDIF(NOT EO_USE_PYEO) + + IF(NOT EO_USE_ES) + SET(EO_DONT_USE_ES 1) + ELSE(NOT EO_USE_ES) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} es) + ENDIF(NOT EO_USE_ES) + + IF(NOT EO_USE_GA) + SET(EO_DONT_USE_GA 1) + ELSE(NOT EO_USE_GA) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} ga) + ENDIF(NOT EO_USE_GA) + + IF(NOT EO_USE_CMA) + SET(EO_DONT_USE_CMA 1) + ELSE(NOT EO_USE_CMA) + SET(EO_LIBRARIES_TO_FIND ${EO_LIBRARIES_TO_FIND} cma) + ENDIF(NOT EO_USE_CMA) +ENDIF(EO_FIND_COMPONENTS) + +IF(NOT EO_INCLUDE_DIRS) + FIND_PATH( + EO_INCLUDE_DIRS + EO.h + PATHS + /usr/include/eo + /usr/local/include/eo + ) +ENDIF(NOT EO_INCLUDE_DIRS) + +IF(NOT EO_LIBRARY_DIRS) + FIND_PATH( + EO_LIBRARY_DIRS + libeo.a + PATHS + /usr/lib + /usr/local/lib + ) +ENDIF(NOT EO_LIBRARY_DIRS) + +IF(NOT EO_LIBRARIES) + SET(EO_LIBRARIES) + FOREACH(component ${EO_LIBRARIES_TO_FIND}) + FIND_LIBRARY( + EO_${component}_LIBRARY + NAMES ${component} + PATHS + /usr/lib + /usr/local/lib + ) + IF(EO_${component}_LIBRARY) + SET(EO_LIBRARIES ${EO_LIBRARIES} ${EO_${component}_LIBRARY}) + ELSE(EO_${component}_LIBRARY) + MESSAGE(FATAL_ERROR "${component} component not found.") + ENDIF(EO_${component}_LIBRARY) + ENDFOREACH(component) +ENDIF(NOT EO_LIBRARIES) + +IF(EO_INCLUDE_DIRS AND EO_LIBRARY_DIRS AND EO_LIBRARIES) + SET(EO_FOUND 1) + MARK_AS_ADVANCED(EO_FOUND) + MARK_AS_ADVANCED(EO_INCLUDE_DIRS) + MARK_AS_ADVANCED(EO_LIBRARY_DIRS) + MARK_AS_ADVANCED(EO_LIBRARIES) +ENDIF(EO_INCLUDE_DIRS AND EO_LIBRARY_DIRS AND EO_LIBRARIES) diff --git a/edo/distclean b/edo/distclean new file mode 100755 index 000000000..e4a02bc44 --- /dev/null +++ b/edo/distclean @@ -0,0 +1,4 @@ +#!/usr/bin/env sh + +rm -rf debug +rm -rf release diff --git a/edo/doc/CMakeLists.txt b/edo/doc/CMakeLists.txt new file mode 100644 index 000000000..317ea767b --- /dev/null +++ b/edo/doc/CMakeLists.txt @@ -0,0 +1,40 @@ +###################################################################################### +### 0) Documentation +###################################################################################### + + +if(DOXYGEN_FOUND) + # Directory where the generation will be launched + set(EDO_DOC_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL "Documentation directory" FORCE) + # Name of the doxygene configuration file + set(EDO_DOC_CONFIG_FILE "edo.doxyfile" CACHE INTERNAL "Documentation configuration file") + if(DOXYGEN_EXECUTABLE) + # Creating the custom target + if(UNIX AND NOT ${CMAKE_VERBOSE_MAKEFILE}) + add_custom_target(doc-edo + COMMAND ${DOXYGEN_EXECUTABLE} ${EDO_DOC_CONFIG_FILE} 2> /dev/null > /dev/null + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + else(UNIX AND NOT ${CMAKE_VERBOSE_MAKEFILE}) + add_custom_target(doc-edo + COMMAND ${DOXYGEN_EXECUTABLE} ${EDO_DOC_CONFIG_FILE} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + endif(UNIX AND NOT ${CMAKE_VERBOSE_MAKEFILE}) + endif(DOXYGEN_EXECUTABLE) + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${EDO_DOC_CONFIG_FILE}.cmake" + "${EDO_DOC_DIR}/${EDO_DOC_CONFIG_FILE}") + install( + DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + DESTINATION local/share${INSTALL_SUB_DIR}/edo COMPONENT doc + PATTERN "CMakeFiles" EXCLUDE + PATTERN "cmake_install.cmake" EXCLUDE + PATTERN "CTestTestfile.cmake" EXCLUDE + PATTERN "Makefile" EXCLUDE + PATTERN "edo.cfg" EXCLUDE + PATTERN "edo.doxytag" EXCLUDE + ) +else(DOXYGEN_FOUND) + message(STATUS "Unable to generate the documentation, Doxygen package not found") +endif(DOXYGEN_FOUND) + diff --git a/edo/doc/edo.doxyfile.cmake b/edo/doc/edo.doxyfile.cmake new file mode 100644 index 000000000..fd5657261 --- /dev/null +++ b/edo/doc/edo.doxyfile.cmake @@ -0,0 +1,1564 @@ +# Doxyfile 1.6.3 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = @PACKAGE_NAME@ + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @PACKAGE_VERSION@ + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = @CMAKE_BINARY_DIR@/doc + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = @CMAKE_SOURCE_DIR@ + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = YES + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = YES + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = NO + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = NO + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = @CMAKE_SOURCE_DIR@ + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = *.cpp \ + *.h \ + NEWS \ + README + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = @CMAKE_BINARY_DIR@ + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 3 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = edo + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = YES + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index +# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup +# and does not have live searching capabilities. + +SERVER_BASED_SEARCH = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = YES + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = WITH_EIGEN + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/edo/doc/edo_design.svg b/edo/doc/edo_design.svg new file mode 100644 index 000000000..07bfecb38 --- /dev/null +++ b/edo/doc/edo_design.svg @@ -0,0 +1,2689 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Evaluation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Selection + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Stop. criteria? + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Replacement + + Best solution + Parents + Genitors + Offsprings + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Initialization + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Estimator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Sampler + + + Distrib + + + diff --git a/edo/doc/edo_distrib.svg b/edo/doc/edo_distrib.svg new file mode 100644 index 000000000..24b9a21f8 --- /dev/null +++ b/edo/doc/edo_distrib.svg @@ -0,0 +1,2885 @@ + + + + + EDO distribution coupling + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + EDO distribution coupling + + + Johann Dreo + + + 2012-07-19 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Modifier + + + + + + + population + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Estimator + + + + + + + + Distrib + + population + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Sampler + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Repairer + + + diff --git a/edo/doc/index.h b/edo/doc/index.h new file mode 100644 index 000000000..76fc8a71c --- /dev/null +++ b/edo/doc/index.h @@ -0,0 +1,39 @@ +/** @mainpage Welcome to Evolving Distribution Objects + +@section shortcuts In one word + +%EDO is an extension of %EO oriented toward Estimation-of-Distribution-like +Algorithms. + +You can search for advanced features by browsing the modules page. + +@section intro Introduction + +%EDO is an extension of %EO, that facilitate the design and implementation of +stochastic search metaheuristics. It is based on the assumption that those +algorithms are updating a probability distribution, that is used to generate +a sample (a population, in %EO) of solutions (individuals, in %EO). + +Basically, EDO decompose the variation operators of %EO in a set of +sub-operators that are binded by a distribution. Thus, most of the +representation-independent operators of %EO can be used in %EDO algorithms. + +Apart from choosing which distribution he want to use as a model, the user is +not supposed to directly manipulate it. Using the same approach than within %EO, +the user has just to indicate what he want to use, without having to bother how +he want to use it. + +On the designer side, it is still possible to implement specific operators +without having to change other ones. + + + +The two main operators are the Estimators, that builds a given +distribution according to a population and the Samplers that builds a +population according to a distribution. There is also Modifiers that +are here to change arbitrarily the parameters of a distribution, if necessary. + + + +*/ diff --git a/edo/edo.pc b/edo/edo.pc new file mode 100644 index 000000000..a70434383 --- /dev/null +++ b/edo/edo.pc @@ -0,0 +1,12 @@ +# Package Information for pkg-config + +prefix=/usr +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include/edo + +Name: Evolving Distribution Objects +Description: Evolving Distribution Objects +Version: 1.0 +Libs: -L${libdir} -ledo -ledoutils +Cflags: -I${includedir} diff --git a/edo/install.cmake-dist b/edo/install.cmake-dist new file mode 100644 index 000000000..35cc06172 --- /dev/null +++ b/edo/install.cmake-dist @@ -0,0 +1,10 @@ +# Variables to set + +# directory we need to build project +SET(EO_DIR "<>" CACHE PATH "EO 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) # do not use quotes around this list or it will fail diff --git a/edo/package_deb b/edo/package_deb new file mode 100755 index 000000000..1a44d0219 --- /dev/null +++ b/edo/package_deb @@ -0,0 +1,5 @@ +#!/usr/bin/env sh + +cd release +cpack -G DEB +cd .. diff --git a/edo/package_rpm b/edo/package_rpm new file mode 100755 index 000000000..8d46b7d04 --- /dev/null +++ b/edo/package_rpm @@ -0,0 +1,5 @@ +#!/usr/bin/env sh + +cd release +cpack -G RPM +cd .. diff --git a/edo/src/CMakeLists.txt b/edo/src/CMakeLists.txt new file mode 100644 index 000000000..d8dbf1abb --- /dev/null +++ b/edo/src/CMakeLists.txt @@ -0,0 +1,37 @@ +###################################################################################### +### 1) Set all needed source files for the project +###################################################################################### + +include_directories(${EO_SRC_DIR}) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +set(EDO_LIB_OUTPUT_PATH ${EDO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${EDO_LIB_OUTPUT_PATH}) + + +###################################################################################### +### 3) Look for headers +###################################################################################### + +file(GLOB HDRS edo) +install(FILES ${HDRS} DESTINATION local/include${INSTALL_SUB_DIR}/edo COMPONENT headers) + + +###################################################################################### +### 4) Install directories +###################################################################################### + +install(DIRECTORY utils + DESTINATION local/include${INSTALL_SUB_DIR}/edo + COMPONENT headers + FILES_MATCHING PATTERN "*.h" + ) + + +###################################################################################### +### 2) Where must cmake go now ? +###################################################################################### + +ADD_SUBDIRECTORY(utils) + +###################################################################################### diff --git a/edo/src/TODO b/edo/src/TODO new file mode 100644 index 000000000..e69de29bb diff --git a/edo/src/edo b/edo/src/edo new file mode 100644 index 000000000..0da9ed9d4 --- /dev/null +++ b/edo/src/edo @@ -0,0 +1,89 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edo_ +#define _edo_ + +#include "edoAlgo.h" +//#include "edoEDASA.h" +#include "edoAlgoAdaptive.h" +#include "edoAlgoStateless.h" + +#include "edoDistrib.h" +#include "edoUniform.h" +#include "edoNormalMono.h" +#include "edoNormalMulti.h" +#include "edoNormalAdaptive.h" + +#include "edoEstimator.h" +#include "edoEstimatorUniform.h" +#include "edoEstimatorNormalMono.h" +#include "edoEstimatorNormalMulti.h" +#include "edoEstimatorAdaptive.h" +#include "edoEstimatorNormalAdaptive.h" + +#include "edoModifier.h" +#include "edoModifierDispersion.h" +#include "edoModifierMass.h" +#include "edoUniformCenter.h" +#include "edoNormalMonoCenter.h" +#include "edoNormalMultiCenter.h" + +#include "edoSampler.h" +#include "edoSamplerUniform.h" +#include "edoSamplerNormalMono.h" +#include "edoSamplerNormalMulti.h" +#include "edoSamplerNormalAdaptive.h" + +#include "edoVectorBounds.h" + +#include "edoRepairer.h" +#include "edoRepairerDispatcher.h" +#include "edoRepairerRound.h" +#include "edoRepairerModulo.h" +#include "edoBounder.h" +#include "edoBounderNo.h" +#include "edoBounderBound.h" +#include "edoBounderRng.h" +#include "edoBounderUniform.h" + +#include "edoContinue.h" +#include "utils/edoCheckPoint.h" + +#include "utils/edoStat.h" +#include "utils/edoStatUniform.h" +#include "utils/edoStatNormalMono.h" +#include "utils/edoStatNormalMulti.h" + +#include "utils/edoFileSnapshot.h" +#include "utils/edoPopStat.h" + +#endif // !_edo_ + +// Local Variables: +// mode: C++ +// End: diff --git a/edo/src/edoAlgo.h b/edo/src/edoAlgo.h new file mode 100644 index 000000000..b420f3074 --- /dev/null +++ b/edo/src/edoAlgo.h @@ -0,0 +1,64 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + + +#ifndef _edoAlgo_h +#define _edoAlgo_h + +#include + +/** + @defgroup Algorithms Algorithms + + In EDO, as in EO, an algorithm is a functor that takes one or several + solutions to an optimization problem as arguments, and iteratively modify + them with the help of operators.It differs from a canonical EO algorithm + because it is templatized on a edoDistrib rather than just an EOT. + + @see eoAlgo +*/ + +/** An EDO algorithm differs from a canonical EO algorithm because it is + * templatized on a Distribution rather than just an EOT. + * + * Derivating from an eoAlgo, it should define an operator()( EOT sol ) + * + * @ingroup Algorithms + */ +template < typename D > +class edoAlgo : public eoAlgo< typename D::EOType > +{ + //! Alias for the type + typedef typename D::EOType EOType; + + // virtual R operator()(A1) = 0; (defined in eoUF) + +public: + virtual ~edoAlgo(){} +}; + +#endif // !_edoAlgo_h diff --git a/edo/src/edoAlgoAdaptive.h b/edo/src/edoAlgoAdaptive.h new file mode 100644 index 000000000..5ee0f359a --- /dev/null +++ b/edo/src/edoAlgoAdaptive.h @@ -0,0 +1,213 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoAlgoAdaptive_h +#define _edoAlgoAdaptive_h + +#include + +#include + +#include "edoAlgo.h" +#include "edoEstimator.h" +#include "edoModifierMass.h" +#include "edoSampler.h" +#include "edoContinue.h" + +/** A generic stochastic search template for algorithms that need a distribution parameter. + * + * An adaptive algorithm will directly updates a distribution, it must thus be instanciated + * with an edoDistrib at hand. Thus, this distribution object should be instanciated appart. + * The reference to this distribution is generally also needed by at least one of the + * algorithm's operator, generally for algorithms that shares the same algorithms across + * operators and/or iterations. + * + * If you no operator needs to update the distribution, then it is simpler to use an + * edoAlgoStateless . + * + * @ingroup Algorithms + */ +template < typename D > +class edoAlgoAdaptive : public edoAlgo< D > +{ +public: + //! Alias for the type EOT + typedef typename D::EOType EOType; + + //! Alias for the atom type + typedef typename EOType::AtomType AtomType; + + //! Alias for the fitness + typedef typename EOType::Fitness Fitness; + +public: + + /*! + Takes algo operators, all are mandatory + + \param distrib A distribution to use, if you want to update this parameter (e.gMA-ES) instead of replacing it (e.g. an EDA) + \param evaluator Evaluate a population + \param selector Selection of the best candidate solutions in the population + \param estimator Estimation of the distribution parameters + \param sampler Generate feasible solutions using the distribution + \param replacor Replace old solutions by new ones + \param pop_continuator Stopping criterion based on the population features + \param distribution_continuator Stopping criterion based on the distribution features + */ + edoAlgoAdaptive( + D & distrib, + eoPopEvalFunc < EOType > & evaluator, + eoSelect< EOType > & selector, + edoEstimator< D > & estimator, + edoSampler< D > & sampler, + eoReplacement< EOType > & replacor, + eoContinue< EOType > & pop_continuator, + edoContinue< D > & distribution_continuator + ) : + _distrib(distrib), + _evaluator(evaluator), + _selector(selector), + _estimator(estimator), + _sampler(sampler), + _replacor(replacor), + _pop_continuator(pop_continuator), + _dummy_continue(), + _distribution_continuator(distribution_continuator) + {} + + + //! constructor without an edoContinue + /*! + Takes algo operators, all are mandatory + + \param distrib A distribution to use, if you want to update this parameter (e.gMA-ES) instead of replacing it (e.g. an EDA) + \param evaluator Evaluate a population + \param selector Selection of the best candidate solutions in the population + \param estimator Estimation of the distribution parameters + \param sampler Generate feasible solutions using the distribution + \param replacor Replace old solutions by new ones + \param pop_continuator Stopping criterion based on the population features + */ + edoAlgoAdaptive ( + D & distrib, + eoPopEvalFunc < EOType > & evaluator, + eoSelect< EOType > & selector, + edoEstimator< D > & estimator, + edoSampler< D > & sampler, + eoReplacement< EOType > & replacor, + eoContinue< EOType > & pop_continuator + ) : + _distrib( distrib ), + _evaluator(evaluator), + _selector(selector), + _estimator(estimator), + _sampler(sampler), + _replacor(replacor), + _pop_continuator(pop_continuator), + _dummy_continue(), + _distribution_continuator( _dummy_continue ) + {} + + /** Call the algorithm + * + * \param pop the population of candidate solutions + * \return void + */ + void operator ()(eoPop< EOType > & pop) + { + assert(pop.size() > 0); + + eoPop< EOType > current_pop; + eoPop< EOType > selected_pop; + + // update the extern distribution passed to the estimator (cf. CMA-ES) + // OR replace the dummy distribution for estimators that do not need extern distributions (cf. EDA) + _distrib = _estimator(pop); + + // Evaluating a first time the candidate solutions + // The first pop is not supposed to be evaluated (@see eoPopLoopEval). + // _evaluator( current_pop, pop ); + + do { + // (1) Selection of the best points in the population + _selector(pop, selected_pop); + assert( selected_pop.size() > 0 ); + + // (2) Estimation of the distribution parameters + _distrib = _estimator(selected_pop); + + // (3) sampling + // The sampler produces feasible solutions (@see edoSampler that + // encapsulate an edoBounder) + current_pop.clear(); + for( unsigned int i = 0; i < pop.size(); ++i ) { + current_pop.push_back( _sampler(_distrib) ); + } + + // (4) Evaluate new solutions + _evaluator( pop, current_pop ); + + // (5) Replace old solutions by new ones + _replacor(pop, current_pop); // e.g. copy current_pop in pop + + } while( _distribution_continuator( _distrib ) && _pop_continuator( pop ) ); + } // operator() + + +protected: + + //! The distribution that you want to update + D & _distrib; + + //! A full evaluation function. + eoPopEvalFunc & _evaluator; + + //! A EOType selector + eoSelect & _selector; + + //! A EOType estimator. It is going to estimate distribution parameters. + edoEstimator & _estimator; + + //! A D sampler + edoSampler & _sampler; + + //! A EOType replacor + eoReplacement & _replacor; + + //! A EOType population continuator + eoContinue & _pop_continuator; + + //! A D continuator that always return true + edoDummyContinue _dummy_continue; + + //! A D continuator + edoContinue & _distribution_continuator; + +}; + +#endif // !_edoAlgoAdaptive_h + diff --git a/edo/src/edoAlgoStateless.h b/edo/src/edoAlgoStateless.h new file mode 100644 index 000000000..a325ff24a --- /dev/null +++ b/edo/src/edoAlgoStateless.h @@ -0,0 +1,105 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoAlgoStateless_h +#define _edoAlgoStateless_h + +#include "edoAlgoAdaptive.h" + +/** A generic stochastic search template for algorithms that need a distribution parameter but replace it rather than update it + * + * This use a default dummy distribution, for algorithms willing to replace it instead of updating + * Thus we can instanciate _distrib on this and replace it at the first iteration with an estimator. + * This is why an edoDistrib must have an empty constructor. + * + * @ingroup Algorithms + */ +template < typename D > +class edoAlgoStateless : public edoAlgoAdaptive< D > +{ +public: + //! Alias for the type EOT + typedef typename D::EOType EOType; + + //! Alias for the atom type + typedef typename EOType::AtomType AtomType; + + //! Alias for the fitness + typedef typename EOType::Fitness Fitness; + +public: + + /** Full constructor + \param evaluator Evaluate a population + \param selector Selection of the best candidate solutions in the population + \param estimator Estimation of the distribution parameters + \param sampler Generate feasible solutions using the distribution + \param replacor Replace old solutions by new ones + \param pop_continuator Stopping criterion based on the population features + \param distribution_continuator Stopping criterion based on the distribution features + */ + edoAlgoStateless( + eoPopEvalFunc < EOType > & evaluator, + eoSelect< EOType > & selector, + edoEstimator< D > & estimator, + edoSampler< D > & sampler, + eoReplacement< EOType > & replacor, + eoContinue< EOType > & pop_continuator, + edoContinue< D > & distribution_continuator + ) : + edoAlgoAdaptive( *(new D), evaluator, selector, estimator, sampler, replacor, pop_continuator, distribution_continuator) + {} + + /** Constructor without an edoContinue + + \param evaluator Evaluate a population + \param selector Selection of the best candidate solutions in the population + \param estimator Estimation of the distribution parameters + \param sampler Generate feasible solutions using the distribution + \param replacor Replace old solutions by new ones + \param pop_continuator Stopping criterion based on the population features + */ + edoAlgoStateless ( + eoPopEvalFunc < EOType > & evaluator, + eoSelect< EOType > & selector, + edoEstimator< D > & estimator, + edoSampler< D > & sampler, + eoReplacement< EOType > & replacor, + eoContinue< EOType > & pop_continuator + ) : + edoAlgoAdaptive( *(new D), evaluator, selector, estimator, sampler, replacor, pop_continuator) + {} + + ~edoAlgoStateless() + { + // delete the temporary distrib allocated in constructors + delete &(this->_distrib); + } +}; + +#endif // !_edoAlgoStateless_h + diff --git a/edo/src/edoBounder.h b/edo/src/edoBounder.h new file mode 100644 index 000000000..19b90b6be --- /dev/null +++ b/edo/src/edoBounder.h @@ -0,0 +1,64 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoBounder_h +#define _edoBounder_h + +#include + +/** The interface of a set of classes that modifies a solution so as to respect + * a given set of bounds (typically an hypercube). + * + * @ingroup Repairers + * @ingroup Core + */ +template < typename EOT > +class edoBounder : public edoRepairer< EOT > +{ +public: + edoBounder() + {} + + + edoBounder( EOT min/* = EOT(1, 0)*/, EOT max/* = EOT(1, 1)*/ ) + : _min(min), _max(max) + { + assert(_min.size() > 0); + assert(_min.size() == _max.size()); + } + + // virtual void operator()( EOT& ) = 0 (provided by eoUF< A1, R >) + + EOT& min(){return _min;} + EOT& max(){return _max;} + +private: + EOT _min; + EOT _max; +}; + +#endif // !_edoBounder_h diff --git a/edo/src/edoBounderBound.h b/edo/src/edoBounderBound.h new file mode 100644 index 000000000..36ad53144 --- /dev/null +++ b/edo/src/edoBounderBound.h @@ -0,0 +1,66 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoBounderBound_h +#define _edoBounderBound_h + +#include "edoBounder.h" + +/** A bounder that correct an incorrect variable by setting it to the min/max + * + * @ingroup Repairers + */ +template < typename EOT > +class edoBounderBound : public edoBounder< EOT > +{ +public: + edoBounderBound( EOT min, EOT max ) + : edoBounder< EOT >( min, max ) + {} + + void operator()( EOT& x ) + { + unsigned int size = x.size(); + assert(size > 0); + + for (unsigned int d = 0; d < size; ++d) // browse all dimensions + { + if (x[d] < this->min()[d]) + { + x[d] = this->min()[d]; + continue; + } + + if (x[d] > this->max()[d]) + { + x[d] = this->max()[d]; + } + } + } +}; + +#endif // !_edoBounderBound_h diff --git a/edo/src/edoBounderNo.h b/edo/src/edoBounderNo.h new file mode 100644 index 000000000..33416d56d --- /dev/null +++ b/edo/src/edoBounderNo.h @@ -0,0 +1,44 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoBounderNo_h +#define _edoBounderNo_h + +#include "edoBounder.h" + +/** A bounder that does nothing. + * + * @ingroup Repairers + */ +template < typename EOT > +class edoBounderNo : public edoBounder< EOT > +{ +public: + void operator()( EOT& ) {} +}; + +#endif // !_edoBounderNo_h diff --git a/edo/src/edoBounderRng.h b/edo/src/edoBounderRng.h new file mode 100644 index 000000000..bfe6cb712 --- /dev/null +++ b/edo/src/edoBounderRng.h @@ -0,0 +1,67 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoBounderRng_h +#define _edoBounderRng_h + +#include "edoBounder.h" + +/** A bounder that randomly draw new values for variables going out bounds, + * using an eoRng to do so. + * + * @ingroup Repairers + */ +template < typename EOT > +class edoBounderRng : public edoBounder< EOT > +{ +public: + edoBounderRng( EOT min, EOT max, eoRndGenerator< double > & rng ) + : edoBounder< EOT >( min, max ), _rng(rng) + {} + + void operator()( EOT& x ) + { + unsigned int size = x.size(); + assert(size > 0); + + for (unsigned int d = 0; d < size; ++d) // browse all dimensions + { + + // FIXME: attention: les bornes RNG ont les memes bornes quelque soit les dimensions idealement on voudrait avoir des bornes differentes pour chaque dimensions. + + if (x[d] < this->min()[d] || x[d] > this->max()[d]) + { + x[d] = _rng(); + } + } + } + +private: + eoRndGenerator< double> & _rng; +}; + +#endif // !_edoBounderRng_h diff --git a/edo/src/edoBounderUniform.h b/edo/src/edoBounderUniform.h new file mode 100644 index 000000000..f5ea97c7d --- /dev/null +++ b/edo/src/edoBounderUniform.h @@ -0,0 +1,70 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo +*/ + +#ifndef _edoBounderUniform_h +#define _edoBounderUniform_h + +#include "edoBounder.h" + +/** A bounder that randomly draw new values for variables going out bounds, + * in a given uniform distribution. + * + * @ingroup Repairers + */ +template < typename EOT > +class edoBounderUniform : public edoBounder< EOT > +{ +public: + edoBounderUniform( EOT min, EOT max ) + : edoBounder< EOT >( min, max ) + { + } + + void operator()( EOT& sol ) + { + assert( this->min().size() > 0 ); + assert( this->max().size() > 0 ); + + assert( sol.size() > 0); + assert( sol.size() == this->min().size() ); + + eo::log << eo::debug << "BounderUniform: from sol = " << sol; + eo::log.flush(); + + unsigned int size = sol.size(); + 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 + + eo::log << eo::debug << "\tto sol = " << sol << std::endl; + } +}; + +#endif // !_edoBounderUniform_h diff --git a/edo/src/edoContinue.h b/edo/src/edoContinue.h new file mode 100644 index 000000000..8089601e2 --- /dev/null +++ b/edo/src/edoContinue.h @@ -0,0 +1,66 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _doContinue_h +#define _doContinue_h + +#include +#include + +/** A continuator that check the state of an edoDistrib + * + * @see eoContinue + * + * @ingroup Continuators + * @ingroup Core + */ +template < typename D > +class edoContinue : public eoUF< const D&, bool >, public eoPersistent +{ +public: + virtual std::string className(void) const { return "edoContinue"; } + + void readFrom(std::istream&) + { + /* It should be implemented by subclasses ! */ + } + + void printOn(std::ostream&) const + { + /* It should be implemented by subclasses ! */ + } +}; + +template < typename D > +class edoDummyContinue : public edoContinue< D > +{ + bool operator()(const D&){ return true; } + + virtual std::string className() const { return "edoDummyContinue"; } +}; + +#endif // !_edoContinue_h diff --git a/edo/src/edoDistrib.h b/edo/src/edoDistrib.h new file mode 100644 index 000000000..57cb45b3c --- /dev/null +++ b/edo/src/edoDistrib.h @@ -0,0 +1,61 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoDistrib_h +#define _edoDistrib_h + +#include + +/** @defgroup Core + * + * Core functors that made the basis of EDO. + */ + +/** @defgroup Distributions Distributions + * + * A distribution is a data structure that holds sufficient informations to + * describe a probability density function by a set of parameters. + * + * It is passed across EDO operators and can be updated or manipulated by them. + */ + +/** Base class for distributions. This is really just an empty shell. + * + * @ingroup Distributions + * @ingroup Core + */ +template < typename EOT > +class edoDistrib : public eoFunctorBase +{ +public: + //! Alias for the type + typedef EOT EOType; + + virtual ~edoDistrib(){} +}; + +#endif // !_edoDistrib_h diff --git a/edo/src/edoEDASA.h b/edo/src/edoEDASA.h new file mode 100644 index 000000000..1966d54db --- /dev/null +++ b/edo/src/edoEDASA.h @@ -0,0 +1,272 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoEDASA_h +#define _edoEDASA_h + +#include +//#include + +#include + +#include "edoAlgo.h" +#include "edoEstimator.h" +#include "edoModifierMass.h" +#include "edoSampler.h" +#include "edoContinue.h" + +//! edoEDASA< D > + +template < typename D > +class edoEDASA : public edoAlgo< D > +{ +public: + //! Alias for the type EOT + typedef typename D::EOType EOType; + + //! Alias for the atom type + typedef typename EOType::AtomType AtomType; + + //! Alias for the fitness + typedef typename EOType::Fitness Fitness; + +public: + + //! edoEDASA constructor + /*! + All the boxes used by a EDASA need to be given. + + \param selector Population Selector + \param estimator Distribution Estimator + \param selectone SelectOne + \param modifier Distribution Modifier + \param sampler Distribution Sampler + \param pop_continue Population Continuator + \param distribution_continue Distribution Continuator + \param evaluation Evaluation function. + \param sa_continue Stopping criterion. + \param cooling_schedule Cooling schedule, describes how the temperature is modified. + \param initial_temperature The initial temperature. + \param replacor Population replacor + */ + edoEDASA (eoSelect< EOType > & selector, + edoEstimator< D > & estimator, + eoSelectOne< EOType > & selectone, + edoModifierMass< D > & modifier, + edoSampler< D > & sampler, + eoContinue< EOType > & pop_continue, + edoContinue< D > & distribution_continue, + eoEvalFunc < EOType > & evaluation, + moContinuator< moDummyNeighbor > & sa_continue, + moCoolingSchedule & cooling_schedule, + double initial_temperature, + eoReplacement< EOType > & replacor + ) + : _selector(selector), + _estimator(estimator), + _selectone(selectone), + _modifier(modifier), + _sampler(sampler), + _pop_continue(pop_continue), + _distribution_continue(distribution_continue), + _evaluation(evaluation), + _sa_continue(sa_continue), + _cooling_schedule(cooling_schedule), + _initial_temperature(initial_temperature), + _replacor(replacor) + + {} + + //! function that launches the EDASA algorithm. + /*! + As a moTS or a moHC, the EDASA can be used for HYBRIDATION in an evolutionary algorithm. + + \param pop A population to improve. + \return TRUE. + */ + void operator ()(eoPop< EOType > & pop) + { + assert(pop.size() > 0); + + double temperature = _initial_temperature; + + eoPop< EOType > current_pop; + + eoPop< EOType > selected_pop; + + + //------------------------------------------------------------- + // Estimating a first time the distribution parameter thanks + // to population. + //------------------------------------------------------------- + + D distrib = _estimator(pop); + + double size = distrib.size(); + assert(size > 0); + + //------------------------------------------------------------- + + + do + { + //------------------------------------------------------------- + // (3) Selection of the best points in the population + //------------------------------------------------------------- + + selected_pop.clear(); + + _selector(pop, selected_pop); + + assert( selected_pop.size() > 0 ); + + //------------------------------------------------------------- + + + //------------------------------------------------------------- + // (4) Estimation of the distribution parameters + //------------------------------------------------------------- + + distrib = _estimator(selected_pop); + + //------------------------------------------------------------- + + + // TODO: utiliser selected_pop ou pop ??? + + assert(selected_pop.size() > 0); + + + //------------------------------------------------------------- + // Init of a variable contening a point with the bestest fitnesses + //------------------------------------------------------------- + + EOType current_solution = _selectone(selected_pop); + + //------------------------------------------------------------- + + + //------------------------------------------------------------- + // Fit the current solution with the distribution parameters (bounds) + //------------------------------------------------------------- + + // FIXME: si besoin de modifier la dispersion de la distribution + // _modifier_dispersion(distribution, selected_pop); + _modifier(distrib, current_solution); + + //------------------------------------------------------------- + + + //------------------------------------------------------------- + // Evaluating a first time the current solution + //------------------------------------------------------------- + + _evaluation( current_solution ); + + //------------------------------------------------------------- + + + //------------------------------------------------------------- + // Building of the sampler in current_pop + //------------------------------------------------------------- + + _sa_continue.init( current_solution ); + + current_pop.clear(); + + do + { + EOType candidate_solution = _sampler(distrib); + _evaluation( candidate_solution ); + + // TODO: verifier le critere d'acceptation + if ( candidate_solution.fitness() < current_solution.fitness() || + rng.uniform() < exp( ::fabs(candidate_solution.fitness() - current_solution.fitness()) / temperature ) ) + { + current_pop.push_back(candidate_solution); + current_solution = candidate_solution; + } + } + while ( _sa_continue( current_solution ) ); + + //------------------------------------------------------------- + + + _replacor(pop, current_pop); // copy current_pop in pop + + pop.sort(); + + if ( ! _cooling_schedule( temperature ) ){ eo::log << eo::debug << "_cooling_schedule" << std::endl; break; } + + if ( ! _distribution_continue( distrib ) ){ eo::log << eo::debug << "_distribution_continue" << std::endl; break; } + + if ( ! _pop_continue( pop ) ){ eo::log << eo::debug << "_pop_continue" << std::endl; break; } + + } + while ( 1 ); + } + +private: + + //! A EOType selector + eoSelect < EOType > & _selector; + + //! A EOType estimator. It is going to estimate distribution parameters. + edoEstimator< D > & _estimator; + + //! SelectOne + eoSelectOne< EOType > & _selectone; + + //! A D modifier + edoModifierMass< D > & _modifier; + + //! A D sampler + edoSampler< D > & _sampler; + + //! A EOType population continuator + eoContinue < EOType > & _pop_continue; + + //! A D continuator + edoContinue < D > & _distribution_continue; + + //! A full evaluation function. + eoEvalFunc < EOType > & _evaluation; + + //! Stopping criterion before temperature update + moContinuator< moDummyNeighbor > & _sa_continue; + + //! The cooling schedule + moCoolingSchedule & _cooling_schedule; + + //! Initial temperature + double _initial_temperature; + + //! A EOType replacor + eoReplacement < EOType > & _replacor; +}; + +#endif // !_edoEDASA_h diff --git a/edo/src/edoEstimator.h b/edo/src/edoEstimator.h new file mode 100644 index 000000000..7c9df6f24 --- /dev/null +++ b/edo/src/edoEstimator.h @@ -0,0 +1,57 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoEstimator_h +#define _edoEstimator_h + +#include +#include + +/** @defgroup Estimators Estimators + * + * Estimators takes an eoPop and estimates the parameters of a distributions + * (defined as an hypothesis) from it. + */ + +/** Base class for estimators. + * + * Estimators takes an eoPop and estimates the parameters of a distributions + * (defined as an hypothesis) from it. + * + * @ingroup Estimators + * @ingroup Core + */ +template < typename D > +class edoEstimator : public eoUF< eoPop< typename D::EOType >&, D > +{ +public: + typedef typename D::EOType EOType; + + // virtual D operator() ( eoPop< EOT >& )=0 (provided by eoUF< A1, R >) +}; + +#endif // !_edoEstimator_h diff --git a/edo/src/edoEstimatorAdaptive.h b/edo/src/edoEstimatorAdaptive.h new file mode 100644 index 000000000..225e2e57d --- /dev/null +++ b/edo/src/edoEstimatorAdaptive.h @@ -0,0 +1,58 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoEstimatorAdaptive_h +#define _edoEstimatorAdaptive_h + +#include +#include + +#include "edoEstimator.h" + +/** An interface that explicits the needs for a permanent distribution + * that will be updated by operators. + * + * @ingroup Estimators + * @ingroup Core + */ +template < typename D > +class edoEstimatorAdaptive : public edoEstimator +{ +public: + typedef typename D::EOType EOType; + + edoEstimatorAdaptive( D& distrib ) : _distrib(distrib) {} + + // virtual D operator() ( eoPop< EOT >& )=0 (provided by eoUF< A1, R >) + + D & distribution() const { return _distrib; } + +protected: + D & _distrib; +}; + +#endif // !_edoEstimatorAdaptive_h diff --git a/edo/src/edoEstimatorNormalAdaptive.h b/edo/src/edoEstimatorNormalAdaptive.h new file mode 100644 index 000000000..f1adf723f --- /dev/null +++ b/edo/src/edoEstimatorNormalAdaptive.h @@ -0,0 +1,253 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + + +#ifndef _edoEstimatorNormalAdaptive_h +#define _edoEstimatorNormalAdaptive_h + +#ifdef WITH_EIGEN + +#include + +#include + +#include "edoNormalAdaptive.h" +#include "edoEstimatorAdaptive.h" + +/** An estimator that works on adaptive normal distributions, basically the heart of the CMA-ES algorithm. + * + * @ingroup Estimators + * @ingroup CMAES + * @ingroup Adaptivenormal + */ +template< typename EOT, typename D = edoNormalAdaptive > +class edoEstimatorNormalAdaptive : public edoEstimatorAdaptive< D > +{ +public: + typedef typename EOT::AtomType AtomType; + typedef typename D::Vector Vector; // column vectors @see edoNormalAdaptive + typedef typename D::Matrix Matrix; + + edoEstimatorNormalAdaptive( D& distrib ) : + edoEstimatorAdaptive( distrib ), + _calls(0), + _eigeneval(0) + {} + +private: + Eigen::VectorXd edoCMAESweights( unsigned int pop_size ) + { + // compute recombination weights + Eigen::VectorXd weights( pop_size ); + double sum_w = 0; + for( unsigned int i = 0; i < pop_size; ++i ) { + double w_i = log( pop_size + 0.5 ) - log( i + 1 ); + weights(i) = w_i; + sum_w += w_i; + } + // normalization of weights + weights /= sum_w; + + assert( weights.size() == pop_size); + return weights; + } + +public: + void resetCalls() + { + _calls = 0; + } + + // update the distribution reference this->distribution() + edoNormalAdaptive operator()( eoPop& pop ) + { + + /********************************************************************** + * INITIALIZATION + *********************************************************************/ + + unsigned int N = pop[0].size(); // FIXME expliciter la dimension du pb ? + unsigned int lambda = pop.size(); + + // number of calls to the operator == number of generations + _calls++; + // number of "evaluations" until now + unsigned int counteval = _calls * lambda; + + // Here, if we are in canonical CMA-ES, + // pop is supposed to be the mu ranked better solutions, + // as the rank mu selection is supposed to have occured. + Matrix arx( N, lambda ); + + // copy the pop (most probably a vector of vectors) in a Eigen3 matrix + for( unsigned int d = 0; d < N; ++d ) { + for( unsigned int i = 0; i < lambda; ++i ) { + arx(d,i) = pop[i][d]; // NOTE: pop = arx.transpose() + } // dimensions + } // individuals + + // muXone array for weighted recombination + Eigen::VectorXd weights = edoCMAESweights( lambda ); + assert( weights.size() == lambda ); + + // FIXME exposer les constantes dans l'interface + + // variance-effectiveness of sum w_i x_i + double mueff = pow(weights.sum(), 2) / (weights.array().square()).sum(); + + // time constant for cumulation for C + double cc = (4+mueff/N) / (N+4 + 2*mueff/N); + + // t-const for cumulation for sigma control + double cs = (mueff+2) / (N+mueff+5); + + // learning rate for rank-one update of C + double c1 = 2 / (pow(N+1.3,2)+mueff); + + // and for rank-mu update + double cmu = 2 * (mueff-2+1/mueff) / ( pow(N+2,2)+mueff); + + // damping for sigma + double damps = 1 + 2*std::max(0.0, sqrt((mueff-1)/(N+1))-1) + cs; + + + // shortcut to the referenced distribution + D& d = this->distribution(); + + // C^-1/2 + Matrix invsqrtC = + d.coord_sys() * d.scaling().asDiagonal().inverse() + * d.coord_sys().transpose(); + assert( invsqrtC.innerSize() == d.coord_sys().innerSize() ); + assert( invsqrtC.outerSize() == d.coord_sys().outerSize() ); + + // expectation of ||N(0,I)|| == norm(randn(N,1)) + double chiN = sqrt(N)*(1-1/(4*N)+1/(21*pow(N,2))); + + + /********************************************************************** + * WEIGHTED MEAN + *********************************************************************/ + + // compute weighted mean into xmean + Vector xold = d.mean(); + assert( xold.size() == N ); + // xmean ( N, 1 ) = arx( N, lambda ) * weights( lambda, 1 ) + Vector xmean = arx * weights; + assert( xmean.size() == N ); + d.mean( xmean ); + + + /********************************************************************** + * CUMULATION: UPDATE EVOLUTION PATHS + *********************************************************************/ + + // cumulation for sigma + d.path_sigma( + (1.0-cs)*d.path_sigma() + sqrt(cs*(2.0-cs)*mueff)*invsqrtC*(xmean-xold)/d.sigma() + ); + + // sign of h + double hsig; + if( d.path_sigma().norm()/sqrt(1.0-pow((1.0-cs),(2.0*counteval/lambda)))/chiN + < 1.4 + 2.0/(N+1.0) + ) { + hsig = 1.0; + } else { + hsig = 0.0; + } + + // cumulation for the covariance matrix + d.path_covar( + (1.0-cc)*d.path_covar() + hsig*sqrt(cc*(2.0-cc)*mueff)*(xmean-xold) / d.sigma() + ); + + Matrix xmu( N, lambda); + xmu = xold.rowwise().replicate(lambda); + assert( xmu.innerSize() == N ); + assert( xmu.outerSize() == lambda ); + Matrix artmp = (1.0/d.sigma()) * (arx - xmu); + // Matrix artmp = (1.0/d.sigma()) * arx - xold.colwise().replicate(lambda); + assert( artmp.innerSize() == N && artmp.outerSize() == lambda ); + + + /********************************************************************** + * COVARIANCE MATRIX ADAPTATION + *********************************************************************/ + + d.covar( + (1-c1-cmu) * d.covar() // regard old matrix + + c1 * (d.path_covar()*d.path_covar().transpose() // plus rank one update + + (1-hsig) * cc*(2-cc) * d.covar()) // minor correction if hsig==0 + + cmu * artmp * weights.asDiagonal() * artmp.transpose() // plus rank mu update + ); + + // Adapt step size sigma + d.sigma( d.sigma() * exp((cs/damps)*(d.path_sigma().norm()/chiN - 1)) ); + + + + /********************************************************************** + * DECOMPOSITION OF THE COVARIANCE MATRIX + *********************************************************************/ + + // Decomposition of C into B*diag(D.^2)*B' (diagonalization) + if( counteval - _eigeneval > lambda/(c1+cmu)/N/10 ) { // to achieve O(N^2) + _eigeneval = counteval; + + // enforce symmetry of the covariance matrix + Matrix C = d.covar(); + // FIXME edoEstimatorNormalAdaptive.h:213:44: erreur: expected primary-expression before ‘)’ token + // copy the upper part in the lower one + //C.triangularView() = C.adjoint(); + // Matrix CS = C.triangularView() + C.triangularView().transpose(); + d.covar( C ); + + Eigen::SelfAdjointEigenSolver eigensolver( d.covar() ); // FIXME use JacobiSVD? + d.coord_sys( eigensolver.eigenvectors() ); + Matrix mD = eigensolver.eigenvalues().asDiagonal(); + assert( mD.innerSize() == N && mD.outerSize() == N ); + + // from variance to standard deviations + mD.cwiseSqrt(); + d.scaling( mD.diagonal() ); + } + + return d; + } // operator() + +protected: + + unsigned int _calls; + unsigned int _eigeneval; + + + // D & distribution() inherited from edoEstimatorAdaptive +}; +#endif // WITH_EIGEN + +#endif // !_edoEstimatorNormalAdaptive_h diff --git a/edo/src/edoEstimatorNormalMono.h b/edo/src/edoEstimatorNormalMono.h new file mode 100644 index 000000000..9e80145d3 --- /dev/null +++ b/edo/src/edoEstimatorNormalMono.h @@ -0,0 +1,122 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoEstimatorNormalMono_h +#define _edoEstimatorNormalMono_h + +#include "edoEstimator.h" +#include "edoNormalMono.h" + +/** An estimator for edoNormalMono + * + * @ingroup Estimators + * @ingroup Mononormal + */ +template < typename EOT > +class edoEstimatorNormalMono : public edoEstimator< edoNormalMono< EOT > > +{ + public: + typedef typename EOT::AtomType AtomType; + + //! Knuth's algorithm, online variance, numericably stable + class Variance + { + public: + Variance() : _n(0), _mean(0), _M2(0) {} + + void update(AtomType x) + { + _n++; + + AtomType delta = x - _mean; + + _mean += delta / _n; + _M2 += delta * ( x - _mean ); + } + + AtomType mean() const {return _mean;} + + //! Population variance + AtomType var_n() const { + assert( _n > 0 ); + return _M2 / _n; + } + + /** Sample variance (using Bessel's correction) + * is an unbiased estimate of the population variance, + * but it has uniformly higher mean squared error + */ + AtomType var() const { + assert( _n > 1 ); + return _M2 / (_n - 1); + } + + //! Population standard deviation + AtomType std_n() const {return sqrt( var_n() );} + + //! Sample standard deviation, is a biased estimate of the population standard deviation + AtomType std() const {return sqrt( var() );} + + private: + AtomType _n; + AtomType _mean; + AtomType _M2; + }; + + public: + edoNormalMono< EOT > operator()(eoPop& pop) + { + unsigned int popsize = pop.size(); + assert(popsize > 0); + + unsigned int dimsize = pop[0].size(); + assert(dimsize > 0); + + std::vector< Variance > var( dimsize ); + + for (unsigned int i = 0; i < popsize; ++i) + { + for (unsigned int d = 0; d < dimsize; ++d) + { + var[d].update( pop[i][d] ); + } + } + + EOT mean( dimsize ); + EOT variance( dimsize ); + + for (unsigned int d = 0; d < dimsize; ++d) + { + mean[d] = var[d].mean(); + variance[d] = var[d].var_n(); + } + + return edoNormalMono< EOT >( mean, variance ); + } +}; + +#endif // !_edoEstimatorNormalMono_h diff --git a/edo/src/edoEstimatorNormalMulti.h b/edo/src/edoEstimatorNormalMulti.h new file mode 100644 index 000000000..1298d8a51 --- /dev/null +++ b/edo/src/edoEstimatorNormalMulti.h @@ -0,0 +1,256 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + + +#ifndef _edoEstimatorNormalMulti_h +#define _edoEstimatorNormalMulti_h + + +#include "edoEstimator.h" +#include "edoNormalMulti.h" + +#ifdef WITH_BOOST +#include +#include +namespace ublas = boost::numeric::ublas; +#else +#ifdef WITH_EIGEN +#include +#endif // WITH_EIGEN +#endif // WITH_BOOST + + +/** An estimator for edoNormalMulti + * + * Exists in two implementations, using either + * Boost::uBLAS (if compiled WITH_BOOST) + * or Eigen3 (WITH_EIGEN). + * + * @ingroup Estimators + * @ingroup EMNA + * @ingroup Multinormal + */ +template < typename EOT, typename D=edoNormalMulti > +class edoEstimatorNormalMulti : public edoEstimator +{ + +#ifdef WITH_BOOST +public: + class CovMatrix + { + public: + typedef typename EOT::AtomType AtomType; + + CovMatrix( const eoPop< EOT >& pop ) + { + //------------------------------------------------------------- + // Some checks before starting to estimate covar + //------------------------------------------------------------- + + unsigned int p_size = pop.size(); // population size + assert(p_size > 0); + + unsigned int s_size = pop[0].size(); // solution size + assert(s_size > 0); + + //------------------------------------------------------------- + + + //------------------------------------------------------------- + // Copy the population to an ublas matrix + //------------------------------------------------------------- + + ublas::matrix< AtomType > sample( p_size, s_size ); + + for (unsigned int i = 0; i < p_size; ++i) + { + for (unsigned int j = 0; j < s_size; ++j) + { + sample(i, j) = pop[i][j]; + } + } + + //------------------------------------------------------------- + + + _varcovar.resize(s_size); + + + //------------------------------------------------------------- + // variance-covariance matrix are symmetric (and semi-definite + // positive), thus a triangular storage is sufficient + // + // variance-covariance matrix computation : transpose(A) * A + //------------------------------------------------------------- + + ublas::symmetric_matrix< AtomType, ublas::lower > var = ublas::prod( ublas::trans( sample ), sample ); + + // Be sure that the symmetric matrix got the good size + + assert(var.size1() == s_size); + assert(var.size2() == s_size); + assert(var.size1() == _varcovar.size1()); + assert(var.size2() == _varcovar.size2()); + + //------------------------------------------------------------- + + + // TODO: to remove the comment below + + // for (unsigned int i = 0; i < s_size; ++i) + // { + // // triangular LOWER matrix, thus j is not going further than i + // for (unsigned int j = 0; j <= i; ++j) + // { + // // we want a reducted covariance matrix + // _varcovar(i, j) = var(i, j) / p_size; + // } + // } + + _varcovar = var / p_size; + + _mean.resize(s_size); // FIXME: check if it is really used because of the assignation below + + // unit vector + ublas::scalar_vector< AtomType > u( p_size, 1 ); + + // sum over columns + _mean = ublas::prod( ublas::trans( sample ), u ); + + // division by n + _mean /= p_size; + } + + const ublas::symmetric_matrix< AtomType, ublas::lower >& get_varcovar() const {return _varcovar;} + + const ublas::vector< AtomType >& get_mean() const {return _mean;} + + private: + ublas::symmetric_matrix< AtomType, ublas::lower > _varcovar; + ublas::vector< AtomType > _mean; + }; + +public: + typedef typename EOT::AtomType AtomType; + + edoNormalMulti< EOT > operator()(eoPop& pop) + { + unsigned int popsize = pop.size(); + assert(popsize > 0); + + unsigned int dimsize = pop[0].size(); + assert(dimsize > 0); + + CovMatrix cov( pop ); + + return edoNormalMulti< EOT >( cov.get_mean(), cov.get_varcovar() ); + } +}; + +#else +#ifdef WITH_EIGEN + +public: + class CovMatrix + { + public: + typedef typename EOT::AtomType AtomType; + typedef typename D::Vector Vector; + typedef typename D::Matrix Matrix; + + CovMatrix( const eoPop< EOT >& pop ) + { + // Some checks before starting to estimate covar + unsigned int p_size = pop.size(); // population size + assert(p_size > 0); + unsigned int s_size = pop[0].size(); // solution size + assert(s_size > 0); + + // Copy the population to an ublas matrix + Matrix sample( p_size, s_size ); + + for (unsigned int i = 0; i < p_size; ++i) { + for (unsigned int j = 0; j < s_size; ++j) { + sample(i, j) = pop[i][j]; + } + } + + // variance-covariance matrix are symmetric, thus a triangular storage is sufficient + // variance-covariance matrix computation : transpose(A) * A + Matrix var = sample.transpose() * sample; + + // Be sure that the symmetric matrix got the good size + assert(var.innerSize() == s_size); + assert(var.outerSize() == s_size); + + _varcovar = var / p_size; + + // unit vector + Vector u( p_size); + u = Vector::Constant(p_size, 1); + + // sum over columns + _mean = sample.transpose() * u; + + // division by n + _mean /= p_size; + } + + const Matrix& get_varcovar() const {return _varcovar;} + + const Vector& get_mean() const {return _mean;} + + private: + Matrix _varcovar; + Vector _mean; + }; + +public: + typedef typename EOT::AtomType AtomType; + + edoNormalMulti< EOT > operator()(eoPop& pop) + { + unsigned int p_size = pop.size(); + assert(p_size > 0); + + unsigned int s_size = pop[0].size(); + assert(s_size > 0); + + CovMatrix cov( pop ); + + assert( cov.get_mean().innerSize() == s_size ); + assert( cov.get_mean().outerSize() == 1 ); + assert( cov.get_varcovar().innerSize() == s_size ); + assert( cov.get_varcovar().outerSize() == s_size ); + + return edoNormalMulti< EOT >( cov.get_mean(), cov.get_varcovar() ); + } +#endif // WITH_EIGEN +#endif // WITH_BOOST +}; // class edoNormalMulti + +#endif // !_edoEstimatorNormalMulti_h diff --git a/edo/src/edoEstimatorUniform.h b/edo/src/edoEstimatorUniform.h new file mode 100644 index 000000000..f799ac2f1 --- /dev/null +++ b/edo/src/edoEstimatorUniform.h @@ -0,0 +1,73 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoEstimatorUniform_h +#define _edoEstimatorUniform_h + +#include "edoEstimator.h" +#include "edoUniform.h" + +/** An estimator for edoUniform + * + * @ingroup Estimators + */ +template < typename EOT > +class edoEstimatorUniform : public edoEstimator< edoUniform< EOT > > +{ +public: + edoUniform< EOT > operator()(eoPop& pop) + { + unsigned int size = pop.size(); + + assert(size > 0); + + EOT min = pop[0]; + EOT max = pop[0]; + + for (unsigned int i = 1; i < size; ++i) + { + unsigned int size = pop[i].size(); + + assert(size > 0); + + // possibilité d'utiliser std::min_element et std::max_element mais exige 2 pass au lieu d'1. + + for (unsigned int d = 0; d < size; ++d) + { + if (pop[i][d] < min[d]) + min[d] = pop[i][d]; + + if (pop[i][d] > max[d]) + max[d] = pop[i][d]; + } + } + + return edoUniform< EOT >(min, max); + } +}; + +#endif // !_edoEstimatorUniform_h diff --git a/edo/src/edoModifier.h b/edo/src/edoModifier.h new file mode 100644 index 000000000..2b1ef2cbf --- /dev/null +++ b/edo/src/edoModifier.h @@ -0,0 +1,50 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoModifier_h +#define _edoModifier_h + +/** @defgroup Modifiers + * + * A set of classes that arbitrarly modify a given distribution. + */ + +/** A functor to arbitrarly modify a distribution + * + * @ingroup Core + * @ingroup Modifiers + */ +template < typename D > +class edoModifier +{ +public: + virtual ~edoModifier(){} + + typedef typename D::EOType EOType; +}; + +#endif // !_edoModifier_h diff --git a/edo/src/edoModifierDispersion.h b/edo/src/edoModifierDispersion.h new file mode 100644 index 000000000..7636f67e5 --- /dev/null +++ b/edo/src/edoModifierDispersion.h @@ -0,0 +1,47 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoModifierDispersion_h +#define _edoModifierDispersion_h + +#include +#include + +#include "edoModifier.h" + +/** An semantic pseudo-interface for modifiers that updates dispersion parameters (like variance). + * + * @ingroup Modifiers + */ +template < typename D > +class edoModifierDispersion : public edoModifier< D >, public eoBF< D&, eoPop< typename D::EOType >&, void > +{ +public: + // virtual void operator() ( D&, eoPop< D::EOType >& )=0 (provided by eoBF< A1, A2, R >) +}; + +#endif // !_edoModifierDispersion_h diff --git a/edo/src/edoModifierMass.h b/edo/src/edoModifierMass.h new file mode 100644 index 000000000..aa90c55a3 --- /dev/null +++ b/edo/src/edoModifierMass.h @@ -0,0 +1,49 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoModifierMass_h +#define _edoModifierMass_h + +#include + +#include "edoModifier.h" + + +/** An semantic pseudo-interface for modifiers that updates mass parameters (like mean). + * + * @ingroup Modifiers + */ +template < typename D > +class edoModifierMass : public edoModifier< D >, public eoBF< D&, typename D::EOType&, void > +{ +public: + //typedef typename D::EOType::AtomType AtomType; // does not work !!! + + // virtual void operator() ( D&, D::EOType& )=0 (provided by eoBF< A1, A2, R >) +}; + +#endif // !_edoModifierMass_h diff --git a/edo/src/edoNormalAdaptive.h b/edo/src/edoNormalAdaptive.h new file mode 100644 index 000000000..edde019b1 --- /dev/null +++ b/edo/src/edoNormalAdaptive.h @@ -0,0 +1,171 @@ + +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dreo + Pierre Savéant +*/ + +#ifndef _edoNormalAdaptive_h +#define _edoNormalAdaptive_h + +#include "edoDistrib.h" + +#ifdef WITH_EIGEN + +#include + +/** @defgroup CMAES CMAES + * + * CMA-ES (Covariance Matrix Adaptation Evolution Strategy) is a stochastic, + * derivative-free methods for numerical optimization of non-linear or + * non-convex continuous optimization problems. + * + * @ingroup Algorithms + */ + +/** @defgroup Adaptivenormal Adaptive normal + * + * A multi-variate normal distribution that can be updated via several components. + * This is the data structure on which works the CMA-ES algorithm. + * + * @ingroup Distributions + */ + +/** A normal distribution that can be updated via several components. This is the data structure on which works the CMA-ES + * algorithm. + * + * This is *just* a data structure, the operators working on it are supposed to maintain its consistency (e.g. of the + * covariance matrix against its eigen vectors). + * + * The distribution is defined by its mean, its covariance matrix (which can be decomposed in its eigen vectors and + * values), a scaling factor (sigma) and the so-called evolution paths for the covariance and sigma. + * evolution paths. + * + * NOTE: this is only available as an Eigen3 implementation (built WITH_EIGEN). + * + * @ingroup Distributions + * @ingroup CMAES + * @ingroup Adaptivenormal + */ +template < typename EOT > +class edoNormalAdaptive : public edoDistrib< EOT > +{ +public: + //typedef EOT EOType; + typedef typename EOT::AtomType AtomType; + typedef Eigen::Matrix< AtomType, Eigen::Dynamic, 1> Vector; // column vectors ( n lines, 1 column) + typedef Eigen::Matrix< AtomType, Eigen::Dynamic, Eigen::Dynamic> Matrix; + + edoNormalAdaptive( unsigned int dim = 1 ) : + _dim(dim), + _mean( Vector::Zero(dim) ), + _C( Matrix::Identity(dim,dim) ), + _B( Matrix::Identity(dim,dim) ), + _D( Vector::Constant( dim, 1) ), + _sigma(1.0), + _p_c( Vector::Zero(dim) ), + _p_s( Vector::Zero(dim) ) + { + assert( _dim > 0); + } + + edoNormalAdaptive( unsigned int dim, + Vector mean, + Matrix C, + Matrix B, + Vector D, + double sigma, + Vector p_c, + Vector p_s + ) : + _mean( mean ), + _C( C ), + _B( B ), + _D( D ), + _sigma(sigma), + _p_c( p_c ), + _p_s( p_s ) + { + assert( dim > 0); + assert( _mean.innerSize() == dim ); + assert( _C.innerSize() == dim && _C.outerSize() == dim ); + assert( _B.innerSize() == dim && _B.outerSize() == dim ); + assert( _D.innerSize() == dim ); + assert( _sigma != 0.0 ); + assert( _p_c.innerSize() == dim ); + assert( _p_s.innerSize() == dim ); + } + + unsigned int size() + { + return _mean.innerSize(); + } + + Vector mean() const {return _mean;} + Matrix covar() const {return _C;} + Matrix coord_sys() const {return _B;} + Vector scaling() const {return _D;} + double sigma() const {return _sigma;} + Vector path_covar() const {return _p_c;} + Vector path_sigma() const {return _p_s;} + + //! Set the mean with an Eigen3 vector + void mean( Vector m ) { _mean = m; assert( m.size() == _dim ); } + + /** Set the mean with an EOT instead of an Eigen3 mean + * + * Explicit copy of the EOT in a vector. + */ + void mean( EOT m ) + { + Vector center( m.size() ); + for( unsigned int i=0, end=m.size(); i + Caner Candan +*/ + +#ifndef _edoNormalMono_h +#define _edoNormalMono_h + +#include "edoDistrib.h" + +/** @defgroup Mononormal Normal + * A normal (Gaussian) distribution that only model variances of variables. + * + * @ingroup Distributions + */ + +/** A normal (Gaussian) distribution that only model variances of variables. + * + * This is basically a mean vector and a variances vector. Do not model co-variances. + * + * @ingroup Distributions + * @ingroup Mononormal + */ +template < typename EOT > +class edoNormalMono : public edoDistrib< EOT > +{ +public: + edoNormalMono() + : _mean(EOT(1,0)), _variance(EOT(1,1)) + {} + + edoNormalMono( const EOT& mean, const EOT& variance ) + : _mean(mean), _variance(variance) + { + assert(_mean.size() > 0); + assert(_mean.size() == _variance.size()); + } + + unsigned int size() + { + assert(_mean.size() == _variance.size()); + return _mean.size(); + } + + EOT mean(){return _mean;} + EOT variance(){return _variance;} + +private: + EOT _mean; + EOT _variance; +}; + +#endif // !_edoNormalMono_h diff --git a/edo/src/edoNormalMonoCenter.h b/edo/src/edoNormalMonoCenter.h new file mode 100644 index 000000000..9c31204b1 --- /dev/null +++ b/edo/src/edoNormalMonoCenter.h @@ -0,0 +1,51 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoNormalMonoCenter_h +#define _edoNormalMonoCenter_h + +#include "edoModifierMass.h" +#include "edoNormalMono.h" + +/** Change a distribution's mean for a given EOT + * + * @ingroup Modifiers + * @ingroup Mononormal + */ +template < typename EOT > +class edoNormalMonoCenter : public edoModifierMass< edoNormalMono< EOT > > +{ +public: + typedef typename EOT::AtomType AtomType; + + void operator() ( edoNormalMono< EOT >& distrib, EOT& mass ) + { + distrib.mean() = mass; + } +}; + +#endif // !_edoNormalMonoCenter_h diff --git a/edo/src/edoNormalMulti.h b/edo/src/edoNormalMulti.h new file mode 100644 index 000000000..a64a91214 --- /dev/null +++ b/edo/src/edoNormalMulti.h @@ -0,0 +1,163 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* + Authors: + Johann Dreo + Caner Candan +*/ + +#ifndef _edoNormalMulti_h +#define _edoNormalMulti_h + +#include "edoDistrib.h" + +#ifdef WITH_BOOST +#include +#include +namespace ublas = boost::numeric::ublas; +#else +#ifdef WITH_EIGEN +#include +#endif // WITH_EIGEN +#endif // WITH_BOOST + +/** @defgroup EMNA + * + * Estimation of Multivariate Normal Algorithm (EMNA) is a stochastic, + * derivative-free methods for numerical optimization of non-linear or + * non-convex continuous optimization problems. + * + * @ingroup Algorithms + */ + +/** @defgroup Multinormal Multivariate normal + * + * Distribution that model co-variances between variables. + * + * @ingroup Distributions + */ + +/** A multi-normal distribution, that models co-variances. + * + * Defines a mean vector and a co-variances matrix. + * + * Exists in two implementations, using either + * Boost::uBLAS (if compiled WITH_BOOST) + * or Eigen3 (WITH_EIGEN). + * + * @ingroup Distributions + * @ingroup EMNA + * @ingroup Multinormal + */ +template < typename EOT > +class edoNormalMulti : public edoDistrib< EOT > +{ +#ifdef WITH_BOOST + + +public: + typedef typename EOT::AtomType AtomType; + + edoNormalMulti( unsigned int dim = 1 ) : + _mean( const ublas::vector(0,dim) ), + _varcovar( const ublas::identity_matrix(dim) ) + { + assert(_mean.size() > 0); + assert(_mean.size() == _varcovar.size1()); + assert(_mean.size() == _varcovar.size2()); + } + + edoNormalMulti + ( + const ublas::vector< AtomType >& mean, + const ublas::symmetric_matrix< AtomType, ublas::lower >& varcovar + ) + : _mean(mean), _varcovar(varcovar) + { + assert(_mean.size() > 0); + assert(_mean.size() == _varcovar.size1()); + assert(_mean.size() == _varcovar.size2()); + } + + unsigned int size() + { + assert(_mean.size() == _varcovar.size1()); + assert(_mean.size() == _varcovar.size2()); + return _mean.size(); + } + + ublas::vector< AtomType > mean() const {return _mean;} + ublas::symmetric_matrix< AtomType, ublas::lower > varcovar() const {return _varcovar;} + +private: + ublas::vector< AtomType > _mean; + ublas::symmetric_matrix< AtomType, ublas::lower > _varcovar; + +#else +#ifdef WITH_EIGEN + + +public: + typedef typename EOT::AtomType AtomType; + typedef Eigen::Matrix< AtomType, Eigen::Dynamic, 1> Vector; + typedef Eigen::Matrix< AtomType, Eigen::Dynamic, Eigen::Dynamic> Matrix; + + edoNormalMulti( unsigned int dim = 1 ) : + _mean( Vector::Zero(dim) ), + _varcovar( Matrix::Identity(dim,dim) ) + { + assert(_mean.size() > 0); + assert(_mean.innerSize() == _varcovar.innerSize()); + assert(_mean.innerSize() == _varcovar.outerSize()); + } + + edoNormalMulti( + const Vector & mean, + const Matrix & varcovar + ) + : _mean(mean), _varcovar(varcovar) + { + assert(_mean.innerSize() > 0); + assert(_mean.innerSize() == _varcovar.innerSize()); + assert(_mean.innerSize() == _varcovar.outerSize()); + } + + unsigned int size() + { + assert(_mean.innerSize() == _varcovar.innerSize()); + assert(_mean.innerSize() == _varcovar.outerSize()); + return _mean.innerSize(); + } + + Vector mean() const {return _mean;} + Matrix varcovar() const {return _varcovar;} + +private: + Vector _mean; + Matrix _varcovar; + +#endif // WITH_EIGEN +#endif // WITH_BOOST + +}; // class edoNormalMulti + +#endif // !_edoNormalMulti_h diff --git a/edo/src/edoNormalMultiCenter.h b/edo/src/edoNormalMultiCenter.h new file mode 100644 index 000000000..30510c60d --- /dev/null +++ b/edo/src/edoNormalMultiCenter.h @@ -0,0 +1,85 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoNormalMultiCenter_h +#define _edoNormalMultiCenter_h + +#include "edoModifierMass.h" +#include "edoNormalMulti.h" + +#ifdef WITH_BOOST + +/** Changes a given distribution's mean by a given EOT. + * + * @ingroup Modifiers + * @ingroup EMNA + * @inngroup Multinormal + */ +template < typename EOT > +class edoNormalMultiCenter : public edoModifierMass< edoNormalMulti< EOT > > +{ +public: + typedef typename EOT::AtomType AtomType; + + void operator() ( edoNormalMulti< EOT >& distrib, EOT& mass ) + { + ublas::vector< AtomType > mean( distrib.size() ); + std::copy( mass.begin(), mass.end(), mean.begin() ); + distrib.mean() = mean; + } +}; + +#else +#ifdef WITH_EIGEN + +/** Changes a given distribution's mean by a given EOT. + * + * @ingroup Modifiers + */ +template < typename EOT, typename D = edoNormalMulti< EOT > > +class edoNormalMultiCenter : public edoModifierMass +{ +public: + typedef typename EOT::AtomType AtomType; + typedef typename D::Vector Vector; + + void operator() ( edoNormalMulti< EOT >& distrib, EOT& mass ) + { + assert( distrib.size() == mass.innerSize() ); + Vector mean( distrib.size() ); + for( unsigned int i=0; i < distrib.size(); i++ ) { + mean(i) = mass[i]; + } + distrib.mean() = mean; + } +}; + +#endif // WITH_EIGEN +#endif // WITH_BOOST + + +#endif // !_edoNormalMultiCenter_h diff --git a/edo/src/edoRepairer.h b/edo/src/edoRepairer.h new file mode 100644 index 000000000..a594bec4d --- /dev/null +++ b/edo/src/edoRepairer.h @@ -0,0 +1,55 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2011 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoRepairer_h +#define _edoRepairer_h + +#include + +/** @defgroup Repairers + * + * A set of classes that modifies an unfeasible candidate + * solution so as to respect a given set of constraints and thus make a feasible + * solution. + */ + +/** The interface of a set of classes that modifies an unfeasible candidate + * solution so as to respect a given set of constraints and thus make a feasible + * solution. + * + * @ingroup Repairers + * @ingroup Core + */ +template < typename EOT > +class edoRepairer : public eoUF< EOT&, void > +{ +public: + // virtual void operator()( EOT& ) = 0 (provided by eoUF< A1, R >) + virtual void operator()( EOT& ) {} +}; + +#endif // !_edoRepairer_h diff --git a/edo/src/edoRepairerApply.h b/edo/src/edoRepairerApply.h new file mode 100644 index 000000000..49430050a --- /dev/null +++ b/edo/src/edoRepairerApply.h @@ -0,0 +1,103 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2011 Thales group +*/ +/* +Authors: + Johann Dréo +*/ + +#ifndef _edoRepairerApply_h +#define _edoRepairerApply_h + +#include + +#include "edoRepairer.h" + +/** Interface for applying an arbitrary unary function as a repairer on each item of the solution + * + * @ingroup Repairers + */ +template < typename EOT, typename F = typename EOT::AtomType(typename EOT::AtomType) > +class edoRepairerApply : public edoRepairer +{ +public: + edoRepairerApply( F function ) : _function(function) {} + +protected: + F * _function; +}; + + +/** Apply an arbitrary unary function as a repairer on each item of the solution + * + * By default, the signature of the expected function is "EOT::AtomType(EOT::AtomType)" + * + * @ingroup Repairers + */ +template < typename EOT, typename F = typename EOT::AtomType(typename EOT::AtomType)> +class edoRepairerApplyUnary : public edoRepairerApply +{ +public: + edoRepairerApplyUnary( F function ) : edoRepairerApply(function) {} + + virtual void operator()( EOT& sol ) + { + std::transform( sol.begin(), sol.end(), sol.begin(), *(this->_function) ); + sol.invalidate(); + } +}; + + +/** Apply an arbitrary binary function as a repairer on each item of the solution, + * the second argument of the function being fixed and given at instanciation. + * + * @see edoRepairerApplyUnary + * + * @ingroup Repairers + */ +template < typename EOT, typename F = typename EOT::AtomType(typename EOT::AtomType, typename EOT::AtomType)> +class edoRepairerApplyBinary : public edoRepairerApply +{ +public: + typedef typename EOT::AtomType ArgType; + + edoRepairerApplyBinary( + F function, + ArgType arg + ) : edoRepairerApply(function), _arg(arg) {} + + virtual void operator()( EOT& sol ) + { + // call the binary function on each item + // TODO find a way to use std::transform here? Or would it be too bloated? + for(typename EOT::iterator it = sol.begin(); it != sol.end(); ++it ) { + *it = (*(this->_function))( *it, _arg ); + } + sol.invalidate(); + } + +protected: + ArgType _arg; +}; + + +#endif // !_edoRepairerApply_h + diff --git a/edo/src/edoRepairerDispatcher.h b/edo/src/edoRepairerDispatcher.h new file mode 100644 index 000000000..bf4ff7cf8 --- /dev/null +++ b/edo/src/edoRepairerDispatcher.h @@ -0,0 +1,184 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2011 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoRepairerDispatcher_h +#define _edoRepairerDispatcher_h + +#include +#include + +#include "edoRepairer.h" + +/** Repair a candidate solution by sequentially applying several repairers on + * subparts of the solution (subparts being defined by the corresponding set + * of indexes). + * + * Only work on EOT that implements the "push_back( EOT::AtomType )" and + * "operator[](uint)" and "at(uint)" methods (i.e. random access containers). + * + * Expects _addresses_ of the repairer operators. + * + * Use the second template type if you want a different container to store + * indexes. You can use any iterable. For example, you may want to use a set if + * you need to be sure that indexes are use only once: + * edoRepairerDispatcher > rpd; + * std::set idx(1,1); + * idx.insert(2); + * rpd.add( idx, &repairer ); + * + * A diagram trying to visually explain how it works: + \ditaa + + | + /-\ | /------------\ + | +---|---+ Dispatcher | + | | v | | + | |+-----+| --------------------------------+ + | || x_0 || +-+-+-+ | +------------\ | /-\ + | |+-----+| |2|3|5+*----*-* Repairer A +---|---+ | + | || x_1 || +-+-+-+ | | | | v | | + | |+-----+| | | | |+-----+| | + | || x_2 || | | | || x_2 || | + | |+-----+| | | | |+-----+| | + | || x_3 || | | | || x_3 || | + | |+-----+| | | | |+-----+| | + | || x_4 || | | | || x_5 || | + | |+-----+| | | | |+-----+| | + | || x_5 || | | | | | | | + | |+-----+| | | | +---|---+ | + | || x_6 || | | \------------/ | \-/ + | |+-----+| <-------------------------------+ + | || x_7 || | | + | |+-----+| +-+-+ | | + | || x_8 || |2|3+*------+ + | |+-----+| +-+-+ | + | || x_9 || | + | |+-----+| +-+-+ | +------------\ /-\ + | | | | |1|5+*--------* Repairer B +-------+ | + | | | | +-+-+ | | | | | + | | | | | | | | | + | | | | | | +-------+ | + | +---|---+ | \------------/ \-/ + \-/ | \------------/ + v + + \endditaa + + * @example t-dispatcher-round.cpp + * + * @ingroup Repairers + */ +template < typename EOT, typename ICT = std::vector > +class edoRepairerDispatcher + : public edoRepairer, + std::vector< + std::pair< ICT, edoRepairer< EOT >* > + > +{ +public: + + //! Empty constructor + edoRepairerDispatcher() : + std::vector< + std::pair< std::vector< unsigned int >, edoRepairer< EOT >* > + >() + {} + + //! Constructor with a single index set and repairer operator + edoRepairerDispatcher( ICT idx, edoRepairer* op ) : + std::vector< + std::pair< std::vector< unsigned int >, edoRepairer< EOT >* > + >() + { + this->add( idx, op ); + } + + //! Add more indexes set and their corresponding repairer operator address to the list + void add( ICT idx, edoRepairer* op ) + { +#ifndef NDEBUG + if( idx.size() == 0 ) { + eo::log << eo::warnings << "A repairer is added to the dispatcher while having an empty index list, nothing will be repaired" << std::endl; + } +#endif + assert( op != NULL ); + + this->push_back( std::make_pair(idx, op) ); + } + + //! Repair a solution by calling several repair operator on subset of indexes + virtual void operator()( EOT& sol ) + { +// std::cout << "in dispatcher, sol = " << sol << std::endl; + + // iterate over { indexe, repairer } + // ipair is an iterator that points on a pair of + for( typename edoRepairerDispatcher::iterator ipair = this->begin(); ipair != this->end(); ++ipair ) { + + assert( ipair->first.size() <= sol.size() ); // assert there is less indexes than items in the whole solution + + // a partial copy of the sol + EOT partsol; + +// std::cout << "\tusing indexes = "; +// + // iterate over indexes + // j is an iterator that points on an uint + for( std::vector< unsigned int >::iterator j = ipair->first.begin(); j != ipair->first.end(); ++j ) { + +// std::cout << *j << " "; +// std::cout.flush(); + + partsol.push_back( sol.at(*j) ); + } // for j +// std::cout << std::endl; +// std::cout << "\tpartial sol = " << partsol << std::endl; + + if( partsol.size() == 0 ) { + continue; + } + assert( partsol.size() > 0 ); + + // apply the repairer on the partial copy + // the repairer is a functor, thus second is callable + (*(ipair->second))( partsol ); + + { // copy back the repaired partial solution to sol + // browse partsol with uint k, and the idx set with an iterator (std::vector is an associative tab) + unsigned int k=0; + for( std::vector< unsigned int >::iterator j = ipair->first.begin(); j != ipair->first.end(); ++j ) { + sol[ *j ] = partsol[ k ]; + k++; + } // for j + } // context for k + } // for ipair + + sol.invalidate(); + } +}; + +#endif // !_edoRepairerDispatcher_h diff --git a/edo/src/edoRepairerModulo.h b/edo/src/edoRepairerModulo.h new file mode 100644 index 000000000..1bc7e7682 --- /dev/null +++ b/edo/src/edoRepairerModulo.h @@ -0,0 +1,47 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2011 Thales group +*/ +/* +Authors: + Johann Dréo +*/ + +#ifndef _edoRepairerModulo_h +#define _edoRepairerModulo_h + +#include + +#include "edoRepairerApply.h" + +/** Repair an EOT container by applying the standard modulo function on it. + * + * @ingroup Repairers + */ +template < typename EOT > +class edoRepairerModulo: public edoRepairerApplyBinary +{ +public: + edoRepairerModulo( double denominator ) : edoRepairerApplyBinary( std::fmod, denominator ) {} +}; + + +#endif // !_edoRepairerModulo_h + diff --git a/edo/src/edoRepairerRound.h b/edo/src/edoRepairerRound.h new file mode 100644 index 000000000..a882021cc --- /dev/null +++ b/edo/src/edoRepairerRound.h @@ -0,0 +1,110 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2011 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoRepairerRound_h +#define _edoRepairerRound_h + +#include + +#include "edoRepairerApply.h" + + +/** A repairer that calls "floor" on each items of a solution + * + * Just a proxy to "edoRepairerApplyUnary rep( std::floor);" + * + * @ingroup Repairers + */ +template < typename EOT > +class edoRepairerFloor : public edoRepairerApplyUnary +{ +public: + edoRepairerFloor() : edoRepairerApplyUnary( std::floor ) {} +}; + + +/** A repairer that calls "ceil" on each items of a solution + * + * @see edoRepairerFloor + * + * @ingroup Repairers + */ +template < typename EOT > +class edoRepairerCeil : public edoRepairerApplyUnary +{ +public: + edoRepairerCeil() : edoRepairerApplyUnary( std::ceil ) {} +}; + + +// FIXME find a way to put this function as a member of edoRepairerRoundDecimals +template< typename ArgType > +ArgType edoRound( ArgType val, ArgType prec = 1.0 ) +{ + return (val > 0.0) ? + floor(val * prec + 0.5) / prec : + ceil(val * prec - 0.5) / prec ; +} + +/** A repairer that round values at a given a precision. + * + * e.g. if prec=0.1, 8.06 will be rounded to 8.1 + * + * @see edoRepairerFloor + * @see edoRepairerCeil + * + * @ingroup Repairers + */ +template < typename EOT > +class edoRepairerRoundDecimals : public edoRepairerApplyBinary +{ +public: + typedef typename EOT::AtomType ArgType; + + //! Generally speaking, we expect decimals being <= 1, but it can work for higher values + edoRepairerRoundDecimals( ArgType decimals ) : edoRepairerApplyBinary( edoRound, 1 / decimals ) + { + assert( decimals <= 1.0 ); + assert( 1/decimals >= 1.0 ); + } +}; + + +/** A repairer that do a rounding around val+0.5 + * + * @see edoRepairerRoundDecimals + * + * @ingroup Repairers + */ +template < typename EOT > +class edoRepairerRound : public edoRepairerRoundDecimals +{ +public: + edoRepairerRound() : edoRepairerRoundDecimals( 1.0 ) {} +}; + +#endif // !_edoRepairerRound_h diff --git a/edo/src/edoSampler.h b/edo/src/edoSampler.h new file mode 100644 index 000000000..d2b1b431c --- /dev/null +++ b/edo/src/edoSampler.h @@ -0,0 +1,100 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoSampler_h +#define _edoSampler_h + +#include + +#include "edoRepairer.h" +#include "edoBounderNo.h" + + +/** @defgroup Samplers + * + * Functors that draw and repair individuals according to a given distribution. + */ + +/** Base class for samplers + * + * The functor here is already implemented: it first sample an EOT from the + * given distribution, and then apply the given repairers (if set). + * + * Thus, the function that need to be overloaded is "sample", unlike most of EO + * functors. + * + * @ingroup Samplers + * @ingroup Core + */ +template < typename D > +class edoSampler : public eoUF< D&, typename D::EOType > +{ +public: + typedef typename D::EOType EOType; + + edoSampler(edoRepairer< EOType > & repairer) + : _dummy_repairer(), _repairer(repairer) + {} + + + edoSampler() + : _dummy_repairer(), _repairer( _dummy_repairer ) + {} + + + // virtual EOType operator()( D& ) = 0 (provided by eoUF< A1, R >) + + EOType operator()( D& distrib ) + { + assert( distrib.size() > 0 ); + + // Point we want to sample to get higher a set of points + // (coordinates in n dimension) + // x = {x1, x2, ..., xn} + // the sample method is implemented in the derivated class + EOType solution(sample(distrib)); + + // Now we are bounding the distribution thanks to min and max + // parameters. + _repairer(solution); + + return solution; + } + +protected: + + virtual EOType sample( D& ) = 0; + +private: + edoBounderNo _dummy_repairer; + + //! repairer functor + edoRepairer< EOType > & _repairer; + +}; + +#endif // !_edoSampler_h diff --git a/edo/src/edoSamplerNormalAdaptive.h b/edo/src/edoSamplerNormalAdaptive.h new file mode 100644 index 000000000..051e14835 --- /dev/null +++ b/edo/src/edoSamplerNormalAdaptive.h @@ -0,0 +1,91 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#ifndef _edoSamplerNormalAdaptive_h +#define _edoSamplerNormalAdaptive_h + +#include +#include + +#include + +/** Sample points in a multi-normal law defined by a mean vector, a covariance matrix, a sigma scale factor and + * evolution paths. This is a step of the CMA-ES algorithm. + * + * @ingroup Samplers + * @ingroup CMAES + * @ingroup Adaptivenormal + */ +#ifdef WITH_EIGEN + +template< class EOT, typename D = edoNormalAdaptive< EOT > > +class edoSamplerNormalAdaptive : public edoSampler< D > +{ +public: + typedef typename EOT::AtomType AtomType; + + typedef typename D::Vector Vector; + typedef typename D::Matrix Matrix; + + edoSamplerNormalAdaptive( edoRepairer & repairer ) + : edoSampler< D >( repairer) + {} + + + EOT sample( D& distrib ) + { + unsigned int N = distrib.size(); + assert( N > 0); + + // T = vector of size elements drawn in N(0,1) + Vector T( N ); + for ( unsigned int i = 0; i < N; ++i ) { + T( i ) = rng.normal(); + } + assert(T.innerSize() == N ); + assert(T.outerSize() == 1); + + // mean(N,1) + sigma * B(N,N) * ( D(N,1) .* T(N,1) ) + Vector sol = distrib.mean() + + distrib.sigma() + * distrib.coord_sys() * (distrib.scaling().cwiseProduct(T) ); // C * T = B * (D .* T) + assert( sol.size() == N ); + /*Vector sol = distrib.mean() + distrib.sigma() + * distrib.coord_sys().dot( distrib.scaling().dot( T ) );*/ + + // copy in the EOT structure (more probably a vector) + EOT solution( N ); + for( unsigned int i = 0; i < N; i++ ) { + solution[i]= sol(i); + } + + return solution; + } +}; +#endif // WITH_EIGEN + +#endif // !_edoSamplerNormalAdaptive_h diff --git a/edo/src/edoSamplerNormalMono.h b/edo/src/edoSamplerNormalMono.h new file mode 100644 index 000000000..f4bf7964a --- /dev/null +++ b/edo/src/edoSamplerNormalMono.h @@ -0,0 +1,76 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoSamplerNormalMono_h +#define _edoSamplerNormalMono_h + +#include + +#include + +#include "edoSampler.h" +#include "edoNormalMono.h" +#include "edoBounder.h" + +/** A sampler for edoNormalMono + * + * @ingroup Samplers + * @ingroup Mononormal + */ +template < typename EOT, typename D = edoNormalMono< EOT > > +class edoSamplerNormalMono : public edoSampler< D > +{ +public: + typedef typename EOT::AtomType AtomType; + + edoSamplerNormalMono( edoRepairer & repairer ) : edoSampler< D >( repairer) {} + + EOT sample( edoNormalMono& distrib ) + { + unsigned int size = distrib.size(); + assert(size > 0); + + // The point we want to draw + // (coordinates in n dimension) + // x = {x1, x2, ..., xn} + EOT solution; + + // Sampling all dimensions + for (unsigned int i = 0; i < size; ++i) { + AtomType mean = distrib.mean()[i]; + AtomType variance = distrib.variance()[i]; + // should use the standard deviation, which have the same scale than the mean + AtomType random = rng.normal(mean, sqrt(variance) ); + + solution.push_back(random); + } + + return solution; + } +}; + +#endif // !_edoSamplerNormalMono_h diff --git a/edo/src/edoSamplerNormalMulti.h b/edo/src/edoSamplerNormalMulti.h new file mode 100644 index 000000000..d6e3b9bc7 --- /dev/null +++ b/edo/src/edoSamplerNormalMulti.h @@ -0,0 +1,186 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoSamplerNormalMulti_h +#define _edoSamplerNormalMulti_h + +#include +#include + +#include + + +#ifdef WITH_BOOST +#include +#include +#include +namespace ublas = boost::numeric::ublas; +#else +#ifdef WITH_EIGEN +#include +#endif // WITH_EIGEN +#endif // WITH_BOOST + + +/** Sample points in a multi-normal law defined by a mean vector and a covariance matrix. + * + * Given M the mean vector and V the covariance matrix, of order n: + * - draw a vector T in N(0,I) (i.e. each value is drawn in a normal law with mean=0 an stddev=1) + * - compute the Cholesky decomposition L of V (i.e. such as V=LL*) + * - return X = M + LT + * + * Exists in two implementations, using either + * Boost::uBLAS (if compiled WITH_BOOST) + * or Eigen3 (WITH_EIGEN). + * + * @ingroup Samplers + * @ingroup EMNA + * @ingroup Multinormal + */ +template< typename EOT, typename D = edoNormalMulti< EOT > > +class edoSamplerNormalMulti : public edoSampler< D > +{ + +#ifdef WITH_BOOST + +public: + typedef typename EOT::AtomType AtomType; + + edoSamplerNormalMulti( edoRepairer & repairer ) + : edoSampler< D >( repairer) + {} + + + EOT sample( D& distrib ) + { + unsigned int size = distrib.size(); + assert(size > 0); + + // L = cholesky decomposition of varcovar + const typename cholesky::CholeskyBase::FactorMat& L = _cholesky( distrib.varcovar() ); + + // T = vector of size elements drawn in N(0,1) + ublas::vector< AtomType > T( size ); + for ( unsigned int i = 0; i < size; ++i ) { + T( i ) = rng.normal(); + } + + // LT = L * T + ublas::vector< AtomType > LT = ublas::prod( L, T ); + + // solution = means + LT + ublas::vector< AtomType > mean = distrib.mean(); + ublas::vector< AtomType > ublas_solution = mean + LT; + EOT solution( size ); + std::copy( ublas_solution.begin(), ublas_solution.end(), solution.begin() ); + + return solution; + } + +protected: + cholesky::CholeskyLLT _cholesky; + +#else +#ifdef WITH_EIGEN + +public: + typedef typename EOT::AtomType AtomType; + + typedef typename D::Vector Vector; + typedef typename D::Matrix Matrix; + + edoSamplerNormalMulti( edoRepairer & repairer ) + : edoSampler< D >( repairer) + {} + + + EOT sample( D& distrib ) + { + unsigned int size = distrib.size(); + assert(size > 0); + + // LsD = cholesky decomposition of varcovar + + // Computes L and mD such as V = L mD L^T + Eigen::LDLT cholesky( distrib.varcovar() ); + Matrix L = cholesky.matrixL(); + assert(L.innerSize() == size); + assert(L.outerSize() == size); + + Matrix mD = cholesky.vectorD().asDiagonal(); + assert(mD.innerSize() == size); + assert(mD.outerSize() == size); + + // now compute the final symetric matrix: LsD = L mD^1/2 + // remember that V = ( L mD^1/2) ( L mD^1/2)^T + // fortunately, the square root of a diagonal matrix is the square + // root of all its elements + Matrix sqrtD = mD.cwiseSqrt(); + assert(sqrtD.innerSize() == size); + assert(sqrtD.outerSize() == size); + + Matrix LsD = L * sqrtD; + assert(LsD.innerSize() == size); + assert(LsD.outerSize() == size); + + // T = vector of size elements drawn in N(0,1) + Vector T( size ); + for ( unsigned int i = 0; i < size; ++i ) { + T( i ) = rng.normal(); + } + assert(T.innerSize() == size); + assert(T.outerSize() == 1); + + // LDT = (L mD^1/2) * T + Vector LDT = LsD * T; + assert(LDT.innerSize() == size); + assert(LDT.outerSize() == 1); + + // solution = means + LDT + Vector mean = distrib.mean(); + assert(mean.innerSize() == size); + assert(mean.outerSize() == 1); + + Vector typed_solution = mean + LDT; + assert(typed_solution.innerSize() == size); + assert(typed_solution.outerSize() == 1); + + // copy in the EOT structure (more probably a vector) + EOT solution( size ); + for( unsigned int i = 0; i < mean.innerSize(); i++ ) { + solution[i]= typed_solution(i); + } + assert( solution.size() == size ); + + return solution; + } +#endif // WITH_EIGEN +#endif // WITH_BOOST +}; // class edoNormalMulti + + +#endif // !_edoSamplerNormalMulti_h diff --git a/edo/src/edoSamplerUniform.h b/edo/src/edoSamplerUniform.h new file mode 100644 index 000000000..334daf36b --- /dev/null +++ b/edo/src/edoSamplerUniform.h @@ -0,0 +1,82 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoSamplerUniform_h +#define _edoSamplerUniform_h + +#include + +#include "edoSampler.h" +#include "edoUniform.h" + +/** + * This class uses the Uniform distribution parameters (bounds) to return + * a random position used for population sampling. + * + * Returns a random number in [min,max[ for each variable defined by the given + * distribution. + * + * Note: if the distribution given at call defines a min==max for one of the + * variable, the result will be the same number. + * + * @ingroup Samplers + */ +template < typename EOT, class D = edoUniform > +class edoSamplerUniform : public edoSampler< D > +{ +public: + typedef D Distrib; + + edoSamplerUniform( edoRepairer & repairer ) : edoSampler< D >( repairer) {} + + EOT sample( edoUniform< EOT >& distrib ) + { + unsigned int size = distrib.size(); + assert(size > 0); + + // Point we want to sample to get higher a set of points + // (coordinates in n dimension) + // x = {x1, x2, ..., xn} + EOT solution; + + // Sampling all dimensions + for (unsigned int i = 0; i < size; ++i) + { + double min = distrib.min()[i]; + double max = distrib.max()[i]; + double random = rng.uniform(min, max); + + assert( ( min == random && random == max ) || ( min <= random && random < max) ); // random in [ min, max [ + + solution.push_back(random); + } + + return solution; + } +}; + +#endif // !_edoSamplerUniform_h diff --git a/edo/src/edoUniform.h b/edo/src/edoUniform.h new file mode 100644 index 000000000..fa524d2db --- /dev/null +++ b/edo/src/edoUniform.h @@ -0,0 +1,49 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoUniform_h +#define _edoUniform_h + +#include "edoDistrib.h" +#include "edoVectorBounds.h" + +/** A uniform distribution. + * + * Defined by its bounds. + * + * @ingroup Distributions + */ +template < typename EOT > +class edoUniform : public edoDistrib< EOT >, public edoVectorBounds< EOT > +{ +public: + edoUniform(EOT min, EOT max) + : edoVectorBounds< EOT >(min, max) + {} +}; + +#endif // !_edoUniform_h diff --git a/edo/src/edoUniformCenter.h b/edo/src/edoUniformCenter.h new file mode 100644 index 000000000..d6e646f34 --- /dev/null +++ b/edo/src/edoUniformCenter.h @@ -0,0 +1,59 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoUniformCenter_h +#define _edoUniformCenter_h + +#include "edoModifierMass.h" +#include "edoUniform.h" + +/** Modify an edoUniform distribution by centering its bounds around a given EOT. + * + * @ingroup Modifiers + */ +template < typename EOT > +class edoUniformCenter : public edoModifierMass< edoUniform< EOT > > +{ +public: + typedef typename EOT::AtomType AtomType; + + void operator() ( edoUniform< EOT >& distrib, EOT& mass ) + { + for (unsigned int i = 0, n = mass.size(); i < n; ++i) + { + AtomType& min = distrib.min()[i]; + AtomType& max = distrib.max()[i]; + + AtomType range = (max - min) / 2; + + min = mass[i] - range; + max = mass[i] + range; + } + } +}; + +#endif // !_edoUniformCenter_h diff --git a/edo/src/edoVectorBounds.h b/edo/src/edoVectorBounds.h new file mode 100644 index 000000000..7d01bad4e --- /dev/null +++ b/edo/src/edoVectorBounds.h @@ -0,0 +1,58 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoVectorBounds_h +#define _edoVectorBounds_h + +/** A class that holds min and max bounds vectors. + */ +template < typename EOT > +class edoVectorBounds +{ +public: + edoVectorBounds(EOT min, EOT max) + : _min(min), _max(max) + { + assert(_min.size() > 0); + assert(_min.size() == _max.size()); + } + + EOT min(){return _min;} + EOT max(){return _max;} + + unsigned int size() + { + assert(_min.size() == _max.size()); + return _min.size(); + } + +private: + EOT _min; + EOT _max; +}; + +#endif // !_edoVectorBounds_h diff --git a/edo/src/utils/CMakeLists.txt b/edo/src/utils/CMakeLists.txt new file mode 100644 index 000000000..fdd552e29 --- /dev/null +++ b/edo/src/utils/CMakeLists.txt @@ -0,0 +1,21 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the target +###################################################################################### + +set(EDOUTILS_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${EDOUTILS_LIB_OUTPUT_PATH}) + +file(GLOB SOURCES *.cpp) +add_library(edoutils ${SOURCES}) +install(TARGETS edoutils ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +set(EDOUTILS_VERSION ${GLOBAL_VERSION}) +set_target_properties(edoutils PROPERTIES VERSION "${EDOUTILS_VERSION}") + diff --git a/edo/src/utils/edoCheckPoint.h b/edo/src/utils/edoCheckPoint.h new file mode 100644 index 000000000..5ba25ac1b --- /dev/null +++ b/edo/src/utils/edoCheckPoint.h @@ -0,0 +1,146 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoCheckPoint_h +#define _edoCheckPoint_h + +#include +#include + +#include "edoContinue.h" +#include "edoStat.h" + +//! eoCheckPoint< EOT > classe fitted to Distribution Object library + +template < typename D > +class edoCheckPoint : public edoContinue< D > +{ +public: + typedef typename D::EOType EOType; + + edoCheckPoint(edoContinue< D >& _cont) + { + _continuators.push_back( &_cont ); + } + + bool operator()(const D& distrib) + { + for ( unsigned int i = 0, size = _stats.size(); i < size; ++i ) + { + (*_stats[i])( distrib ); + } + + for ( unsigned int i = 0, size = _updaters.size(); i < size; ++i ) + { + (*_updaters[i])(); + } + + for ( unsigned int i = 0, size = _monitors.size(); i < size; ++i ) + { + (*_monitors[i])(); + } + + bool bContinue = true; + for ( unsigned int i = 0, size = _continuators.size(); i < size; ++i ) + { + if ( !(*_continuators[i])( distrib ) ) + { + bContinue = false; + } + } + + if ( !bContinue ) + { + for ( unsigned int i = 0, size = _stats.size(); i < size; ++i ) + { + _stats[i]->lastCall( distrib ); + } + + for ( unsigned int i = 0, size = _updaters.size(); i < size; ++i ) + { + _updaters[i]->lastCall(); + } + + for ( unsigned int i = 0, size = _monitors.size(); i < size; ++i ) + { + _monitors[i]->lastCall(); + } + } + + return bContinue; + } + + void add(edoContinue< D >& cont) { _continuators.push_back( &cont ); } + void add(edoStatBase< D >& stat) { _stats.push_back( &stat ); } + void add(eoMonitor& mon) { _monitors.push_back( &mon ); } + void add(eoUpdater& upd) { _updaters.push_back( &upd ); } + + virtual std::string className(void) const { return "edoCheckPoint"; } + + std::string allClassNames() const + { + std::string s("\n" + className() + "\n"); + + s += "Stats\n"; + for ( unsigned int i = 0, size = _stats.size(); i < size; ++i ) + { + s += _stats[i]->className() + "\n"; + } + s += "\n"; + + s += "Updaters\n"; + for ( unsigned int i = 0; i < _updaters.size(); ++i ) + { + s += _updaters[i]->className() + "\n"; + } + s += "\n"; + + s += "Monitors\n"; + for ( unsigned int i = 0; i < _monitors.size(); ++i ) + { + s += _monitors[i]->className() + "\n"; + } + s += "\n"; + + s += "Continuators\n"; + for ( unsigned int i = 0, size = _continuators.size(); i < size; ++i ) + { + s += _continuators[i]->className() + "\n"; + } + s += "\n"; + + return s; + } + +private: + std::vector< edoContinue< D >* > _continuators; + std::vector< edoStatBase< D >* > _stats; + std::vector< eoMonitor* > _monitors; + std::vector< eoUpdater* > _updaters; +}; + +#endif // !_edoCheckPoint_h diff --git a/edo/src/utils/edoCholesky.h b/edo/src/utils/edoCholesky.h new file mode 100644 index 000000000..fad067507 --- /dev/null +++ b/edo/src/utils/edoCholesky.h @@ -0,0 +1,295 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +namespace cholesky { + + +#ifdef WITH_BOOST + +/** Cholesky decomposition, given a matrix V, return a matrix L + * such as V = L L^T (L^T being the transposed of L). + * + * Need a symmetric and positive definite matrix as an input, which + * should be the case of a non-ill-conditionned covariance matrix. + * Thus, expect a (lower) triangular matrix. + */ +template< typename T > +class CholeskyBase +{ +public: + //! The covariance-matrix is symetric + typedef ublas::symmetric_matrix< T, ublas::lower > CovarMat; + + //! The factorization matrix is triangular + // FIXME check if triangular types behaviour is like having 0 + typedef ublas::matrix< T > FactorMat; + + /** Instanciate without computing anything, you are responsible of + * calling the algorithm and getting the result with operator() + * */ + CholeskyBase( size_t s1 = 1, size_t s2 = 1 ) : + _L(ublas::zero_matrix(s1,s2)) + {} + + /** Computation is made at instanciation and then cached in a member variable, + * use decomposition() to get the result. + */ + CholeskyBase(const CovarMat& V) : + _L(ublas::zero_matrix(V.size1(),V.size2())) + { + (*this)( V ); + } + + /** Compute the factorization and cache the result */ + virtual void factorize( const CovarMat& V ) = 0; + + /** Compute the factorization and return the result */ + virtual const FactorMat& operator()( const CovarMat& V ) + { + this->factorize( V ); + return decomposition(); + } + + //! The decomposition of the covariance matrix + const FactorMat & decomposition() const + { + return _L; + } + +protected: + + /** Assert that the covariance matrix have the required properties and returns its dimension. + * + * Note: if compiled with NDEBUG, will not assert anything and just return the dimension. + */ + unsigned assert_properties( const CovarMat& V ) + { + unsigned int Vl = V.size1(); // number of lines + + // the result goes in _L + _L = ublas::zero_matrix(Vl,Vl); + +#ifndef NDEBUG + assert(Vl > 0); + + unsigned int Vc = V.size2(); // number of columns + assert(Vc > 0); + assert( Vl == Vc ); + + // partial assert that V is semi-positive definite + // assert that all diagonal elements are positives + for( unsigned int i=0; i < Vl; ++i ) { + assert( V(i,i) > 0 ); + } + + /* FIXME what is the more efficient way to check semi-positive definite? Candidates are: + * perform the cholesky factorization + * check if all eigenvalues are positives + * check if all of the leading principal minors are positive + */ +#endif + + return Vl; + } + + //! The decomposition is a (lower) symetric matrix, just like the covariance matrix + FactorMat _L; +}; + + +/** This standard algorithm makes use of square root and is thus subject + * to round-off errors if the covariance matrix is very ill-conditioned. + * + * Compute L such that V = L L^T + * + * When compiled in debug mode and called on ill-conditionned matrix, + * will raise an assert before calling the square root on a negative number. + */ +template< typename T > +class CholeskyLLT : public CholeskyBase +{ +public: + virtual void factorize( const typename CholeskyBase::CovarMat& V ) + { + unsigned int N = assert_properties( V ); + + unsigned int i=0, j=0, k; + this->_L(0, 0) = sqrt( V(0, 0) ); + + // end of the column + for ( j = 1; j < N; ++j ) { + this->_L(j, 0) = V(0, j) / this->_L(0, 0); + } + + // end of the matrix + for ( i = 1; i < N; ++i ) { // each column + // diagonal + double sum = 0.0; + for ( k = 0; k < i; ++k) { + sum += this->_L(i, k) * this->_L(i, k); + } + + this->_L(i,i) = L_i_i( V, i, sum ); + + for ( j = i + 1; j < N; ++j ) { // rows + // one element + sum = 0.0; + for ( k = 0; k < i; ++k ) { + sum += this->_L(j, k) * this->_L(i, k); + } + + this->_L(j, i) = (V(j, i) - sum) / this->_L(i, i); + + } // for j in ]i,N[ + } // for i in [1,N[ + } + + + /** The step of the standard LLT algorithm where round off errors may appear */ + inline virtual T L_i_i( const typename CholeskyBase::CovarMat& V, const unsigned int& i, const double& sum ) const + { + // round-off errors may appear here + assert( V(i,i) - sum >= 0 ); + return sqrt( V(i,i) - sum ); + } +}; + + +/** This standard algorithm makes use of square root but do not fail + * if the covariance matrix is very ill-conditioned. + * Here, we propagate the error by using the absolute value before + * computing the square root. + * + * Be aware that this increase round-off errors, this is just a ugly + * hack to avoid crash. + */ +template< typename T > +class CholeskyLLTabs : public CholeskyLLT +{ +public: + inline virtual T L_i_i( const typename CholeskyBase::CovarMat& V, const unsigned int& i, const double& sum ) const + { + /***** ugly hack *****/ + return sqrt( fabs( V(i,i) - sum) ); + } +}; + + +/** This standard algorithm makes use of square root but do not fail + * if the covariance matrix is very ill-conditioned. + * Here, if the diagonal difference ir negative, we set it to zero. + * + * Be aware that this increase round-off errors, this is just a ugly + * hack to avoid crash. + */ +template< typename T > +class CholeskyLLTzero : public CholeskyLLT +{ +public: + inline virtual T L_i_i( const typename CholeskyBase::CovarMat& V, const unsigned int& i, const double& sum ) const + { + T Lii; + if( V(i,i) - sum >= 0 ) { + Lii = sqrt( V(i,i) - sum); + } else { + /***** ugly hack *****/ + Lii = 0; + } + return Lii; + } +}; + + +/** This alternative algorithm do not use square root in an inner loop, + * but only for some diagonal elements of the matrix D. + * + * Computes L and D such as V = L D L^T. + * The factorized matrix is (L D^1/2), because V = (L D^1/2) (L D^1/2)^T + */ +template< typename T > +class CholeskyLDLT : public CholeskyBase +{ +public: + virtual void factorize( const typename CholeskyBase::CovarMat& V ) + { + // use "int" everywhere, because of the "j-1" operation + int N = assert_properties( V ); + // example of an invertible matrix whose decomposition is undefined + assert( V(0,0) != 0 ); + + typename CholeskyBase::FactorMat L = ublas::zero_matrix(N,N); + typename CholeskyBase::FactorMat D = ublas::zero_matrix(N,N); + D(0,0) = V(0,0); + + for( int j=0; j_L = root( L, D ); + } + + + inline typename CholeskyBase::FactorMat root( typename CholeskyBase::FactorMat& L, typename CholeskyBase::FactorMat& D ) + { + // now compute the final symetric matrix: this->_L = L D^1/2 + // remember that V = ( L D^1/2) ( L D^1/2)^T + + // fortunately, the square root of a diagonal matrix is the square + // root of all its elements + typename CholeskyBase::FactorMat sqrt_D = D; + for( int i=0; i < D.size1(); ++i) { + sqrt_D(i,i) = sqrt(D(i,i)); + } + + // the factorization is thus this->_L*D^1/2 + return ublas::prod( L, sqrt_D ); + } +}; + +#else +#ifdef WITH_EIGEN + +#endif // WITH_EIGEN +#endif // WITH_BOOST + + +} // namespace cholesky diff --git a/edo/src/utils/edoFileSnapshot.cpp b/edo/src/utils/edoFileSnapshot.cpp new file mode 100644 index 000000000..1860ac0f1 --- /dev/null +++ b/edo/src/utils/edoFileSnapshot.cpp @@ -0,0 +1,141 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001 +Copyright (C) 2010 Thales group +*/ +/* +Authors: + todos@geneura.ugr.es + Marc Schoenauer + Martin Keijzer + Johann Dréo + Caner Candan +*/ + +#include + +#include +#include +#include + +#include +#include +#include + +edoFileSnapshot::edoFileSnapshot(std::string dirname, + unsigned int frequency /*= 1*/, + std::string filename /*= "gen"*/, + std::string delim /*= " "*/, + unsigned int counter /*= 0*/, + bool rmFiles /*= true*/, + bool saveFilenames /*= true*/) + : _dirname(dirname), _frequency(frequency), + _filename(filename), _delim(delim), + _counter(counter), _saveFilenames(saveFilenames), + _descOfFiles( NULL ), _boolChanged(true) +{ + std::string s = "test -d " + _dirname; + + int res = system(s.c_str()); + + // test for (unlikely) errors + + if ( (res == -1) || (res == 127) ) + { + throw std::runtime_error("Problem executing test of dir in eoFileSnapshot"); + } + + // now make sure there is a dir without any genXXX file in it + if (res) // no dir present + { + s = std::string("mkdir ") + _dirname; + } + else if (!res && rmFiles) + { + s = std::string("/bin/rm -f ") + _dirname+ "/" + _filename + "*"; + } + else + { + s = " "; + } + + int dummy; + dummy = system(s.c_str()); + // all done + + _descOfFiles = new std::ofstream( std::string(dirname + "/list_of_files.txt").c_str() ); + +} + +edoFileSnapshot::~edoFileSnapshot() +{ + delete _descOfFiles; +} + +void edoFileSnapshot::setCurrentFileName() +{ + std::ostringstream oscount; + oscount << _counter; + _currentFileName = _dirname + "/" + _filename + oscount.str(); +} + +eoMonitor& edoFileSnapshot::operator()(void) +{ + if (_counter % _frequency) + { + _boolChanged = false; // subclass with gnuplot will do nothing + _counter++; + return (*this); + } + _counter++; + _boolChanged = true; + setCurrentFileName(); + + std::ofstream os(_currentFileName.c_str()); + + if (!os) + { + std::string str = "edoFileSnapshot: Could not open " + _currentFileName; + throw std::runtime_error(str); + } + + if ( _saveFilenames ) + { + *_descOfFiles << _currentFileName.c_str() << std::endl; + } + + return operator()(os); +} + +eoMonitor& edoFileSnapshot::operator()(std::ostream& os) +{ + iterator it = vec.begin(); + + os << (*it)->getValue(); + + for ( ++it; it != vec.end(); ++it ) + { + os << _delim.c_str() << (*it)->getValue(); + } + + os << '\n'; + + return *this; +} diff --git a/edo/src/utils/edoFileSnapshot.h b/edo/src/utils/edoFileSnapshot.h new file mode 100644 index 000000000..7f157f321 --- /dev/null +++ b/edo/src/utils/edoFileSnapshot.h @@ -0,0 +1,81 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001 +Copyright (C) 2010 Thales group +*/ +/* +Authors: + todos@geneura.ugr.es + Marc Schoenauer + Martin Keijzer + Johann Dréo + Caner Candan +*/ + +#ifndef _edoFileSnapshot_h +#define _edoFileSnapshot_h + +#include +#include +#include + +#include "utils/eoMonitor.h" + +//! edoFileSnapshot + +class edoFileSnapshot : public eoMonitor +{ +public: + + edoFileSnapshot(std::string dirname, + unsigned int frequency = 1, + std::string filename = "gen", + std::string delim = " ", + unsigned int counter = 0, + bool rmFiles = true, + bool saveFilenames = true); + + virtual ~edoFileSnapshot(); + + virtual bool hasChanged() {return _boolChanged;} + virtual std::string getDirName() { return _dirname; } + virtual unsigned int getCounter() { return _counter; } + virtual const std::string baseFileName() { return _filename;} + std::string getFileName() {return _currentFileName;} + + void setCurrentFileName(); + + virtual eoMonitor& operator()(void); + + virtual eoMonitor& operator()(std::ostream& os); + +private : + std::string _dirname; + unsigned int _frequency; + std::string _filename; + std::string _delim; + std::string _currentFileName; + unsigned int _counter; + bool _saveFilenames; + std::ofstream* _descOfFiles; + bool _boolChanged; +}; + +#endif // !_edoFileSnapshot diff --git a/edo/src/utils/edoHyperVolume.h b/edo/src/utils/edoHyperVolume.h new file mode 100644 index 000000000..2ef73708b --- /dev/null +++ b/edo/src/utils/edoHyperVolume.h @@ -0,0 +1,54 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoHyperVolume_h +#define _edoHyperVolume_h + +//! edoHyperVolume + +template < typename EOT > +class edoHyperVolume +{ +public: + typedef typename EOT::AtomType AtomType; + + edoHyperVolume() : _hv(1) {} + + void update(AtomType v) + { + _hv *= ::sqrt( v ); + + assert( _hv <= std::numeric_limits< AtomType >::max() ); + } + + AtomType get_hypervolume() const { return _hv; } + +protected: + AtomType _hv; +}; + +#endif // !_edoHyperVolume_h diff --git a/edo/src/utils/edoPopStat.h b/edo/src/utils/edoPopStat.h new file mode 100644 index 000000000..4d5c9f10c --- /dev/null +++ b/edo/src/utils/edoPopStat.h @@ -0,0 +1,70 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001 +Copyright (C) 2010 Thales group +*/ +/* +Authors: + todos@geneura.ugr.es + Marc Schoenauer + Martin Keijzer + Johann Dréo + Caner Candan +*/ + +#ifndef _edoPopStat_h +#define _edoPopStat_h + +#include + + +/** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats. +This snippet is a workaround: +This class will "print" a whole population into a std::string - that you can later +send to any stream +This is the plain version - see eoPopString for the Sorted version + +Note: this Stat should probably be used only within eoStdOutMonitor, and not +inside an eoFileMonitor, as the eoState construct will work much better there. +*/ +template +class edoPopStat : public eoStat +{ +public: + + using eoStat::value; + + /** default Ctor, void std::string by default, as it appears + on the description line once at beginning of evolution. and + is meaningless there. _howMany defaults to 0, that is, the whole + population*/ + edoPopStat(std::string _desc ="") + : eoStat("", _desc) {} + + /** Fills the value() of the eoParam with the dump of the population. */ + void operator()(const eoPop& _pop) + { + std::ostringstream os; + os << _pop; + value() = os.str(); + } +}; + +#endif // !_edoPopStat_h diff --git a/edo/src/utils/edoStat.h b/edo/src/utils/edoStat.h new file mode 100644 index 000000000..233101323 --- /dev/null +++ b/edo/src/utils/edoStat.h @@ -0,0 +1,76 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoStat_h +#define _edoStat_h + +#include + +//! edoStatBase< D > + +template < typename D > +class edoStatBase : public eoUF< const D&, void > +{ +public: + // virtual void operator()( const D& ) = 0 (provided by eoUF< A1, R >) + + virtual void lastCall( const D& ) {} + virtual std::string className() const { return "edoStatBase"; } +}; + +template < typename D > class edoCheckPoint; + +template < typename D, typename T > +class edoStat : public eoValueParam< T >, public edoStatBase< D > +{ +public: + edoStat(T value, std::string description) + : eoValueParam< T >(value, description) + {} + + virtual std::string className(void) const { return "edoStat"; } + + edoStat< D, T >& addTo(edoCheckPoint< D >& cp) { cp.add(*this); return *this; } + + // TODO: edoStat< D, T >& addTo(eoMonitor& mon) { mon.add(*this); return *this; } +}; + + +//! A parent class for any kind of distribution to dump parameter to std::string type + +template < typename D > +class edoDistribStat : public edoStat< D, std::string > +{ +public: + using edoStat< D, std::string >::value; + + edoDistribStat(std::string desc) + : edoStat< D, std::string >("", desc) + {} +}; + +#endif // !_edoStat_h diff --git a/edo/src/utils/edoStatNormalMono.h b/edo/src/utils/edoStatNormalMono.h new file mode 100644 index 000000000..87705a0b0 --- /dev/null +++ b/edo/src/utils/edoStatNormalMono.h @@ -0,0 +1,57 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoStatNormalMono_h +#define _edoStatNormalMono_h + +#include "edoStat.h" +#include "edoNormalMono.h" + +//! edoStatNormalMono< EOT > + +template < typename EOT > +class edoStatNormalMono : public edoDistribStat< edoNormalMono< EOT > > +{ +public: + using edoDistribStat< edoNormalMono< EOT > >::value; + + edoStatNormalMono( std::string desc = "" ) + : edoDistribStat< edoNormalMono< EOT > >( desc ) + {} + + void operator()( const edoNormalMono< EOT >& distrib ) + { + value() = "\n# ====== mono normal distribution dump =====\n"; + + std::ostringstream os; + os << distrib.mean() << " " << distrib.variance() << std::endl; + + value() += os.str(); + } +}; + +#endif // !_edoStatNormalMono_h diff --git a/edo/src/utils/edoStatNormalMulti.h b/edo/src/utils/edoStatNormalMulti.h new file mode 100644 index 000000000..961fd7cba --- /dev/null +++ b/edo/src/utils/edoStatNormalMulti.h @@ -0,0 +1,82 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoStatNormalMulti_h +#define _edoStatNormalMulti_h + +#include + +#include "edoStat.h" +#include "../edoNormalMulti.h" + +#ifdef WITH_BOOST + +#include + +#else +#ifdef WITH_EIGEN + + // include nothing + +#endif // WITH_EIGEN +#endif // WITH_BOOST + +//! edoStatNormalMulti< EOT > +template < typename EOT > +class edoStatNormalMulti : public edoDistribStat< edoNormalMulti< EOT > > +{ +public: + // typedef typename EOT::AtomType AtomType; + + using edoDistribStat< edoNormalMulti< EOT > >::value; + + edoStatNormalMulti( std::string desc = "" ) + : edoDistribStat< edoNormalMulti< EOT > >( desc ) + {} + + void operator()( const edoNormalMulti< EOT >& distrib ) + { + value() = "\n# ====== multi normal distribution dump =====\n"; + + std::ostringstream os; + + os << distrib.mean() << std::endl << std::endl << distrib.varcovar() << std::endl; + + // ublas::vector< AtomType > mean = distrib.mean(); + // std::copy(mean.begin(), mean.end(), std::ostream_iterator< std::string >( os, " " )); + + // ublas::symmetric_matrix< AtomType, ublas::lower > varcovar = distrib.varcovar(); + // std::copy(varcovar.begin(), varcovar.end(), std::ostream_iterator< std::string >( os, " " )); + + // os << std::endl; + + value() += os.str(); + } +}; + + +#endif // !_edoStatNormalMulti_h diff --git a/edo/src/utils/edoStatUniform.h b/edo/src/utils/edoStatUniform.h new file mode 100644 index 000000000..c0fa79352 --- /dev/null +++ b/edo/src/utils/edoStatUniform.h @@ -0,0 +1,57 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#ifndef _edoStatUniform_h +#define _edoStatUniform_h + +#include "edoStat.h" +#include "edoUniform.h" + +//! edoStatUniform< EOT > + +template < typename EOT > +class edoStatUniform : public edoDistribStat< edoUniform< EOT > > +{ +public: + using edoDistribStat< edoUniform< EOT > >::value; + + edoStatUniform( std::string desc = "" ) + : edoDistribStat< edoUniform< EOT > >( desc ) + {} + + void operator()( const edoUniform< EOT >& distrib ) + { + value() = "\n# ====== uniform distribution dump =====\n"; + + std::ostringstream os; + os << distrib.min() << " " << distrib.max() << std::endl; + + value() += os.str(); + } +}; + +#endif // !_edoStatUniform_h diff --git a/edo/test/CMakeLists.txt b/edo/test/CMakeLists.txt new file mode 100644 index 000000000..0d98852fe --- /dev/null +++ b/edo/test/CMakeLists.txt @@ -0,0 +1,56 @@ +############################################################################### +## +## CMakeLists file for unit test +## +############################################################################### + + +###################################################################################### +### 1) Include the sources +###################################################################################### + +###################################################################################### + + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +###################################################################################### + + +###################################################################################### +### 3) Define your targets and link the librairies +###################################################################################### + +find_package(Boost 1.33.0) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +include_directories(${Boost_INCLUDE_DIRS}) +link_directories(${Boost_LIBRARY_DIRS}) + +include_directories(${CMAKE_SOURCE_DIR}/application/common) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EDO_SRC_DIR}/src) + +set(SOURCES + #t-cholesky + t-variance + t-edoEstimatorNormalMulti + t-mean-distance + t-bounderno + t-uniform + t-continue + t-dispatcher-round + t-repairer-modulo + ) + +foreach(current ${SOURCES}) + add_executable(${current} ${current}.cpp) + add_test(${current} ${current}) + target_link_libraries(${current} eo eoutils edoutils ${Boost_LIBRARIES}) + install(TARGETS ${current} RUNTIME DESTINATION share/edo/test COMPONENT test) +endforeach() + +###################################################################################### diff --git a/edo/test/boxplot.py b/edo/test/boxplot.py new file mode 100755 index 000000000..3e10e4066 --- /dev/null +++ b/edo/test/boxplot.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python + +from pylab import * + +FILE_LOCATIONS = 'means_distances_results/files_description.txt' + +data = [] + +locations = [ line.split()[0] for line in open( FILE_LOCATIONS ) ] + +for cur_file in locations: + data.append( [ float(line.split()[7]) for line in open( cur_file ).readlines() ] ) + +print locations +#print data + +boxplot( data ) + +show() diff --git a/edo/test/t-bounderno.cpp b/edo/test/t-bounderno.cpp new file mode 100644 index 000000000..ac294ce7d --- /dev/null +++ b/edo/test/t-bounderno.cpp @@ -0,0 +1,40 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#include +#include + +#include "Rosenbrock.h" + +typedef eoReal< eoMinimizingFitness > EOT; + +int main(void) +{ + edoBounderNo< EOT > bounder; + + return 0; +} diff --git a/edo/test/t-cholesky.cpp b/edo/test/t-cholesky.cpp new file mode 100644 index 000000000..b141e6e48 --- /dev/null +++ b/edo/test/t-cholesky.cpp @@ -0,0 +1,250 @@ + +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo +*/ + +//#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +typedef eoReal< eoMinimizingFitness > EOT; +typedef edoNormalMulti EOD; + + +void setformat( std::ostream& out ) +{ + out << std::right; + out << std::setfill(' '); + out << std::setw( 5 + std::numeric_limits::digits10); + out << std::setprecision(std::numeric_limits::digits10); + out << std::setiosflags(std::ios_base::showpoint); +} + + +template +std::string format(const MT& mat ) +{ + std::ostringstream out; + setformat(out); + + for( unsigned int i=0; i +T round( T val, T prec = 1.0 ) +{ + return (val > 0.0) ? + floor(val * prec + 0.5) / prec : + ceil(val * prec - 0.5) / prec ; +} + + +template +bool equal( const MT& M1, const MT& M2, double prec /* = 1/std::numeric_limits::digits10 ???*/ ) +{ + if( M1.size1() != M2.size1() || M1.size2() != M2.size2() ) { + return false; + } + + for( unsigned int i=0; i= 4 ) { +// precision = std::atof(argv[3]); +// } +// std::cout << "precision = " << precision << std::endl; +// std::cout << "usage: t-cholesky [N] [precision]" << std::endl; +// std::cout << "N = " << N << std::endl; +// std::cout << "precision = " << precision << std::endl; +// std::string linesep = "--------------------------------------------------------------------------------------------"; +// std::cout << linesep << std::endl; +// +// setformat(std::cout); +// +// std::cout << "Covariance matrix" << std::endl << format(V) << std::endl; +// std::cout << linesep << std::endl; +// +// edoSamplerNormalMulti::Cholesky LLT( edoSamplerNormalMulti::Cholesky::standard ); +// FactorMat L0 = LLT(V); +// CovarMat V0 = ublas::prod( L0, ublas::trans(L0) ); +// CovarMat E0 = error(V,V0); +// std::cout << "LLT" << std::endl << format(E0) << std::endl; +// std::cout << trigsum(E0) << std::endl; +// std::cout << "LLT" << std::endl << format(L0) << std::endl; +// std::cout << "LLT covar" << std::endl << format(V0) << std::endl; +// assert( equal(V0,V,precision) ); +// std::cout << linesep << std::endl; +// +// edoSamplerNormalMulti::Cholesky LLTa( edoSamplerNormalMulti::Cholesky::absolute ); +// FactorMat L1 = LLTa(V); +// CovarMat V1 = ublas::prod( L1, ublas::trans(L1) ); +// CovarMat E1 = error(V,V1); +// std::cout << "LLT abs" << std::endl << format(E1) << std::endl; +// std::cout << trigsum(E1) << std::endl; +// std::cout << "LLT abs" << std::endl << format(L1) << std::endl; +// std::cout << "LLT covar" << std::endl << format(V1) << std::endl; +// assert( equal(V1,V,precision) ); +// std::cout << linesep << std::endl; +// +// edoSamplerNormalMulti::Cholesky LDLT( edoSamplerNormalMulti::Cholesky::robust ); +// FactorMat L2 = LDLT(V); +// CovarMat V2 = ublas::prod( L2, ublas::trans(L2) ); +// CovarMat E2 = error(V,V2); +// std::cout << "LDLT" << std::endl << format(E2) << std::endl; +// std::cout << trigsum(E2) << std::endl; +// std::cout << "LDLT" << std::endl << format(L2) << std::endl; +// std::cout << "LDLT covar" << std::endl << format(V2) << std::endl; +// assert( equal(V2,V,precision) ); +// std::cout << linesep << std::endl; + +} diff --git a/edo/test/t-continue.cpp b/edo/test/t-continue.cpp new file mode 100644 index 000000000..2f2bd3247 --- /dev/null +++ b/edo/test/t-continue.cpp @@ -0,0 +1,44 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#include +#include + +#include "Rosenbrock.h" + +typedef eoReal< eoMinimizingFitness > EOT; +typedef edoUniform< EOT > Distrib; + +int main(void) +{ + eoState state; + + edoContinue< Distrib >* continuator = new edoDummyContinue< Distrib >(); + state.storeFunctor(continuator); + + return 0; +} diff --git a/edo/test/t-dispatcher-round.cpp b/edo/test/t-dispatcher-round.cpp new file mode 100644 index 000000000..cfcd9261c --- /dev/null +++ b/edo/test/t-dispatcher-round.cpp @@ -0,0 +1,81 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Pierre Savéant +*/ + +#include +#include +#include + +typedef eoReal< eoMinimizingFitness > EOT; + +int main(void) +{ + EOT sol; + sol.push_back(1.1); + sol.push_back(1.1); + sol.push_back(3.9); + sol.push_back(3.9); + sol.push_back(5.4); + sol.push_back(5.6); + sol.push_back(7.011); + sol.push_back(8.09); + sol.push_back(8.21); + + std::cout << "expect: INVALID 9 1 2 3 4 5 6 7 8.1 8.2" << std::endl; + + edoRepairer* rep1 = new edoRepairerFloor(); + edoRepairer* rep2 = new edoRepairerCeil(); + edoRepairer* rep3 = new edoRepairerRound(); + edoRepairer* rep4 = new edoRepairerRoundDecimals( 10 ); + + std::vector indexes1; + indexes1.push_back(0); + indexes1.push_back(2); + + std::vector indexes2; + indexes2.push_back(1); + indexes2.push_back(3); + + std::vector indexes3; + indexes3.push_back(4); + indexes3.push_back(5); + + std::vector indexes4; + indexes4.push_back(6); + indexes4.push_back(7); + indexes4.push_back(8); + + edoRepairerDispatcher repare( indexes1, rep1 ); + repare.add( indexes2, rep2 ); + repare.add( indexes3, rep3 ); + repare.add( indexes4, rep4 ); + + repare(sol); + + std::cout << sol << std::endl; + + return 0; +} diff --git a/edo/test/t-edoEstimatorNormalMulti.cpp b/edo/test/t-edoEstimatorNormalMulti.cpp new file mode 100644 index 000000000..6483a1062 --- /dev/null +++ b/edo/test/t-edoEstimatorNormalMulti.cpp @@ -0,0 +1,199 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#include +#include + +#include +//#include + +#include + +#include "Rosenbrock.h" +#include "Sphere.h" + +typedef eoReal< eoMinimizingFitness > EOT; +typedef edoNormalMulti< EOT > Distrib; +typedef EOT::AtomType AtomType; + +#ifdef WITH_BOOST +#include +#include + typedef ublas::vector< AtomType > Vector; + typedef ublas::symmetric_matrix< AtomType, ublas::lower > Matrix; +#else +#ifdef WITH_EIGEN +#include + typedef edoNormalMulti::Vector Vector; + typedef edoNormalMulti::Matrix Matrix; +#endif +#endif + +int main(int ac, char** av) +{ + // (0) parser + eo routines + eoParser parser(ac, av); + + std::string section("Algorithm parameters"); + + unsigned int p_size = parser.createParam((unsigned int)100, "popSize", "Population Size", 'P', section).value(); // P + unsigned int s_size = parser.createParam((unsigned int)2, "dimension-size", "Dimension size", 'd', section).value(); // d + AtomType mean_value = parser.createParam((AtomType)0, "mean", "Mean value", 'm', section).value(); // m + AtomType covar1_value = parser.createParam((AtomType)1.0, "covar1", "Covar value 1", '1', section).value(); + AtomType covar2_value = parser.createParam((AtomType)0.5, "covar2", "Covar value 2", '2', section).value(); + AtomType covar3_value = parser.createParam((AtomType)1.0, "covar3", "Covar value 3", '3', section).value(); + + std::ostringstream ss; + ss << p_size << "_" << std::fixed << std::setprecision(1) + << mean_value << "_" << covar1_value << "_" << covar2_value << "_" + << covar3_value << "_gen"; + std::string gen_filename = ss.str(); + + if( parser.userNeedsHelp() ) { + parser.printHelp(std::cout); + exit(1); + } + + make_verbose(parser); + make_help(parser); + + assert(p_size > 0); + assert(s_size > 0); + + eoState state; + + // (1) Population init and sampler + eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); + state.storeFunctor(gen); + + eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( s_size, *gen ); + state.storeFunctor(init); + + // create an empty pop and let the state handle the memory + // fill population thanks to eoInit instance + eoPop< EOT >& pop = state.takeOwnership( eoPop< EOT >( p_size, *init ) ); + + // (2) distribution initial parameters + Vector mean( s_size ); + + for (unsigned int i = 0; i < s_size; ++i) { + mean( i ) = mean_value; + } + + Matrix varcovar( s_size, s_size ); + + varcovar( 0, 0 ) = covar1_value; + varcovar( 0, 1 ) = covar2_value; + varcovar( 1, 1 ) = covar3_value; + + Distrib distrib( mean, varcovar ); + + // (3a) distribution output preparation + edoDummyContinue< Distrib >* distrib_dummy_continue = new edoDummyContinue< Distrib >(); + state.storeFunctor(distrib_dummy_continue); + + edoCheckPoint< Distrib >* distrib_continue = new edoCheckPoint< Distrib >( *distrib_dummy_continue ); + state.storeFunctor(distrib_continue); + + edoDistribStat< Distrib >* distrib_stat = new edoStatNormalMulti< EOT >(); + state.storeFunctor(distrib_stat); + + distrib_continue->add( *distrib_stat ); + + edoFileSnapshot* distrib_file_snapshot = new edoFileSnapshot( "TestResDistrib", 1, gen_filename ); + state.storeFunctor(distrib_file_snapshot); + distrib_file_snapshot->add(*distrib_stat); + distrib_continue->add(*distrib_file_snapshot); + + // (3b) distribution output + (*distrib_continue)( distrib ); + + // Prepare bounder class to set bounds of sampling. + // This is used by edoSampler. + edoBounder< EOT >* bounder = new edoBounderRng< EOT >( + EOT(pop[0].size(), -5), EOT(pop[0].size(), 5), *gen + ); + state.storeFunctor(bounder); + + // Prepare sampler class with a specific distribution + edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder ); + state.storeFunctor(sampler); + + // (4) sampling phase + pop.clear(); + + for( unsigned int i = 0; i < p_size; ++i ) { + EOT candidate_solution = (*sampler)( distrib ); + pop.push_back( candidate_solution ); + } + + // (5) population output + eoContinue< EOT >* pop_cont = new eoGenContinue< EOT >( 2 ); // never reached fitness + state.storeFunctor(pop_cont); + + eoCheckPoint< EOT >* pop_continue = new eoCheckPoint< EOT >( *pop_cont ); + state.storeFunctor(pop_continue); + + edoPopStat< EOT >* pop_stat = new edoPopStat; + state.storeFunctor(pop_stat); + pop_continue->add(*pop_stat); + + edoFileSnapshot* pop_file_snapshot = new edoFileSnapshot( "TestResPop", 1, gen_filename ); + state.storeFunctor(pop_file_snapshot); + pop_file_snapshot->add(*pop_stat); + pop_continue->add(*pop_file_snapshot); + + (*pop_continue)( pop ); + + // (6) estimation phase + edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >(); + state.storeFunctor(estimator); + + distrib = (*estimator)( pop ); + + // (7) distribution output + (*distrib_continue)( distrib ); + + // (8) euclidianne distance estimation + Vector new_mean = distrib.mean(); + Matrix new_varcovar = distrib.varcovar(); + + AtomType distance = 0; + for( unsigned int d = 0; d < s_size; ++d ) { + distance += pow( mean[ d ] - new_mean[ d ], 2 ); + } + + distance = sqrt( distance ); + + eo::log << eo::logging + << "mean: " << mean << std::endl + << "new mean: " << new_mean << std::endl + << "distance: " << distance << std::endl + ; + + return 0; +} diff --git a/edo/test/t-mean-distance.cpp b/edo/test/t-mean-distance.cpp new file mode 100644 index 000000000..59b1c8aa5 --- /dev/null +++ b/edo/test/t-mean-distance.cpp @@ -0,0 +1,243 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#include +#include + +#include +#include +#include + +#include +//#include + +#include + + +#include "Rosenbrock.h" +#include "Sphere.h" + +typedef eoReal< eoMinimizingFitness > EOT; +typedef edoNormalMulti< EOT > Distrib; +typedef EOT::AtomType AtomType; + +#ifdef WITH_BOOST +#include +#include + typedef ublas::vector< AtomType > Vector; + typedef ublas::symmetric_matrix< AtomType, ublas::lower > Matrix; +#else +#ifdef WITH_EIGEN +#include + typedef edoNormalMulti::Vector Vector; + typedef edoNormalMulti::Matrix Matrix; +#endif +#endif + +int main(int ac, char** av) +{ + // (0) parser + eo routines + eoParser parser(ac, av); + + std::string section("Algorithm parameters"); + + unsigned int r_max = parser.createParam((unsigned int)100, "run-number", "Number of run", 'r', section).value(); // r + unsigned int p_min = parser.createParam((unsigned int)10, "population-min", "Population min", 'p', section).value(); // p + unsigned int p_max = parser.createParam((unsigned int)1000, "population-max", "Population max", 'P', section).value(); // P + unsigned int p_step = parser.createParam((unsigned int)50, "population-step", "Population step", 't', section).value(); // t + unsigned int s_size = parser.createParam((unsigned int)2, "dimension-size", "Dimension size", 'd', section).value(); // d + + AtomType mean_value = parser.createParam((AtomType)0, "mean", "Mean value", 'm', section).value(); // m + AtomType covar1_value = parser.createParam((AtomType)1.0, "covar1", "Covar value 1", '1', section).value(); // 1 + AtomType covar2_value = parser.createParam((AtomType)0.5, "covar2", "Covar value 2", '2', section).value(); // 2 + AtomType covar3_value = parser.createParam((AtomType)1.0, "covar3", "Covar value 3", '3', section).value(); // 3 + + std::string results_directory = parser.createParam((std::string)"means_distances_results", "results-directory", "Results directory", 'R', section).value(); // R + std::string files_description = parser.createParam((std::string)"files_description.txt", "files-description", "Files description", 'F', section).value(); // F + + if (parser.userNeedsHelp()) + { + parser.printHelp(std::cout); + exit(1); + } + + make_verbose(parser); + make_help(parser); + + + + assert(r_max >= 1); + assert(s_size >= 2); + + eo::log << eo::quiet; + + ::mkdir( results_directory.c_str(), 0755 ); + + for ( unsigned int p_size = p_min; p_size <= p_max; p_size += p_step ) + { + assert(p_size >= p_min); + + std::ostringstream desc_file; + desc_file << results_directory << "/" << files_description; + + std::ostringstream cur_file; + cur_file << results_directory << "/pop_" << p_size << ".txt"; + + eo::log << eo::file( desc_file.str() ) << cur_file.str().c_str() << std::endl; + + eo::log << eo::file( cur_file.str() ); + + eo::log << eo::logging << "run_number p_size s_size mean(0) mean(1) new-mean(0) new-mean(1) distance" << std::endl; + + eo::log << eo::quiet; + + for ( unsigned int r = 1; r <= r_max; ++r) + { + + eoState state; + + + + // (1) Population init and sampler + + + eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); + state.storeFunctor(gen); + + eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( s_size, *gen ); + state.storeFunctor(init); + + // create an empty pop and let the state handle the memory + // fill population thanks to eoInit instance + eoPop< EOT >& pop = state.takeOwnership( eoPop< EOT >( p_size, *init ) ); + + + + + + // (2) distribution initial parameters + + +#ifdef WITH_BOOST + Vector mean( s_size, mean_value ); +#else +#ifdef WITH_EIGEN + Vector mean( s_size ); + mean = Vector::Constant( s_size, mean_value); +#endif +#endif + Matrix varcovar( s_size, s_size ); + + varcovar( 0, 0 ) = covar1_value; + varcovar( 0, 1 ) = covar2_value; + varcovar( 1, 1 ) = covar3_value; + + Distrib distrib( mean, varcovar ); + + + + + + // Prepare bounder class to set bounds of sampling. + // This is used by edoSampler. + + + edoBounder< EOT >* bounder = new edoBounderRng< EOT >(EOT(pop[0].size(), -5), + EOT(pop[0].size(), 5), + *gen); + state.storeFunctor(bounder); + + + + + + // Prepare sampler class with a specific distribution + + + edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder ); + state.storeFunctor(sampler); + + + + + + // (4) sampling phase + + + pop.clear(); + + for (unsigned int i = 0; i < p_size; ++i) + { + EOT candidate_solution = (*sampler)( distrib ); + pop.push_back( candidate_solution ); + } + + + + + + // (6) estimation phase + + + edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >(); + state.storeFunctor(estimator); + + distrib = (*estimator)( pop ); + + + + + + // (8) euclidianne distance estimation + + + Vector new_mean = distrib.mean(); + Matrix new_varcovar = distrib.varcovar(); + + AtomType distance = 0; + + for ( unsigned int d = 0; d < s_size; ++d ) + { + distance += pow( mean[ d ] - new_mean[ d ], 2 ); + } + + distance = sqrt( distance ); + + eo::log << r << " " << p_size << " " << s_size << " " + << mean(0) << " " << mean(1) << " " + << new_mean(0) << " " << new_mean(1) << " " + << distance << std::endl + ; + + + + } + + } + + return 0; +} diff --git a/edo/test/t-repairer-modulo.cpp b/edo/test/t-repairer-modulo.cpp new file mode 100644 index 000000000..7a495f318 --- /dev/null +++ b/edo/test/t-repairer-modulo.cpp @@ -0,0 +1,55 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo +*/ + +#define _USE_MATH_DEFINES +#include + +#include +#include +#include + +typedef eoReal< eoMinimizingFitness > EOT; + +int main(void) +{ + EOT sol; + sol.push_back( M_PI * 1 ); + sol.push_back( M_PI * 2 ); + sol.push_back( M_PI * 3 ); + sol.push_back( M_PI * 4 ); + sol.push_back( M_PI * 4 + M_PI / 2 ); + sol.push_back( M_PI * 5 + M_PI / 2 ); + // we expect {pi,0,pi,0,pi/2,pi+pi/2} + std::cout << "expect: INVALID 4 3.14159 0 3.14159 0 1.5708 4.71239" << std::endl; + + edoRepairer* repare = new edoRepairerModulo( 2 * M_PI ); // modulo 2pi + + (*repare)(sol); + + std::cout << sol << std::endl; + + return 0; +} diff --git a/edo/test/t-uniform.cpp b/edo/test/t-uniform.cpp new file mode 100644 index 000000000..228ce5e22 --- /dev/null +++ b/edo/test/t-uniform.cpp @@ -0,0 +1,43 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2010 Thales group +*/ +/* +Authors: + Johann Dréo + Caner Candan +*/ + +#include +#include + +#include "Rosenbrock.h" + +typedef eoReal< eoMinimizingFitness > EOT; + +int main(void) +{ + eoState state; + + edoUniform< EOT >* distrib = new edoUniform< EOT >( EOT(3, -1), EOT(3, 1) ); + state.storeFunctor(distrib); + + return 0; +} diff --git a/edo/test/t-variance.cpp b/edo/test/t-variance.cpp new file mode 100644 index 000000000..205fc0561 --- /dev/null +++ b/edo/test/t-variance.cpp @@ -0,0 +1,83 @@ + +#include +#include + +#include +#include +#include + +typedef eoReal Vec; + +void check( Vec ex_mean, Vec ex_var, Vec es_mean, Vec es_var ) +{ + std::cout << "expected mean=" << ex_mean << " variance=" << ex_var << std::endl; + std::cout << "estimated mean=" << es_mean << " variance=" << es_var << std::endl; + + for( unsigned int i=0; i pop; + for( unsigned int i=1; i<7; ++i) { + Vec indiv(1,i); + pop.push_back( indiv ); + std::clog << indiv << " "; + } + std::clog << std::endl; + + edoEstimatorNormalMono estimator; + + edoNormalMono distrib = estimator(pop); + + Vec ex_mean(1,3.5); + Vec ex_var(1,17.5/6); + Vec es_mean = distrib.mean(); + Vec es_var = distrib.variance(); + + check( ex_mean, ex_var, es_mean, es_var ); + + + // Test with negative values + std::clog << "Variance computation on negative values" << std::endl; + pop.clear(); + + pop.push_back( Vec(1, 11.0) ); + pop.push_back( Vec(1, -4.0) ); + pop.push_back( Vec(1, 11.0) ); + pop.push_back( Vec(1, 14.0) ); + pop.push_back( Vec(1, -2.0) ); + + std::clog << pop << std::endl; + + distrib = estimator(pop); + + ex_mean = Vec(1,6.0); + ex_var = Vec(1,278.0/5); + es_mean = distrib.mean(); + es_var = distrib.variance(); + + check( ex_mean, ex_var, es_mean, es_var ); + + + // test single individual + std::clog << "Variance computation on a pop with a single individual" << std::endl; + pop.clear(); + pop.push_back( Vec(1, 0.0) ); + + distrib = estimator(pop); + + ex_mean = Vec(1,0.0); + ex_var = Vec(1,0.0); + es_mean = distrib.mean(); + es_var = distrib.variance(); + + check( ex_mean, ex_var, es_mean, es_var ); +} + diff --git a/edo/test/test_cov_parameters.py b/edo/test/test_cov_parameters.py new file mode 100755 index 000000000..30688ca45 --- /dev/null +++ b/edo/test/test_cov_parameters.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python + +PSIZE = 10000 +MEAN = 0 +CMD = "./test/t-edoEstimatorNormalMulti -P=%s -m=%.1f -1=%.1f -2=%.1f -3=%.1f && ./gplot.py -r TestResPop -p -w 5 -u -g %s -G results_for_test_cov_parameters -f %s_gen1" + +from os import system +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 ) diff --git a/eo/.gitignore b/eo/.gitignore new file mode 100644 index 000000000..2bfc9fc77 --- /dev/null +++ b/eo/.gitignore @@ -0,0 +1,5 @@ +*.swp +debug/ +release/ +*CMakeFiles* +*Makefile diff --git a/eo/CMakeLists.txt b/eo/CMakeLists.txt index 13af65ac5..9b6962f2c 100644 --- a/eo/CMakeLists.txt +++ b/eo/CMakeLists.txt @@ -1,116 +1,53 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 2.6) - -###################################################################################### -### 0) If you want to set your variables in eo-conf.cmake and avoid the cmd line -###################################################################################### - -#INCLUDE(eo-conf.cmake OPTIONAL) - -###################################################################################### - - -###################################################################################### -### 1) Main project config -###################################################################################### - -# set the project namef and other variables -PROJECT(EO) - -# CMake > 2.8 is needed, because of the FindOpenMP feature -#cmake_minimum_required(VERSION 2.8) - -#SET(PROJECT_VERSION_MAJOR 1) -#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}${PROJECT_VERSION_MISC}" CACHE STRING "Global version" FORCE) -SET(GLOBAL_VERSION "${VERSION}") - -SET(PACKAGE_BUGREPORT "eodev-help@sourceforge.net" CACHE STRING "Package bug report" FORCE) -SET(PACKAGE_NAME "Evolving Objects" CACHE STRING "Package name" FORCE) -SET(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}"CACHE STRING "Package string full name" FORCE) -SET(PACKAGE_TARNAME "eo" CACHE STRING "Package tar name" FORCE) - -# regular expression checking -INCLUDE_REGULAR_EXPRESSION("^.*$" "^$") - -# set a language for the entire project. -ENABLE_LANGUAGE(CXX) -ENABLE_LANGUAGE(C) - -###################################################################################### ##################################################################################### -### 2) Include required modules / configuration files +### Include required modules / configuration files ##################################################################################### -FIND_PACKAGE(OpenMP) -IF(OPENMP_FOUND) - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") -ENDIF() +# For eo::mpi +enable_language(C) -INCLUDE(CMakeBackwardCompatibilityCXX) +# For openmp parallel +if(ENABLE_OPENMP) + find_package(OpenMP) + if(OPENMP_FOUND) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") + else() + message( "ERROR: You asked for OpenMP but it has not been found." ) + set(IS_FATAL 1) + endif(OPENMP_FOUND) +endif(ENABLE_OPENMP) -INCLUDE(FindDoxygen) +if(ENABLE_GNUPLOT) + include(FindGnuplot) +endif(ENABLE_GNUPLOT) -INCLUDE(FindGnuplot) +# set a special flag if the environment is windows (should do the same in a config.g file) +if (WIN32) + add_definitions(-D_WINDOWS=1) +endif (WIN32) -INCLUDE(CheckLibraryExists) -IF(UNIX) - INCLUDE(ConfigureChecks.cmake) -ENDIF(UNIX) -INCLUDE(Dart OPTIONNAL) +##################################################################################### +### Include required modules / configuration files +##################################################################################### # now create config headers -CONFIGURE_FILE(config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h) +configure_file(config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h) # now create config install_symlink script file -CONFIGURE_FILE(install_symlink.py.cmake ${CMAKE_CURRENT_BINARY_DIR}/install_symlink.py) - -# now create PKGBUILD file for archlinux package manager -CONFIGURE_FILE(PKGBUILD.cmake ${CMAKE_CURRENT_BINARY_DIR}/PKGBUILD) - -# Set a special flag if the environment is windows (should do the same in a config.g file) -IF (WIN32) - ADD_DEFINITIONS(-D_WINDOWS=1) -ENDIF (WIN32) - -###################################################################################### - -###################################################################################### +configure_file(install_symlink.py.cmake ${CMAKE_CURRENT_BINARY_DIR}/install_symlink.py) ###################################################################################### -### compilation of examples? -###################################################################################### - -#SET(ENABLE_CMAKE_EXAMPLE TRUE CACHE BOOL "Enable copy of benchs and parameters file?") - +### Include subdirectories ###################################################################################### -###################################################################################### -### 4) Test config -###################################################################################### - -#IF (ENABLE_CMAKE_TESTING) -# ENABLE_TESTING() -#ENDIF (ENABLE_CMAKE_TESTING) - -###################################################################################### - - -###################################################################################### -### 5) Where must cmake go now ? -###################################################################################### - -#ADD_SUBDIRECTORY(app) -ADD_SUBDIRECTORY(doc) -ADD_SUBDIRECTORY(src) +add_subdirectory(doc) +add_subdirectory(src) if(ENABLE_CMAKE_TESTING) add_subdirectory(test) @@ -118,31 +55,9 @@ endif(ENABLE_CMAKE_TESTING) if(ENABLE_CMAKE_EXAMPLE) if(${CMAKE_VERBOSE_MAKEFILE}) - message("EO Examples :") + message("EO examples:") endif(${CMAKE_VERBOSE_MAKEFILE}) add_subdirectory(tutorial) + #add_subdirectory(app) # FIXME must be updated endif(ENABLE_CMAKE_EXAMPLE) -###################################################################################### - - -###################################################################################### -### 6) Install pkg-config config file for EO -###################################################################################### - -SET(PCPREFIX "/usr") -SET(PCFLAGS "-leoutils -leo -les -lga -lcma -lgcov") -SET(PCINCLUDEDIR "eo") -CONFIGURE_FILE(pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/eo.pc) -INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/eo.pc DESTINATION ${LIB}/pkgconfig COMPONENT headers) - -###################################################################################### - - -###################################################################################### -### 7) Include packaging -###################################################################################### - -#INCLUDE(Packaging.cmake) - -###################################################################################### diff --git a/eo/NEWS b/eo/NEWS index f4625d6c3..6657f36b8 100644 --- a/eo/NEWS +++ b/eo/NEWS @@ -1,4 +1,29 @@ -* current version +* current release: + +* release 1.3.1 (2012-07-27) + - the eo::mpi modules is no longer dependent from boost::mpi + - parallel multi-start example + - bugfix: an error is now thrown when accessing best_element of an empty population + +* release 1.3.0 (2012-07-24) + - features: + - delete the deprecated code parts (was marked as deprecated in the release 1.1) + - eoSignal: a class to handle signal with eoCheckpoint instances + - eoDetSingleBitFlip: bit flip mutation that changes exactly k bits while checking for duplicate + - eoFunctorStat: a wrapper to turn any stand-alone function and into an eoStat + - generilazed the output of an eoState: now you can change the format, comes with defaults formatting (latex and json) + - eoWrongParamTypeException: a new exception to handle cases where a wrong template is given to eoParser::valueOf + - added a getParam method to the eoParser, that raise an exception if the parameter has not been declared + - eoParserLogger features are now included in the default eoParser + - build system: + - improvements of the build architecture + - create PKGBUILD file for archlinux package manager + - a FindEO module for CMake + - bugfixes: + - fixed regression with gcc 4.7 + - fixed compilation issues in Microsoft Visual C++, related to time measurement + - added several asserts accross the framework (note: asserts are included only in debug mode) + - lot of small bugfixes :-) * release 1.2 (16. May. 2011) - fixed the incremental allocation issue in variation operators which were @@ -20,11 +45,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 diff --git a/eo/app/gprop/CMakeLists.txt b/eo/app/gprop/CMakeLists.txt index e37af2e5f..98b82e11f 100644 --- a/eo/app/gprop/CMakeLists.txt +++ b/eo/app/gprop/CMakeLists.txt @@ -2,30 +2,30 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### -### 2) Specify where CMake can find the libraries (mandatory: before 3) ) +### 2) specify where cmake can find the libraries (mandatory: before 3) ) ###################################################################################### -LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) +link_directories(${EO_BIN_DIR}/lib) ###################################################################################### -### 3) Define your target(s): just an executable here +### 3) define your target(s): just an executable here ###################################################################################### -SET (GPROP_SOURCES gprop.cpp) +set (GPROP_SOURCES gprop.cpp) # especially for Visual Studio -IF(NOT WIN32 OR CYGWIN) - ADD_EXECUTABLE(gprop ${GPROP_SOURCES}) - ADD_DEPENDENCIES(gprop eo eoutils) +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) + set(GPROP_VERSION ${GLOBAL_VERSION}) + set_target_properties(gprop PROPERTIES VERSION "${GPROP_VERSION}") +endif(NOT WIN32 OR CYGWIN) ###################################################################################### diff --git a/eo/app/gpsymreg/CMakeLists.txt b/eo/app/gpsymreg/CMakeLists.txt index 1bb258678..647d65e6f 100644 --- a/eo/app/gpsymreg/CMakeLists.txt +++ b/eo/app/gpsymreg/CMakeLists.txt @@ -2,37 +2,37 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### -### 2) Specify where CMake can find the libraries (mandatory: before 3) ) +### 2) specify where cmake can find the libraries (mandatory: before 3) ) ###################################################################################### -LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) +link_directories(${EO_BIN_DIR}/lib) ###################################################################################### -### 3) Define your target(s): just an executable here +### 3) define your target(s): just an executable here ###################################################################################### -SET (GPSYMREG_SOURCES main.cpp) +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) +add_dependencies(gpsymreg eo eoutils) ###################################################################################### -### 4) Optionnal: define your target(s)'s version: no effect for windows +### 4) optionnal: define your target(s)'s version: no effect for windows ###################################################################################### -SET(GPSYMREG_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(gpsymreg PROPERTIES VERSION "${GPSYMREG_VERSION}") +set(GPSYMREG_VERSION ${GLOBAL_VERSION}) +set_target_properties(gpsymreg PROPERTIES VERSION "${GPSYMREG_VERSION}") ###################################################################################### -### 5) Link the librairies for your target(s) +### 5) link the librairies for your target(s) ###################################################################################### -TARGET_LINK_LIBRARIES(gpsymreg eo eoutils) +target_link_libraries(gpsymreg eo eoutils) ###################################################################################### diff --git a/eo/app/mastermind/CMakeLists.txt b/eo/app/mastermind/CMakeLists.txt index 6fde0887c..5ae1cab06 100644 --- a/eo/app/mastermind/CMakeLists.txt +++ b/eo/app/mastermind/CMakeLists.txt @@ -2,14 +2,14 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +INCLUDE_DIRECTORIES(${EO_SRC_DIR}/src) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Specify where CMake can find the libraries (mandatory: before 3) ) ###################################################################################### -LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) +LINK_DIRECTORIES(${EO_BIN_DIR}/${LIB}) ###################################################################################### ### 3) Define your target(s): just an executable here diff --git a/eo/doc/CMakeLists.txt b/eo/doc/CMakeLists.txt index d7aa864b0..d33151474 100644 --- a/eo/doc/CMakeLists.txt +++ b/eo/doc/CMakeLists.txt @@ -3,16 +3,16 @@ ########################################################################################## IF (DOXYGEN_FOUND) - SET(DOC_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "EO documentation directory") - SET(EO_DOC_CONFIG_FILE "eo.cfg" CACHE PATH "EO documentation configuration file") + SET(EO_DOC_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL "EO documentation directory" FORCE) + SET(EO_DOC_CONFIG_FILE "eo.doxyfile" CACHE INTERNAL "EO documentation configuration file") # Copy necessary doc files - CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/index.h ${DOC_DIR}/index.h COPYONLY) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/index.h ${EO_DOC_DIR}/index.h COPYONLY) FILE(GLOB header_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.htm*) FILE(GLOB pdf_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.pdf) FILE(GLOB jpg_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.jpg) FOREACH (file ${header_files} ${pdf_files} ${jpg_files}) - CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file} ${DOC_DIR}/${file} COPYONLY) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file} ${EO_DOC_DIR}/${file} COPYONLY) ENDFOREACH (file) # define the doc target diff --git a/eo/doc/eo.doxyfile.cmake b/eo/doc/eo.doxyfile.cmake new file mode 100644 index 000000000..e781ed5f6 --- /dev/null +++ b/eo/doc/eo.doxyfile.cmake @@ -0,0 +1,1501 @@ +# Doxyfile 1.6.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = @PACKAGE_NAME@ + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @PACKAGE_VERSION@ + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@ + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = @CMAKE_SOURCE_DIR@ + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = YES + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = NO + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = NO + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = @CMAKE_SOURCE_DIR@ + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = *.cpp \ + *.h \ + NEWS \ + README + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = @CMAKE_SOURCE_DIR@/src/obsolete @CMAKE_SOURCE_DIR@/test @CMAKE_SOURCE_DIR@/tutorial @CMAKE_SOURCE_DIR@/contrib @CMAKE_SOURCE_DIR@/app + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = @CMAKE_SOURCE_DIR@/test + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 3 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = eo + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = YES + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# When the SEARCHENGINE tag is enable doxygen will generate a search box for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP) or Qt help (GENERATE_QHP) +# there is already a search function so this one should typically +# be disabled. + +SEARCHENGINE = YES + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = YES + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = @CMAKE_CURRENT_BINARY_DIR@/eo.doxytag + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/eo/install_symlink.py.cmake b/eo/install_symlink.py.cmake index fd71d68b5..382c0b9f6 100755 --- a/eo/install_symlink.py.cmake +++ b/eo/install_symlink.py.cmake @@ -31,8 +31,16 @@ def uninstall(): print('All symlinks have been removed.') def install(): - for dirname in DATA['dirs']: os.mkdir(dirname) - for src, dst in DATA['links']: os.symlink(src, dst) + for dirname in DATA['dirs']: + try: + os.makedirs(dirname) + except(os.error): + pass + for src, dst in DATA['links']: + try: + os.symlink(src, dst) + except: + pass print('All symlinks have been installed.') def data(): diff --git a/eo/src/CMakeLists.txt b/eo/src/CMakeLists.txt index 6e1bb3e40..283fd838e 100644 --- a/eo/src/CMakeLists.txt +++ b/eo/src/CMakeLists.txt @@ -2,16 +2,16 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Define the eo target ###################################################################################### -SET(EO_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) -SET(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH}) +set(EO_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH}) -SET(EO_SOURCES +set(EO_SOURCES eoFunctorStore.cpp eoPersistent.cpp eoPrintable.cpp @@ -20,35 +20,36 @@ SET(EO_SOURCES eoSIGContinue.cpp ) -ADD_LIBRARY(eo STATIC ${EO_SOURCES}) -INSTALL(TARGETS eo ARCHIVE DESTINATION ${LIB} COMPONENT libraries) - -FILE(GLOB HDRS *.h eo) -INSTALL(FILES ${HDRS} DESTINATION include${INSTALL_SUB_DIR}/eo COMPONENT headers) - -INSTALL(DIRECTORY do es ga gp other utils - DESTINATION include${INSTALL_SUB_DIR}/eo - COMPONENT headers - FILES_MATCHING PATTERN "*.h" PATTERN "checkpointing" PATTERN external_eo - ) +add_library(eo STATIC ${EO_SOURCES}) ###################################################################################### ### 3) Optionnal: define your target(s)'s version: no effect for windows ###################################################################################### -SET(EO_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(eo PROPERTIES VERSION "${EO_VERSION}") +set(EO_VERSION ${GLOBAL_VERSION}) +set_target_properties(eo PROPERTIES VERSION "${EO_VERSION}") + +install(TARGETS eo ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +file(GLOB HDRS *.h eo) +install(FILES ${HDRS} DESTINATION local/include${INSTALL_SUB_DIR}/eo COMPONENT headers) + +install(DIRECTORY do es ga gp other utils + DESTINATION local/include${INSTALL_SUB_DIR}/eo + COMPONENT headers + FILES_MATCHING PATTERN "*.h" PATTERN "checkpointing" PATTERN external_eo + ) ###################################################################################### ### 4) Where must cmake go now ? ###################################################################################### -ADD_SUBDIRECTORY(es) -ADD_SUBDIRECTORY(ga) -ADD_SUBDIRECTORY(utils) +add_subdirectory(es) +add_subdirectory(ga) +add_subdirectory(utils) -IF(ENABLE_PYEO) - ADD_SUBDIRECTORY(pyeo) -ENDIF(ENABLE_PYEO) +if(ENABLE_PYEO) + add_subdirectory(pyeo) +endif(ENABLE_PYEO) ###################################################################################### diff --git a/eo/src/apply.h b/eo/src/apply.h index f685f8d3b..45c4cfc2d 100644 --- a/eo/src/apply.h +++ b/eo/src/apply.h @@ -19,7 +19,7 @@ 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 */ //----------------------------------------------------------------------------- @@ -31,7 +31,10 @@ #include #include #include + +#ifdef _OPENMP #include +#endif /** Applies a unary function to a std::vector of things. @@ -48,29 +51,41 @@ void apply(eoUF& _proc, std::vector& _pop) double t1 = 0; if ( eo::parallel.enableResults() ) - { - t1 = omp_get_wtime(); - } + { + t1 = omp_get_wtime(); + } 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]); } - } +#ifdef _MSC_VER + //Visual Studio supports only OpenMP version 2.0 in which + //an index variable must be of a signed integral type + for (long long i = 0; i < size; ++i) { _proc(_pop[i]); } +#else // _MSC_VER + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } +#endif + } 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]); } - } +#ifdef _MSC_VER + //Visual Studio supports only OpenMP version 2.0 in which + //an index variable must be of a signed integral type + for (long long i = 0; i < size; ++i) { _proc(_pop[i]); } +#else // _MSC_VER + //doesnot work with gcc 4.1.2 + //default(none) shared(_proc, _pop, size) + for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); } +#endif + } if ( eo::parallel.enableResults() ) - { - double t2 = omp_get_wtime(); - eoLogger log; - log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; - } + { + double t2 = omp_get_wtime(); + eoLogger log; + log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' '; + } #else // _OPENMP @@ -94,7 +109,7 @@ void apply(eoUF& _proc, std::vector& _pop) // //default(none) shared(_proc, _pop, size) // for (size_t i = 0; i < size; ++i) // { -// _proc(_pop[i]); +// _proc(_pop[i]); // } // } @@ -112,7 +127,7 @@ void apply(eoUF& _proc, std::vector& _pop) // //default(none) shared(_proc, _pop, size) // for (size_t i = 0; i < size; ++i) // { -// _proc(_pop[i]); +// _proc(_pop[i]); // } // } diff --git a/eo/src/do/make_checkpoint.h b/eo/src/do/make_checkpoint.h index 8e5295115..cc0746ddb 100644 --- a/eo/src/do/make_checkpoint.h +++ b/eo/src/do/make_checkpoint.h @@ -201,7 +201,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu // The Stdout monitor will print parameters to the screen ... if ( needStdoutMonitor ) { - eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + eoStdoutMonitor *monitor = new eoStdoutMonitor(/*false FIXME remove this deprecated prototype*/); _state.storeFunctor(monitor); // when called by the checkpoint (i.e. at every generation) diff --git a/eo/src/do/make_checkpoint_FDC.h b/eo/src/do/make_checkpoint_FDC.h index 33c7f7206..f241667f7 100644 --- a/eo/src/do/make_checkpoint_FDC.h +++ b/eo/src/do/make_checkpoint_FDC.h @@ -175,7 +175,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval // The Stdout monitor will print parameters to the screen ... if ( needStdoutMonitor ) { - eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + eoStdoutMonitor *monitor = new eoStdoutMonitor(/*false FIXME remove this deprecated prototype*/); _state.storeFunctor(monitor); // when called by the checkpoint (i.e. at every generation) diff --git a/eo/src/do/make_checkpoint_assembled.h b/eo/src/do/make_checkpoint_assembled.h index 26463fab3..27d050ada 100644 --- a/eo/src/do/make_checkpoint_assembled.h +++ b/eo/src/do/make_checkpoint_assembled.h @@ -129,7 +129,7 @@ eoCheckPoint& do_make_checkpoint_assembled(eoParser& _parser, eoState& _sta // STDOUT // ------ - eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + eoStdoutMonitor *monitor = new eoStdoutMonitor(/*false FIXME remove this deprecated prototype*/); _state.storeFunctor(monitor); checkpoint->add(*monitor); monitor->add(*generationCounter); diff --git a/eo/src/eo b/eo/src/eo index 8cebd23a0..b87ca57f1 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -78,6 +78,7 @@ #include #include #include +#include // Continuators - all include eoContinue.h #include @@ -102,6 +103,7 @@ #include // Embedding truncation selection #include +#include // the batch selection - from an eoSelectOne #include @@ -141,6 +143,9 @@ #include // includes eoRealBounds.h #include // no eoIntVectorBounds +// Serialization stuff +#include + // aliens #include #include diff --git a/eo/src/eoCombinedContinue.h b/eo/src/eoCombinedContinue.h index dfb70f67b..5162ffaa9 100644 --- a/eo/src/eoCombinedContinue.h +++ b/eo/src/eoCombinedContinue.h @@ -57,6 +57,7 @@ public: { } + /* FIXME remove in next release /// Ctor - for historical reasons ... should disspear some day eoCombinedContinue( eoContinue& _cont1, eoContinue& _cont2) : eoContinue(), std::vector* >() @@ -68,12 +69,14 @@ public: this->push_back(&_cont1); this->push_back(&_cont2); } + */ void add(eoContinue & _cont) { this->push_back(&_cont); } + /* FIXME remove in next release void removeLast(void) { #ifndef DEPRECATED_MESSAGES @@ -82,6 +85,7 @@ public: this->pop_back(); } + */ /** Returns false when one of the embedded continuators say so (logical and) diff --git a/eo/src/eoCombinedInit.h b/eo/src/eoCombinedInit.h index d41122d85..cc93620d3 100644 --- a/eo/src/eoCombinedInit.h +++ b/eo/src/eoCombinedInit.h @@ -44,11 +44,13 @@ public: rates.push_back(_rate); } + /* FIXME remove in next release void add(eoInit & _init, double _rate, bool _verbose) { 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 */ diff --git a/eo/src/eoContinue.h b/eo/src/eoContinue.h index dbbf24805..82544115b 100644 --- a/eo/src/eoContinue.h +++ b/eo/src/eoContinue.h @@ -67,4 +67,43 @@ public: } }; +/** + * Termination condition with a count condition (totalGenerations). This continuator contains + * a count of cycles, which can be retrieved or set. + * + * @ingroup Continuators + * @ingroup Core + */ +template< class EOT > +class eoCountContinue : public eoContinue< EOT > +{ + public: + + eoCountContinue( ) : + thisGenerationPlaceholder( 0 ), + thisGeneration( thisGenerationPlaceholder ) + { + // empty + } + + eoCountContinue( unsigned long& currentGen ) : + thisGenerationPlaceholder( 0 ), + thisGeneration( currentGen ) + { + // empty + } + + virtual std::string className( void ) const { return "eoCountContinue"; } + + virtual void reset( ) + { + thisGeneration = 0; + } + + protected: + + unsigned long thisGenerationPlaceholder; + unsigned long& thisGeneration; +}; + #endif diff --git a/eo/src/eoDetSelect.h b/eo/src/eoDetSelect.h index 4a0858b6a..c89f41f69 100644 --- a/eo/src/eoDetSelect.h +++ b/eo/src/eoDetSelect.h @@ -34,7 +34,7 @@ #include //----------------------------------------------------------------------------- -/** eoDetSelect selects many individuals determinisctically +/** eoDetSelect selects many individuals deterministically * * @ingroup Selectors */ diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 2c7c5474c..4d9c7b6da 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -37,8 +37,6 @@ #include #include - - template class eoIslandsEasyEA ; template class eoDistEvalEasyEA ; @@ -102,6 +100,33 @@ template class eoEasyEA: public eoAlgo offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. } + /** + * @brief Ctor allowing to specify which pop eval function we're going to use. + * + * Ctor taking a breed and merge, an overload of ctor to define an offspring size, and + * the pop eval function used. This allows to precise if we would like to use the + * parallel evaluation, for instance. + */ + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoPopEvalFunc& _pop_eval, + eoBreed& _breed, + eoReplacement& _replace, + unsigned _offspringSize + ) : continuator(_continuator), + eval (_eval), + loopEval(_eval), + popEval(_pop_eval), + selectTransform(dummySelect, dummyTransform), + breed(_breed), + mergeReduce(dummyMerge, dummyReduce), + replace(_replace), + isFirstCall(true) + { + offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. + } + /* eoEasyEA(eoContinue & _continuator, eoPopEvalFunc & _pop_eval, @@ -219,45 +244,44 @@ template class eoEasyEA: public eoAlgo /// Apply a few generation of evolution to the population. virtual void operator()(eoPop& _pop) { - if (isFirstCall) - { - size_t total_capacity = _pop.capacity() + offspring.capacity(); - _pop.reserve(total_capacity); - offspring.reserve(total_capacity); - isFirstCall = false; - } - eoPop empty_pop; - - popEval(empty_pop, _pop); // A first eval of pop. - - do + if (isFirstCall) { - try + size_t total_capacity = _pop.capacity() + offspring.capacity(); + _pop.reserve(total_capacity); + offspring.reserve(total_capacity); + isFirstCall = false; + } + + eoPop empty_pop; + + do + { + try { - unsigned pSize = _pop.size(); - offspring.clear(); // new offspring + unsigned pSize = _pop.size(); - breed(_pop, offspring); + offspring.clear(); // new offspring - popEval(_pop, offspring); // eval of parents + offspring if necessary + breed(_pop, offspring); - replace(_pop, offspring); // after replace, the new pop. is in _pop + popEval(_pop, offspring); // eval of parents + offspring if necessary - if (pSize > _pop.size()) - throw std::runtime_error("Population shrinking!"); - else if (pSize < _pop.size()) - throw std::runtime_error("Population growing!"); + replace(_pop, offspring); // after replace, the new pop. is in _pop + if (pSize > _pop.size()) + throw std::runtime_error("Population shrinking!"); + else if (pSize < _pop.size()) + throw std::runtime_error("Population growing!"); } - catch (std::exception& e) + catch (std::exception& e) { - std::string s = e.what(); - s.append( " in eoEasyEA"); - throw std::runtime_error( s ); + std::string s = e.what(); + s.append( " in eoEasyEA"); + throw std::runtime_error( s ); } } - while ( continuator( _pop ) ); + while ( continuator( _pop ) ); } protected : diff --git a/eo/src/eoEvalDump.h b/eo/src/eoEvalDump.h new file mode 100644 index 000000000..78630bee7 --- /dev/null +++ b/eo/src/eoEvalDump.h @@ -0,0 +1,134 @@ + +/* + This library is free software; you 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 + + © 2012 Thales group + + Authors: + Johann Dreo +*/ + +#ifndef eoEvalDump_H +#define eoEvalDump_H + +#include + +#include + +/** +Dump an evaluated individual to a given file. + +Note: test if the file could be open only in debug mode +If the file cannot be open during the calls, everything will fail in an standard exception. + +The file name should be given at instanciation, if you asked for a single file, it will +erase the previously written one and write the new individual in it. + +If you do not ask for a single file, it will create several files, +one different each time it found a individual. The filenames have then the form: + +"" being a integer, incremented by one each time a new file is written down. + +If you asked for a filename="RESULT", by default, the first dump file will be named "RESULT.0". +*/ +template +class eoEvalDump : public eoEvalFunc +{ +public: + //! A constructor for wrapping your own evaluator in a eoEvalDump. + eoEvalDump( + eoEvalFunc& func, std::string filename, bool single_file = false, + unsigned int file_count = 0, std::string count_prefix = "." + ) : + _func(func), + _filename(filename), _single_file(single_file), _file_count(file_count), _sep(count_prefix), + _of() + {} + + //! A constructor without an eval func, the eoEvalDump will thus just write to the file, without evaluating + eoEvalDump( + std::string filename, bool single_file = false, + unsigned int file_count = 0, std::string count_prefix = "." + ) : + _dummy_eval(), _func(_dummy_eval), + _filename(filename), _single_file(single_file), _file_count(file_count), _sep(count_prefix), + _of() + {} + + virtual void operator()(EOT& sol) + { + _func( sol ); + dump(sol); + } + + unsigned int file_count() { return _file_count; } + +protected: + + // FIXME on x86-64, when called inside a ofstream::open, this function call returns a corrupted string !?? + /* + const char * filename() + { + if( _single_file ) { + return _filename.c_str(); + + } else { + std::ostringstream afilename; + afilename << _filename << _sep << _file_count; + return afilename.str().c_str(); + } + } + */ + + void dump( EOT & sol ) + { + if( _single_file ) { + // explicitely erase the file before writing in it + _of.open( _filename.c_str(), std::ios_base::out | std::ios_base::trunc ); + + } else { + std::ostringstream afilename; + afilename << _filename << _sep << _file_count; + _of.open( afilename.str().c_str() /* NOTE : defaults to : , std::ios_base::out | std::ios_base::trunc */); + } +#ifndef NDEBUG + if ( !_of.is_open() ) { + std::string str = "Error, eoEvalDump could not open: " + _filename; + throw std::runtime_error( str ); + } +#endif + // here, in release mode, we assume that the file could be opened + // thus, we avoid a supplementary test in this costly evaluator + _of << sol << std::endl; + _of.close(); + + _file_count++; + } + +protected: + class DummyEval : public eoEvalFunc + { + void operator()(EOT& sol) {/*empty*/} + }; + DummyEval _dummy_eval; + eoEvalFunc& _func; + std::string _filename; + bool _single_file; + unsigned int _file_count; + std::string _sep; + std::ofstream _of; +}; + +#endif // eoEvalDump_H diff --git a/eo/src/eoEvalKeepBest.h b/eo/src/eoEvalKeepBest.h new file mode 100644 index 000000000..12a9a978f --- /dev/null +++ b/eo/src/eoEvalKeepBest.h @@ -0,0 +1,153 @@ + +/* + This library is free software; you 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 + + © 2012 Thales group + + Authors: + Johann Dreo +*/ + +#ifndef eoEvalKeepBest_H +#define eoEvalKeepBest_H + +#include + +#include +#include + +/** + Evaluate with the given evaluator and keep the best individual found so far. + + This is useful if you use a non-monotonic algorithm, such as CMA-ES, where the + population's best fitness can decrease between two generations. This is + sometime necessary and one can't use elitist replacors, as one do not want to + introduce a bias in the population. + + The eoEvalBestKeep can be used as a wrapper around a classical evaluator, + that keep the best individual it has found since its instanciation. + + To get the best individual, you have to call best_element() on the + eoEvalKeepBest itself, and not on the population (or else you would get the + best individual found at the last generation). + + Example: + + MyEval true_eval; + eoEvalKeepBest wrapped_eval( true_eval ); + + // as an interesting side effect, you will get the best individual since + // initalization. + eoPop pop( my_init ); + eoPopLoopEval loop_eval( wrapped_eval ); + + loop_eval( pop ); + + eoEasyEA algo( …, wrapped_eval, … ); + + algo(pop); + + // do not use pop.best_element()! + std::cout << wrapped_eval.best_element() << std::endl; + + + You can also inherits from eoEvalKeepBest, if you want to add its interface + with your own one. But then, you will have to explicitely call the base class + functor: + class MyEval : public eoEvalKeepBest + { + MyEval() : eoEvalKeepBest() {} + virtual void operator()(EOT& sol) + { + // evaluate sol here + // ... + + // keep the best + eoEvalKeepBest::operator()( sol ); + }; + + @ingroup Evaluation + */ +template class eoEvalKeepBest : public eoEvalFunc, public eoValueParam +{ + public : + + /** A constructor for inheritance: if you want to inherit from eoEvalKeepBest. + * + * Keep in mind that you will have to call eoEvalKeepBest in your own implementation of operator(). + * + * This constructor uses a dummy evaluator. + */ + eoEvalKeepBest( std::string _name = "VeryBest. " ) + : eoValueParam(EOT(), _name), dummy_eval(), func(dummy_eval), _found(false) {} + + + /** A constructor for wrapping your own evaluator in a eoEvalKeepBest. + */ + eoEvalKeepBest(eoEvalFunc& _func, std::string _name = "VeryBest. ") + : eoValueParam(EOT(), _name), dummy_eval(), func(_func), _found(false) {} + + virtual void operator()(EOT& sol) + { + _found = false; + + func(sol); // evaluate + assert( ! sol.invalid() ); + + // if there is no best kept + if( this->value().invalid() ) { + // FIXME replace this test by a reference fitness passed at instanciation + // take the first individual as best + this->value() = sol; + } else { + // if sol is better than the kept individual + if( sol.fitness() > this->value().fitness() ) { + this->value() = sol; + _found = true; + } + } + } + + //! Return the best individual found so far. + EOT best_element() + { + return this->value(); + } + + /** Reset the best individual to the given one. If no individual is + * provided, the next evaluated one will be taken as a reference. + */ + void reset( const EOT& new_best = EOT() ) + { + this->value() = new_best; + } + + //! Tell if a best individual has been found during the last call + bool found() const + { + return _found; + } + + class DummyEval : public eoEvalFunc + { + void operator()(EOT& sol) {/*empty*/} + }; + + protected : + DummyEval dummy_eval; + eoEvalFunc& func; + bool _found; +}; +#endif diff --git a/eo/src/eoEvalUserTimeThrowException.h b/eo/src/eoEvalUserTimeThrowException.h index 2cf72f6c1..2d9ccadd6 100644 --- a/eo/src/eoEvalUserTimeThrowException.h +++ b/eo/src/eoEvalUserTimeThrowException.h @@ -21,28 +21,30 @@ Authors: Johann Dréo */ - -#ifndef __unix__ -/*#warning "Warning: class 'eoEvalUserTimeThrowException' is only available under UNIX systems (defining 'rusage' in 'sys/resource.h'), contributions for other systems are welcomed."*/ -#else +#if !defined(__unix__) && !defined(_WINDOWS) +#warning "Warning: class 'eoEvalUserTimeThrowException' is only available under UNIX (defining 'rusage' in 'sys/resource.h') or Win32 (defining 'GetProcessTimes' in 'WinBase.h') systems, contributions for other systems are welcomed." +#else //!defined(__unix__) && !defined(_WINDOWS) #ifndef __EOEVALUSERTIMETHROWEXCEPTION_H__ #define __EOEVALUSERTIMETHROWEXCEPTION_H__ -#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. + * This class uses (almost-)POSIX or Win32 headers, depending on the platform. * It uses a computation of the user time used on the CPU. For a wallclock time measure, see eoEvalTimeThrowException * * @ingroup Evaluation */ + +#include + +#ifdef __unix__ + +#include +#include + template< class EOT > class eoEvalUserTimeThrowException : public eoEvalFuncCounter< EOT > { @@ -59,7 +61,7 @@ public: if( current >= _max ) { throw eoMaxTimeException( current ); } else { - func(eo); + this->func(eo); } } } @@ -69,5 +71,41 @@ protected: struct rusage _usage; }; +#else +#ifdef _WINDOWS +//here _WINDOWS is defined + +#include + +template< class EOT > +class eoEvalUserTimeThrowException : public eoEvalFuncCounter< EOT > +{ +public: + eoEvalUserTimeThrowException( eoEvalFunc & func, const long max ) : eoEvalFuncCounter( func, "CPU-user"), _max(max) {} + + virtual void operator() ( EOT & eo ) + { + if( eo.invalid() ) { + FILETIME dummy; + GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, &dummy, &_usage); + + ULARGE_INTEGER current; + current.LowPart = _usage.dwLowDateTime; + current.HighPart = _usage.dwHighDateTime; + if( current.QuadPart >= _max ) { + throw eoMaxTimeException( current.QuadPart ); + } else { + func(eo); + } + } + } + +protected: + const long _max; + FILETIME _usage; +}; + +#endif // _WINDOWS +#endif //__unix__ #endif // __EOEVALUSERTIMETHROWEXCEPTION_H__ -#endif // __UNIX__ +#endif //!defined(__unix__) && !defined(_WINDOWS) diff --git a/eo/src/eoFunctorStore.h b/eo/src/eoFunctorStore.h index c609637b4..051daf2ae 100644 --- a/eo/src/eoFunctorStore.h +++ b/eo/src/eoFunctorStore.h @@ -28,6 +28,9 @@ #define _eoFunctorStore_h #include +#include + +#include "utils/eoLogger.h" class eoFunctorBase; @@ -52,6 +55,13 @@ public: template Functor& storeFunctor(Functor* r) { +#ifndef NDEBUG + unsigned int existing = std::count( vec.begin(), vec.end(), r ); + if( existing > 0 ) { + eo::log << eo::warnings << "WARNING: you asked eoFunctorStore to store the functor " << r << " " + << existing + 1 << " times, a segmentation fault may occur in the destructor." << std::endl; + } +#endif // If the compiler complains about the following line, // check if you really are giving it a pointer to an // eoFunctorBase derived object @@ -67,6 +77,7 @@ private : /** no assignment allowed */ eoFunctorStore operator=(const eoFunctorStore&); +protected: std::vector vec; }; diff --git a/eo/src/eoGenContinue.h b/eo/src/eoGenContinue.h index 0d01bb0a1..dc756795d 100644 --- a/eo/src/eoGenContinue.h +++ b/eo/src/eoGenContinue.h @@ -35,24 +35,24 @@ @ingroup Continuators */ template< class EOT> -class eoGenContinue: public eoContinue, public eoValueParam +class eoGenContinue: public eoCountContinue, public eoValueParam { public: + using eoCountContinue::thisGeneration; + using eoCountContinue::thisGenerationPlaceholder; + /// Ctor for setting a eoGenContinue( unsigned long _totalGens) - : eoValueParam(0, "Generations", "Generations"), - repTotalGenerations( _totalGens ), - thisGenerationPlaceHolder(0), - thisGeneration(thisGenerationPlaceHolder) + : eoCountContinue( ), + eoValueParam(0, "Generations", "Generations"), + repTotalGenerations( _totalGens ) {}; /// 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) + : eoCountContinue( _currentGen ), eoValueParam(0, "Generations", "Generations"), + repTotalGenerations( _totalGens ) {}; /** Returns false when a certain number of generations is @@ -77,7 +77,7 @@ public: */ virtual void totalGenerations( unsigned long _tg ) { repTotalGenerations = _tg; - thisGeneration = 0; + eoCountContinue::reset(); }; /** Returns the number of generations to reach*/ @@ -86,7 +86,6 @@ public: return repTotalGenerations; }; - virtual std::string className(void) const { return "eoGenContinue"; } /** Read from a stream @@ -107,8 +106,6 @@ public: private: unsigned long repTotalGenerations; - unsigned long thisGenerationPlaceHolder; - unsigned long& thisGeneration; }; #endif diff --git a/eo/src/eoMergeReduce.h b/eo/src/eoMergeReduce.h index b3cb5b990..6a2618d9d 100644 --- a/eo/src/eoMergeReduce.h +++ b/eo/src/eoMergeReduce.h @@ -55,7 +55,7 @@ class eoMergeReduce : public eoReplacement merge(_merge), reduce(_reduce) {} - void operator()(eoPop& _parents, eoPop& _offspring) + virtual void operator()(eoPop& _parents, eoPop& _offspring) { merge(_parents, _offspring); // parents untouched, result in offspring reduce(_offspring, _parents.size()); @@ -92,6 +92,14 @@ class eoCommaReplacement : public eoMergeReduce public : eoCommaReplacement() : eoMergeReduce(no_elite, truncate) {} + virtual void operator()(eoPop& _parents, eoPop& _offspring) + { + // There must be more offsprings than parents, or else an exception will be raised + assert( _offspring.size() >= _parents.size() ); + + eoMergeReduce::operator()( _parents, _offspring ); + } + private : eoNoElitism no_elite; eoTruncate truncate; diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index 3ea53f466..eb6be46fb 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -4,31 +4,41 @@ // eoPop.h // (c) GeNeura Team, 1998 /* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. + This library is free software; you 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. + 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 + 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 - */ +Authors: + todos@geneura.ugr.es, http://geneura.ugr.es + jmerelo + gustavoromero + mac + maartenkeijzer + kuepper + okoenig + evomarc + Johann Dréo +*/ //----------------------------------------------------------------------------- -#ifndef _EOPOP_H -#define _EOPOP_H +#ifndef _EOPOP_H_ +#define _EOPOP_H_ #include #include #include // needed for GCC 3.2 #include +#include // EO includes #include // for eoInit @@ -54,18 +64,18 @@ template class eoPop: public std::vector, public eoObject, public eoPersistent { -public: + public: - using std::vector::size; - using std::vector::resize; - using std::vector::operator[]; - using std::vector::begin; - using std::vector::end; + 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; + typedef typename EOT::Fitness Fitness; #if defined(__CUDACC__) - typedef typename std::vector::iterator iterator; - typedef typename std::vector::const_iterator const_iterator; + typedef typename std::vector::iterator iterator; + typedef typename std::vector::const_iterator const_iterator; #endif /** Default ctor. Creates empty pop @@ -74,266 +84,297 @@ public: /** Ctor for the initialization of chromosomes - @param _popSize total population size - @param _chromInit Initialization routine, produces EO's, needs to be an eoInit + @param _popSize total population size + @param _chromInit Initialization routine, produces EO's, needs to be an eoInit */ - eoPop( unsigned _popSize, eoInit& _chromInit ) - :std::vector() - { - resize(_popSize); - for ( unsigned i = 0; i < _popSize; i++ ) - { + eoPop( unsigned _popSize, eoInit& _chromInit ) + : std::vector() + { + resize(_popSize); + for ( unsigned i = 0; i < _popSize; i++ ) + { _chromInit(operator[](i)); - } - }; + } + } /** appends random guys at end of pop. - Can be used to initialize it pop is empty + 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 + @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) + void append( unsigned _newPopSize, eoInit& _chromInit ) { - throw std::runtime_error("New size smaller than old size in pop.append"); - return; + unsigned oldSize = size(); + if (_newPopSize < oldSize) + { + throw std::runtime_error("New size smaller than old size in pop.append"); + return; + } + if (_newPopSize == oldSize) + return; + resize(_newPopSize); // adjust the size + for ( unsigned i = oldSize; i < _newPopSize; i++ ) + { + _chromInit(operator[](i)); + } } - if (_newPopSize == oldSize) - return; - resize(_newPopSize); // adjust the size - for ( unsigned i = oldSize; i < _newPopSize; i++ ) + + + /** Ctor from an std::istream; reads the population from a stream, + each element should be in different lines + @param _is the stream + */ + eoPop( std::istream& _is ) :std::vector() { - _chromInit(operator[](i)); + readFrom( _is ); } - }; - /** Ctor from an std::istream; reads the population from a stream, - each element should be in different lines - @param _is the stream - */ - eoPop( std::istream& _is ) :std::vector() { - readFrom( _is ); - } - - /** Empty Dtor */ + /** Empty Dtor */ virtual ~eoPop() {} - /// helper struct for getting a pointer - struct Ref { const EOT* operator()(const EOT& eot) { return &eot;}}; - /// helper struct for comparing on pointers - struct Cmp { - bool operator()(const EOT* a, const EOT* b) const + /// helper struct for getting a pointer + struct Ref { const EOT* operator()(const EOT& eot) { return &eot;}}; + + /// helper struct for comparing on pointers + struct Cmp { + 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 + }; + + /// 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 + of descending Fitness, so the first individual is the best! + */ + void sort(void) + { + std::sort(begin(), end(), Cmp2()); } - }; + /** creates a std::vector pointing to the individuals in descending order */ + void sort(std::vector& result) const + { + result.resize(size()); - /** - sort the population. Use this member to sort in order - of descending Fitness, so the first individual is the best! - */ - void sort(void) - { - std::sort(begin(), end(), Cmp2()); - } + std::transform(begin(), end(), result.begin(), Ref()); - /** creates a std::vector pointing to the individuals in descending order */ - void sort(std::vector& result) const - { - result.resize(size()); + std::sort(result.begin(), result.end(), Cmp()); + } - std::transform(begin(), end(), result.begin(), Ref()); - std::sort(result.begin(), result.end(), Cmp()); - } + /** + shuffle the population. Use this member to put the population + in random order + */ + void shuffle(void) + { + UF_random_generator gen; + std::random_shuffle(begin(), end(), gen); + } - /** - shuffle the population. Use this member to put the population - in random order - */ - void shuffle(void) - { - UF_random_generator gen; - std::random_shuffle(begin(), end(), gen); - } - /** creates a std::vector pointing to the individuals in random order */ - void shuffle(std::vector& result) const - { - result.resize(size()); + /** creates a std::vector pointing to the individuals in random order */ + void shuffle(std::vector& result) const + { + result.resize(size()); - std::transform(begin(), end(), result.begin(), Ref()); + std::transform(begin(), end(), result.begin(), Ref()); - UF_random_generator gen; - std::random_shuffle(result.begin(), result.end(), gen); - } + UF_random_generator gen; + std::random_shuffle(result.begin(), result.end(), gen); + } - /** returns an iterator to the best individual DOES NOT MOVE ANYBODY */ + + /** returns an iterator to the best individual DOES NOT MOVE ANYBODY */ #if defined(__CUDACC__) - eoPop::iterator it_best_element() - { - eoPop:: iterator it = std::max_element(begin(), end()); + eoPop::iterator it_best_element() + { + 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() + { + assert( this->size() > 0 ); + typename eoPop::iterator it = std::max_element(begin(), end()); #endif - return it; - } + return it; + } - /** returns an iterator to the best individual DOES NOT MOVE ANYBODY */ - const EOT & best_element() const - { + + /** returns an iterator to the best individual DOES NOT MOVE ANYBODY */ + const EOT & best_element() const + { #if defined(__CUDACC__) - eoPop::const_iterator it = std::max_element(begin(), end()); + 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); - } + if( it == end() ) + throw std::runtime_error("eoPop: Empty population, when calling best_element()."); + return (*it); + } - /** returns a const reference to the worse individual DOES NOT MOVE ANYBODY */ - const EOT & worse_element() const - { + /** returns a const reference to the worse individual DOES NOT MOVE ANYBODY */ + const EOT & worse_element() const + { #if defined(__CUDACC__) - eoPop::const_iterator it = std::min_element(begin(), end()); + eoPop::const_iterator it = std::min_element(begin(), end()); #else - typename eoPop::const_iterator it = std::min_element(begin(), end()); + assert( this->size() > 0 ); + typename eoPop::const_iterator it = std::min_element(begin(), end()); #endif - return (*it); - } + return (*it); + } - /** returns an iterator to the worse individual DOES NOT MOVE ANYBODY */ + + /** returns an iterator to the worse individual DOES NOT MOVE ANYBODY */ #if defined(__CUDACC__) - eoPop::iterator it_worse_element() - { - eoPop::iterator it = std::min_element(begin(), end()); + eoPop::iterator it_worse_element() + { + eoPop::iterator it = std::min_element(begin(), end()); #else - typename eoPop::iterator it_worse_element() - { - typename eoPop::iterator it = std::min_element(begin(), end()); + typename eoPop::iterator it_worse_element() + { + assert( this->size() > 0 ); + typename eoPop::iterator it = std::min_element(begin(), end()); #endif - return it; - } + return it; + } - /** - slightly faster algorithm than sort to find all individuals that are better - than the nth individual. INDIVIDUALS ARE MOVED AROUND in the pop. - */ + + /** + 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__) - eoPop::iterator nth_element(int nth) - { - eoPop::iterator it = begin() + nth; + eoPop::iterator nth_element(int nth) + { + eoPop::iterator it = begin() + nth; #else - typename eoPop::iterator nth_element(int nth) - { - typename eoPop::iterator it = begin() + nth; + typename eoPop::iterator nth_element(int nth) + { + assert( this->size() > 0 ); + typename eoPop::iterator it = begin() + nth; #endif - std::nth_element(begin(), it, end(), std::greater()); - return it; - } + 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 + struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } }; - std::vector fitness(size()); - std::transform(begin(), end(), fitness.begin(), GetFitness()); - typename std::vector::iterator it = fitness.begin() + which; - std::nth_element(fitness.begin(), it, fitness.end(), std::greater()); - return *it; - } + /** 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 - /** const nth_element function, returns pointers to sorted individuals - * up the the nth - */ - void nth_element(int which, std::vector& result) const - { + std::vector fitness(size()); + std::transform(begin(), end(), fitness.begin(), GetFitness()); - result.resize(size()); - std::transform(begin(), end(), result.begin(), Ref()); + typename std::vector::iterator it = fitness.begin() + which; + std::nth_element(fitness.begin(), it, fitness.end(), std::greater()); + return *it; + } - typename std::vector::iterator it = result.begin() + which; - std::nth_element(result.begin(), it, result.end(), Cmp()); - } + /** const nth_element function, returns pointers to sorted individuals + * up the the nth + */ + void nth_element(int which, std::vector& result) const + { - /** does STL swap with other pop */ - void swap(eoPop& other) - { - std::swap(static_cast& >(*this), static_cast& >(other)); - } + assert( this->size() > 0 ); + result.resize(size()); + std::transform(begin(), end(), result.begin(), Ref()); - /** - * Prints sorted pop but does NOT modify it! - * - * @param _os A std::ostream. - */ - 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; - } - } + typename std::vector::iterator it = result.begin() + which; - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A std::ostream. - */ - virtual void printOn(std::ostream& _os) const - { - _os << size() << '\n'; - std::copy( begin(), end(), std::ostream_iterator( _os, "\n") ); - } + std::nth_element(result.begin(), it, result.end(), Cmp()); + } - /** @name Methods from eoObject */ - //@{ - /** - * Read object. The EOT class must have a ctor from a stream; - * @param _is A std::istream. - */ - virtual void readFrom(std::istream& _is) - { - size_t sz; - _is >> sz; - resize(sz); + /** does STL swap with other pop */ + void swap(eoPop& other) + { + std::swap(static_cast& >(*this), static_cast& >(other)); + } - for (size_t i = 0; i < sz; ++i) { - operator[](i).readFrom( _is ); - } - } - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual std::string className() const {return "eoPop";}; - //@} + /** + * Prints sorted pop but does NOT modify it! + * + * @param _os A std::ostream. + */ + 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; + } + } - virtual void invalidate() - { - for (unsigned i=0; ioperator[](i).invalidate(); - } -}; -#endif + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A std::ostream. + */ + virtual void printOn(std::ostream& _os) const + { + _os << size() << '\n'; + std::copy( begin(), end(), std::ostream_iterator( _os, "\n") ); + } + + + /** @name Methods from eoObject */ + //@{ + /** + * Read object. The EOT class must have a ctor from a stream; + * @param _is A std::istream. + */ + virtual void readFrom(std::istream& _is) + { + size_t sz; + _is >> sz; + + resize(sz); + + for (size_t i = 0; i < sz; ++i) { + operator[](i).readFrom( _is ); + } + } + + + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual std::string className() const {return "eoPop";}; + //@} + + + /** Invalidate the whole population + */ + virtual void invalidate() + { + for (unsigned i=0; ioperator[](i).invalidate(); + } + +}; // class eoPop + +#endif // _EOPOP_H_ + diff --git a/eo/src/eoPopEvalFunc.h b/eo/src/eoPopEvalFunc.h index aba74d9ab..7fcad1467 100644 --- a/eo/src/eoPopEvalFunc.h +++ b/eo/src/eoPopEvalFunc.h @@ -30,6 +30,16 @@ #include #include +# ifdef WITH_MPI +#include +#include +#include +#include +#include + +#include // ceil +# endif // WITH_MPI + /** eoPopEvalFunc: This abstract class is for GLOBAL evaluators * of a population after variation. * It takes 2 populations (typically the parents and the offspring) @@ -77,6 +87,142 @@ private: eoEvalFunc & eval; }; +#ifdef WITH_MPI +/** + * @brief Evaluator of a population of EOT which uses parallelization to evaluate individuals. + * + * This class implements an instance of eoPopEvalFunc that applies a private eoEvalFunc to + * all offspring, but in a parallel way. The original process becomes the central host from a network ("master"), and + * other machines disponible in the MPI network ("slaves") are used as evaluators. Population to evaluate is splitted in + * little packets of individuals, which are sent to the evaluators, that process the effective call to eval. Once all + * the individuals have been evaluated, they are returned to the master. The whole process is entirely invisible to the + * eyes of the user, who just has to launch a certain number of processes in MPI so as to have a result. + * + * The eoEvalFunc is no more directly given, but it is stored in the eo::mpi::ParallelApplyStore, which can be + * instanciated if no one is given at construction. + * + * The use of this class requires the user to have called the eo::mpi::Node::init function, at the beginning of its + * program. + * + * @ingroup Evaluation Parallel + * + * @author Benjamin Bouvier + */ +template +class eoParallelPopLoopEval : public eoPopEvalFunc +{ + public: + /** + * @brief Constructor which creates the job store for the user. + * + * This constructor is the simplest to use, as it creates the store used by the parallel job, for the user. + * The user just precises the scheduling algorithm, the rank of the master and then gives its eval function and + * the size of a packet (how many individuals should be in a single message to evaluator). + * + * @param _assignAlgo The scheduling algorithm used to give orders to evaluators. + * @param _masterRank The MPI rank of the master. + * @param _eval The evaluation functor used to evaluate each individual in the population. + * @param _packetSize The number of individuals to send in one message to evaluator, and which are evaluated at + * a time. + */ + eoParallelPopLoopEval( + // Job parameters + eo::mpi::AssignmentAlgorithm& _assignAlgo, + int _masterRank, + // Default parameters for store + eoEvalFunc & _eval, + int _packetSize = 1 + ) : + assignAlgo( _assignAlgo ), + masterRank( _masterRank ), + needToDeleteStore( true ) // we used new, we'll have to use delete (RAII) + { + store = new eo::mpi::ParallelApplyStore( _eval, _masterRank, _packetSize ); + } + + /** + * @brief Constructor which allows the user to customize its job store. + * + * This constructor allows the user to customize the store, for instance by adding wrappers and other + * functionnalities, before using it for the parallelized evaluation. + * + * @param _assignAlgo The scheduling algorithm used to give orders to evaluators. + * @param _masterRank The MPI rank of the master. + * @param _store Pointer to a parallel eval store given by the user. + */ + eoParallelPopLoopEval( + // Job parameters + eo::mpi::AssignmentAlgorithm& _assignAlgo, + int _masterRank, + eo::mpi::ParallelApplyStore* _store + ) : + assignAlgo( _assignAlgo ), + masterRank( _masterRank ), + store( _store ), + needToDeleteStore( false ) // we haven't used new for creating store, we don't care if we have to delete it (RAII). + { + // empty + } + + /** + * @brief Default destructor. Sends a message to all evaluators indicating that the global loop (eoEasyEA, for + * instance) is over. + */ + ~eoParallelPopLoopEval() + { + // Only the master has to send the termination message + if( eo::mpi::Node::comm().rank() == masterRank ) + { + eo::mpi::EmptyJob job( assignAlgo, masterRank ); + job.run(); + } + + // RAII + if( needToDeleteStore ) + { + delete store; + } + } + + /** + * @brief Parallel implementation of the operator(). + * + * @param _parents Population of parents (ignored). + * @param _offspring Population of children, which will be evaluated. + */ + void operator()( eoPop & _parents, eoPop & _offspring ) + { + (void)_parents; + // Reinits the store and the scheduling algorithm + store->data( _offspring ); + // For static scheduling, it's mandatory to reinit attributions + int nbWorkers = assignAlgo.availableWorkers(); + assignAlgo.reinit( nbWorkers ); + if( ! eo::parallel.isDynamic() ) { + store->data()->packetSize = ceil( static_cast( _offspring.size() ) / nbWorkers ); + } + // Effectively launches the job. + eo::mpi::ParallelApply job( assignAlgo, masterRank, *store ); + job.run(); + } + + private: + // Scheduling algorithm + eo::mpi::AssignmentAlgorithm & assignAlgo; + // Master MPI rank + int masterRank; + + // Store + eo::mpi::ParallelApplyStore* store; + // Do we have to delete the store by ourselves ? + bool needToDeleteStore; +}; + +/** + * @example t-mpi-eval.cpp + */ +#endif + ///////////////////////////////////////////////////////////// // eoTimeVaryingLoopEval ///////////////////////////////////////////////////////////// diff --git a/eo/src/eoProportionalCombinedOp.h b/eo/src/eoProportionalCombinedOp.h index 60c478903..823ac79c9 100644 --- a/eo/src/eoProportionalCombinedOp.h +++ b/eo/src/eoProportionalCombinedOp.h @@ -186,6 +186,7 @@ public: virtual std::string className() const { return "eoPropCombinedQuadOp"; } + /* FIXME remove in next release virtual void add(eoQuadOp & _op, const double _rate, bool _verbose) { #ifndef DEPRECATED_MESSAGES @@ -195,6 +196,7 @@ public: add(_op,_rate); } + */ // addition of a true operator virtual void add(eoQuadOp & _op, const double _rate) @@ -202,7 +204,7 @@ public: ops.push_back(&_op); rates.push_back(_rate); // compute the relative rates in percent - to warn the user! - printOn( eo::log << eo::logging ); + printOn( eo::log << eo::logging ); } // outputs the operators and percentages diff --git a/eo/src/eoRankMuSelect.h b/eo/src/eoRankMuSelect.h new file mode 100644 index 000000000..6e0a737ea --- /dev/null +++ b/eo/src/eoRankMuSelect.h @@ -0,0 +1,54 @@ +/* +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 +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Copyright (C) 2012 Thales group +*/ +/* +Authors: + Johann Dréo +*/ + + +#ifndef _eoRankMuSelect_h +#define _eoRankMuSelect_h + +#include "eoDetSelect.h" + +/** Selects the "Mu" bests individuals. + * + * Note: sorts the population before trucating it. + * + * @ingroup Selectors +*/ +template +class eoRankMuSelect : public eoDetSelect +{ +public : + // false, because mu is not a rate + eoRankMuSelect( unsigned int mu ) : eoDetSelect( mu, false ) {} + + void operator()(const eoPop& source, eoPop& dest) + { + eoPop tmp( source ); + tmp.sort(); + eoDetSelect::operator()( tmp, dest ); + } +}; + +#endif // !_eoRankMuselect_h diff --git a/eo/src/eoSteadyFitContinue.h b/eo/src/eoSteadyFitContinue.h index 229d93bc1..f05697b50 100644 --- a/eo/src/eoSteadyFitContinue.h +++ b/eo/src/eoSteadyFitContinue.h @@ -35,23 +35,26 @@ @ingroup Continuators */ template< class EOT> -class eoSteadyFitContinue: public eoContinue +class eoSteadyFitContinue: public eoCountContinue { public: typedef typename EOT::Fitness Fitness; + using eoCountContinue::thisGenerationPlaceholder; + using eoCountContinue::thisGeneration; + /// Ctor for setting a eoSteadyFitContinue( unsigned long _minGens, unsigned long _steadyGens) - : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGens), - steadyState(false), thisGenerationPlaceHolder(0), - thisGeneration(thisGenerationPlaceHolder){}; + : eoCountContinue( ), repMinGenerations( _minGens ), repSteadyGenerations( _steadyGens), + steadyState(false) + {}; /// Ctor for enabling the save/load the no. of generations counted eoSteadyFitContinue( unsigned long _minGens, unsigned long _steadyGen, unsigned long& _currentGen) - : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGen), - steadyState(_currentGen>_minGens), thisGenerationPlaceHolder(0), - thisGeneration(_currentGen){}; + : eoCountContinue( _currentGen ), repMinGenerations( _minGens ), repSteadyGenerations( _steadyGen), + steadyState(_currentGen>_minGens) + {}; /** Returns false when a certain number of generations is * reached withtout improvement */ @@ -96,7 +99,7 @@ public: /// Resets the state after it's been reached virtual void reset () { steadyState=false; - thisGeneration = 0; + eoCountContinue::reset(); } /** accessors*/ @@ -110,8 +113,6 @@ private: unsigned long repMinGenerations; unsigned long repSteadyGenerations; bool steadyState; - unsigned long thisGenerationPlaceHolder; - unsigned long& thisGeneration; unsigned int lastImprovement; Fitness bestSoFar; }; diff --git a/eo/src/es/CMakeLists.txt b/eo/src/es/CMakeLists.txt index 593f5df8f..4f924bfe6 100644 --- a/eo/src/es/CMakeLists.txt +++ b/eo/src/es/CMakeLists.txt @@ -2,19 +2,19 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Define the es and cma targets ###################################################################################### -SET(ES_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) -SET(CMA_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) +set(ES_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(CMA_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) -SET(LIBRARY_OUTPUT_PATH ${ES_LIB_OUTPUT_PATH}) # the same output for the two libs +set(LIBRARY_OUTPUT_PATH ${ES_LIB_OUTPUT_PATH}) # the same output for the two libs -SET(ES_SOURCES +set(ES_SOURCES make_algo_scalar_es.cpp make_algo_scalar_real.cpp make_checkpoint_es.cpp @@ -31,26 +31,26 @@ SET(ES_SOURCES make_run_real.cpp ) -SET(CMA_SOURCES +set(CMA_SOURCES eig.cpp CMAState.cpp CMAParams.cpp ) -ADD_LIBRARY(es STATIC ${ES_SOURCES}) -INSTALL(TARGETS es ARCHIVE DESTINATION ${LIB} COMPONENT libraries) +add_library(es STATIC ${ES_SOURCES}) +install(TARGETS es ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) -ADD_LIBRARY(cma STATIC ${CMA_SOURCES}) -INSTALL(TARGETS cma ARCHIVE DESTINATION ${LIB} COMPONENT libraries) +add_library(cma STATIC ${CMA_SOURCES}) +install(TARGETS cma ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) ###################################################################################### ### 3) Optionnal ###################################################################################### -SET(ES_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(es PROPERTIES VERSION "${ES_VERSION}") +set(ES_VERSION ${GLOBAL_VERSION}) +set_target_properties(es PROPERTIES VERSION "${ES_VERSION}") -SET(CMA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(cma PROPERTIES VERSION "${CMA_VERSION}") +set(CMA_VERSION ${GLOBAL_VERSION}) +set_target_properties(cma PROPERTIES VERSION "${CMA_VERSION}") ###################################################################################### diff --git a/eo/src/ga/CMakeLists.txt b/eo/src/ga/CMakeLists.txt index ffc6683f7..a2ee1033b 100644 --- a/eo/src/ga/CMakeLists.txt +++ b/eo/src/ga/CMakeLists.txt @@ -2,17 +2,17 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Define the ga target ###################################################################################### -SET(GA_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) -SET(LIBRARY_OUTPUT_PATH ${GA_LIB_OUTPUT_PATH}) +set(GA_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${GA_LIB_OUTPUT_PATH}) -SET(GA_SOURCES +set(GA_SOURCES make_algo_scalar_ga.cpp make_checkpoint_ga.cpp make_continue_ga.cpp @@ -22,14 +22,17 @@ SET(GA_SOURCES make_run_ga.cpp ) -ADD_LIBRARY(ga STATIC ${GA_SOURCES}) -INSTALL(TARGETS ga ARCHIVE DESTINATION ${LIB} COMPONENT libraries) +add_library(ga STATIC ${GA_SOURCES}) +install(TARGETS ga ARCHIVE DESTINATION lib COMPONENT libraries) + +file(GLOB HDRS *.h) +install(FILES ${HDRS} DESTINATION include/eo/ga COMPONENT headers) ###################################################################################### ### 3) Optionnal ###################################################################################### -SET(GA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(ga PROPERTIES VERSION "${GA_VERSION}") +set(GA_VERSION ${GLOBAL_VERSION}) +set_target_properties(ga PROPERTIES VERSION "${GA_VERSION}") ###################################################################################### diff --git a/eo/src/mpi/CMakeLists.txt b/eo/src/mpi/CMakeLists.txt new file mode 100644 index 000000000..bed081847 --- /dev/null +++ b/eo/src/mpi/CMakeLists.txt @@ -0,0 +1,35 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the eompi target +###################################################################################### + +set(EOMPI_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${EOMPI_LIB_OUTPUT_PATH}) + +set(EOMPI_SOURCES + eoMpi.cpp + eoMpiAssignmentAlgorithm.cpp + eoMpiNode.cpp + implMpi.cpp + ) + +add_library(eompi STATIC ${EOMPI_SOURCES}) +install(TARGETS eompi ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) + +file(GLOB HDRS *.h) +install(FILES ${HDRS} DESTINATION local/include${INSTALL_SUB_DIR}/eo/mpi COMPONENT headers) + +###################################################################################### +### 3) Optionnal +###################################################################################### + +set(EOMPI_VERSION ${GLOBAL_VERSION}) +set_target_properties(eompi PROPERTIES VERSION "${EOMPI_VERSION}") + +###################################################################################### diff --git a/eo/src/mpi/eoMpi.cpp b/eo/src/mpi/eoMpi.cpp new file mode 100644 index 000000000..cceb403b5 --- /dev/null +++ b/eo/src/mpi/eoMpi.cpp @@ -0,0 +1,48 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "eoMpi.h" + +namespace eo +{ + namespace mpi + { + /********************************************** + * *********** GLOBALS ************************ + * *******************************************/ + eoTimerStat timerStat; + + namespace Channel + { + const int Commands = 0; + const int Messages = 1; + } + + namespace Message + { + const int Continue = 0; + const int Finish = 1; + const int Kill = 2; + } + + const int DEFAULT_MASTER = 0; + } +} diff --git a/eo/src/mpi/eoMpi.h b/eo/src/mpi/eoMpi.h new file mode 100644 index 000000000..a47ce8a33 --- /dev/null +++ b/eo/src/mpi/eoMpi.h @@ -0,0 +1,868 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EO_MPI_H__ +# define __EO_MPI_H__ + +# include // std::vector + +# include +# include +# include +# include + +# include "eoMpiNode.h" +# include "eoMpiAssignmentAlgorithm.h" + +namespace eo +{ + /** + * @ingroup Parallel + * @defgroup MPI Message Passing Interface + * @brief See namespace eo::mpi to have all explanations about this module. + * @{ + */ + + /** + * @brief MPI parallelization helpers for EO. + * + * This namespace contains parallelization functions which help to parallelize computations in EO. It is based on a + * generic algorithm, which is then customized with functors, corresponding to the algorithm main steps. These + * computations are centralized, i.e there is one central host whose role is to handle the steps of the algorithm ; + * we call it the "master". The other hosts just have to perform a "dummy" computation, which may be any kind of + * processing ; we call them, the "slaves", or less pejoratively, the "workers". Workers can communicate to each + * other, but they receive their orders from the Master and send him back some results. A worker can also be the + * master of a different parallelization process, as soon as it is a part of its work. Machines of the network, also + * called hosts, are identified by an unique number: their rank. At any time during the execution of the program, + * all the hosts know the total number of hosts. + * + * A parallelized Job is a set of tasks which are independant (i.e can be executed in random order without + * modifiying the result) and take a data input and compute a data output to be sent to the Master. The data can be + * of any type, however they have to be serialized to be sent over a network. It is sufficient that they can be + * serialized through boost. + * + * @todo For serialization purposes, don't depend upon boost. It would be easy to use only eoserial and send strings + * via mpi. + * + * The main steps of the algorithm are the following: + * - For the master: + * - Have we done with the treatment we are doing ? + * - If this is the case, we can quit. + * - Otherwise, send an input data to some available worker. + * - If there's no available worker, wait for a worker to be free. + * - When receiving the response, handle it (eventually compute something on the output data, store it...). + * - Go back to the first step. + * - For the worker, it is even easier: + * - Wait for an order. + * - If there's nothing to do, just quit. + * - Otherwise, eventually retrieve data and do the work. + * - Go back to the first step. + * + * There is of course some network adjustements to do and precisions to give there, but the main ideas are present. As the + * job is fully centralized, this is the master who tells the workers when to quit and when to work. + * + * The idea behind these MPI helpers is to be the most generic possible. If we look back at the steps of the + * algorithm, we found that the steps can be splitted into 2 parts: the first consists in the steps of any + * parallelization algorithm and the other consists in the specific parts of the algorithm. Ideally, the user should + * just have to implement the specific parts of the algorithm. We identified these parts to be: + * - For the master: + * - What does mean to have terminated ? There are only two alternatives, in our binary world: either it is + * terminated, or it is not. Hence we only need a function returning a boolean to know if we're done with the + * computation : we'll call it IsFinished. + * - What do we have to do when we send a task ? We don't have any a priori on the form of the sent data, or + * the number of sent data. Moreover, as the tasks are all independant, we don't care of who will do the + * computation, as soon as it's done. Knowing the rank of the worker will be sufficient to send him data. We + * have identified another function, taking a single argument which is the rank of the worker: we'll call it + * SendTask. + * - What do we have to do when we receive a response from a worker ? One more time, we don't know which form + * or structure can have the receive data, only the user can know. Also we let the user the charge to retrieve + * the data ; he just has to know from who the master will retrieve the data. Here is another function, taking + * a rank (the sender's one) as a function argument : this will be HandleResponse. + * - For the worker: + * - What is the processing ? It can have any nature. We just need to be sure that a data is sent back to the + * master, but it seems difficult to check that: it will be the role of the user to assert that data is sent by + * the worker at the end of an execution. We've got identified our last function: ProcessTask. + * + * In term of implementation, it would be annoying to have only abstract classes with these 4 methods to implement. It + * would mean that if you want to alter just one of these 4 functions, you have to implement a new sub class, with a + * new constructor which could have the same signature. Besides, this fashion doesn't allow you to add dynamic + * functionalities, using the design pattern Decorator for instance, without implement a class for each type of + * decoration you want to add. For these reasons, we decided to transform function into functors ; the user can then + * wrap the existing, basic comportments into more sophisticated computations, whenever he wants, and without the + * notion of order. We retrieve here the power of extension given by the design pattern Decorator. + * + * Our 4 functors could have a big amount of data in common (see eoParallelApply to have an idea). + * So as to make it easy for the user to implement these 4 functors, we consider that these functors + * have to share a common data structure. This data structure is referenced (as a pointer) in the 4 functors, so the + * user doesn't need to pass a lot of parameters to each functor constructor. + * + * There are two kinds of jobs: + * - The job which are launched a fixed and well known amount of times, i.e both master and workers know how many + * times they will be launched. They are "one shot jobs". + * - The job which are launched an unknown amount of times, for instance embedded in a while loop for which we don't + * know the amount of repetitions (typically, eoEasyEA loop is a good example, as we don't know the continuator + * condition). They are called "multi job". + * As the master tells the workers to quit, we have to differentiate these two kinds of jobs. When the job is of the + * kind "multi job", the workers would have to perform a while(true) loop so as to receive the orders ; but even if + * the master tells them to quit, they would begin another job and wait for another order, while the master would + * have quit: this would cause a deadlock and workers processes would be blocked, waiting for an order. + */ + namespace mpi + { + /** + * @brief A timer which allows user to generate statistics about computation times. + */ + extern eoTimerStat timerStat; + + /** + * @brief Tags used in MPI messages for framework communication + * + * These tags are used for framework communication and fits "channels", so as to differentiate when we're + * sending an order to a worker (Commands) or data (Messages). They are not reserved by the framework and can be + * used by the user, but he is not bound to. + * + * @ingroup MPI + */ + namespace Channel + { + extern const int Commands; + extern const int Messages; + } + + /** + * @brief Simple orders used by the framework. + * + * These orders are sent by the master to the workers, to indicate to them if they should receive another task + * to do (Continue), if an one shot job is done (Finish) or if a multi job is done (Kill). + * + * @ingroup MPI + */ + namespace Message + { + extern const int Continue; + extern const int Finish; + extern const int Kill; + } + + /** + * @brief If the job only has one master, the user can use this constant, so as not to worry with integer ids. + * + * @ingroup MPI + */ + extern const int DEFAULT_MASTER; + + /** + * @brief Base class for the 4 algorithm functors. + * + * This class can embed a data (JobData) and a wrapper, so as to make all the 4 functors wrappable. + * We can add a wrapper at initialization or at any time when executing the program. + * + * According to RAII, the boolean needDelete helps to know if we have to use the operator delete on the wrapper + * or not. Hence, if any functor is wrapped, user has just to put this boolean to true, to indicate to wrapper + * that it should call delete. This allows to mix wrapper initialized in the heap (with new) or in the stack. + * + * @param JobData a Data type, which can have any form. It can a struct, a single int, anything. + * + * @param Wrapped the type of the functor, which will be stored as a pointer under the name _wrapped. + * This allows to wrap directly the functor in functors of the same type + * here, instead of dealing with SharedDataFunction* that we would have to cast all the time. + * Doing also allows to handle the wrapped functor as the functor we're writing, when coding the wrappers, + * instead of doing some static_cast. For instance, if there are 2 functors subclasses, fA and fB, fA + * implementing doFa() and fB implementing doFb(), we could have the following code: + * @code + * struct fA_wrapper + * { + * // some code + * void doFa() + * { + * _wrapped->doFa(); + * std::cout << "I'm a fA wrapper!" << std::endl; + * // if we didn't have the second template parameter, but a SharedDataFunction, we would have to do this: + * static_cast(_wrapped)->doFa(); + * // do other things (it's a wrapper) + * } + * }; + * + * struct fB_wrapper + * { + * // some code + * void doFb() + * { + * _wrapped->doFb(); // and not: static_cast(_wrapped)->doFb(); + * } + * }; + * @endcode + * This makes the code easier to write for the user. + * + * @ingroup MPI + */ + template< typename JobData, typename Wrapped > + struct SharedDataFunction + { + /** + * @brief Default constructor. + * + * The user is not bound to give a wrapped functor. + */ + SharedDataFunction( Wrapped * w = 0 ) : _data( 0 ), _wrapped( w ), _needDelete( false ) + { + // empty + } + + /** + * @brief Destructor. + * + * Calls delete on the wrapped function, only if necessary. + */ + virtual ~SharedDataFunction() + { + if( _wrapped && _wrapped->needDelete() ) + { + delete _wrapped; + } + } + + /** + * @brief Setter for the wrapped function. + * + * It doesn't do anything on the current wrapped function, like deleting it. + */ + void wrapped( Wrapped * w ) + { + _wrapped = w; + } + + /** + * @brief Setter for the data present in the functor. + * + * Calls the setter on the functor and on the wrapped functors, in a Composite pattern fashion. + */ + void data( JobData* d ) + { + _data = d; + if( _wrapped ) + { + _wrapped->data( d ); + } + } + + /** + * @brief Returns true if we need to use operator delete on this wrapper, false otherwise. + * + * Allows the user to reject delete responsability to the framework, by setting this value to true. + **/ + bool needDelete() { return _needDelete; } + void needDelete( bool b ) { _needDelete = b; } + + protected: + JobData* _data; + Wrapped* _wrapped; // Pointer and not a reference so as to be set at any time and to avoid affectation + bool _needDelete; + }; + + /** + * @brief Functor (master side) used to send a task to the worker. + * + * The user doesn't have to know which worker will receive a task, so we just indicate to master the rank of the + * worker. The data used for computation have to be explicitly sent by the master to the worker, with indicated + * rank. Once this functor has been called, the worker is considered busy until it sends a return message to the + * master. + * + * This is a functor implementing void operator()(int), and also a shared data function, containing wrapper on its + * own type. + * + * @ingroup MPI + */ + template< typename JobData > + struct SendTaskFunction : public eoUF, public SharedDataFunction< JobData, SendTaskFunction > + { + public: + + SendTaskFunction( SendTaskFunction* w = 0 ) : SharedDataFunction >( w ) + { + // empty + } + + virtual ~SendTaskFunction() {} // for inherited classes + }; + + /** + * @brief Functor (master side) used to indicate what to do when receiving a response. + * + * The master calls this function as soon as it receives some data, in some channel. Thanks to MPI, we retrieve + * the rank of the data's sender. This functor is then called with this rank. There is no memoization of a link + * between sent data and rank, so the user has to implement it, if he needs it. + * + * This is a functor implementing void operator()(int), and also a shared data function, containing wrapper on + * its own type. + * + * The master has to receive worker's data on channel (= MPI tag) eo::mpi::Channel::Messages. No other tags are + * allowed. + * + * @ingroup MPI + */ + template< typename JobData > + struct HandleResponseFunction : public eoUF, public SharedDataFunction< JobData, HandleResponseFunction > + { + public: + + HandleResponseFunction( HandleResponseFunction* w = 0 ) : SharedDataFunction >( w ) + { + // empty + } + + virtual ~HandleResponseFunction() {} // for inherited classes + }; + + /** + * @brief Functor (worker side) implementing the processing to do. + * + * This is where the real computation happen. + * Whenever the master sends the command "Continue" to workers, which indicates the worker will receive a task, + * the worker calls this functor. The user has to explicitly retrieve the data, handle it and transmit it, + * processed, back to the master. Data sent back needs to be transmitted via channel (= MPI tag) + * eo::mpi::Channel::Messages, and no one else. If the worker does not send any data back to the master, the latter will + * consider the worker isn't done and a deadlock could occur. + * + * This is a functor implementing void operator()(), and also a shared data function, containing wrapper on its + * own type. + * + * @ingroup MPI + */ + template< typename JobData > + struct ProcessTaskFunction : public eoF, public SharedDataFunction< JobData, ProcessTaskFunction > + { + public: + + ProcessTaskFunction( ProcessTaskFunction* w = 0 ) : SharedDataFunction >( w ) + { + // empty + } + + virtual ~ProcessTaskFunction() {} // for inherited classes + }; + + /** + * @brief Functor (master side) indicating whether the job is done or not. + * + * The master loops on this functor to know when to stop. When this functor returns true, the master will wait + * for the last responses and properly stops the job. Whenever this functor returns false, the master will send + * tasks, until this functor returns true. + * + * This is a functor implementing bool operator()(), and also a shared function, containing wrapper on its own + * type. + * + * @ingroup MPI + */ + template< typename JobData > + struct IsFinishedFunction : public eoF, public SharedDataFunction< JobData, IsFinishedFunction > + { + public: + + IsFinishedFunction( IsFinishedFunction* w = 0 ) : SharedDataFunction >( w ) + { + // empty + } + + virtual ~IsFinishedFunction() {} // for inherited classes + }; + + /** + * @brief Contains all the required data and the functors to launch a job. + * + * Splitting the functors and data from the job in itself allows to use the same functors and data for multiples + * instances of the same job. You define your store once and can use it a lot of times during your program. If + * the store was included in the job, you'd have to give again all the functors and all the datas to each + * invokation of the job. + * + * Job store contains the 4 functors (pointers, so as to be able to wrap them ; references couldn't have + * permitted that) described above and the JobData used by all these functors. It contains + * also helpers to easily wrap the functors, getters and setters on all of them. + * + * The user has to implement data(), which is the getter for retrieving JobData. We don't have any idea of who + * owns the data, moreover it is impossible to initialize it in this generic JobStore, as we don't know its + * form. As a matter of fact, the user has to define this in the JobStore subclasses. + * + * @ingroup MPI + */ + template< typename JobData > + struct JobStore + { + /** + * @brief Default ctor with the 4 functors. + */ + JobStore( + SendTaskFunction* stf, + HandleResponseFunction* hrf, + ProcessTaskFunction* ptf, + IsFinishedFunction* iff + ) : + _stf( stf ), _hrf( hrf ), _ptf( ptf ), _iff( iff ) + { + // empty + } + + /** + * @brief Empty ctor, useful for not forcing users to call the other constructor. + * + * When using this constructor, the user have to care about the 4 functors pointers, otherwise null pointer + * segfaults have to be expected. + */ + JobStore() + { + // empty + } + + /** + * @brief Default destructor. + * + * JobStore is the highest layer which calls needDelete on its functors. + */ + ~JobStore() + { + if( _stf->needDelete() ) delete _stf; + if( _hrf->needDelete() ) delete _hrf; + if( _ptf->needDelete() ) delete _ptf; + if( _iff->needDelete() ) delete _iff; + } + + // Getters + SendTaskFunction & sendTask() { return *_stf; } + HandleResponseFunction & handleResponse() { return *_hrf; } + ProcessTaskFunction & processTask() { return *_ptf; } + IsFinishedFunction & isFinished() { return *_iff; } + + // Setters + void sendTask( SendTaskFunction* stf ) + { + if( !stf ) + return; + + if( _stf && _stf->needDelete() ) + { + delete _stf; + } + _stf = stf; + } + + void handleResponse( HandleResponseFunction* hrf ) + { + if( !hrf ) + return; + + if( _hrf && _hrf->needDelete() ) + { + delete _hrf; + } + _hrf = hrf; + } + + void processTask( ProcessTaskFunction* ptf ) + { + if( !ptf ) + return; + + if( _ptf && _ptf->needDelete() ) + { + delete _ptf; + } + _ptf = ptf; + } + + void isFinished( IsFinishedFunction* iff ) + { + if( !iff ) + return; + + if( _iff && _iff->needDelete() ) + { + delete _iff; + } + _iff = iff; + } + + /** + * @brief Helpers for wrapping send task functor. + */ + void wrapSendTask( SendTaskFunction* stf ) + { + if( stf ) + { + stf->wrapped( _stf ); + _stf = stf; + } + } + + /** + * @brief Helpers for wrapping handle response functor. + */ + void wrapHandleResponse( HandleResponseFunction* hrf ) + { + if( hrf ) + { + hrf->wrapped( _hrf ); + _hrf = hrf; + } + } + + /** + * @brief Helpers for wrapping process task functor. + */ + void wrapProcessTask( ProcessTaskFunction* ptf ) + { + if( ptf ) + { + ptf->wrapped( _ptf ); + _ptf = ptf; + } + } + + /** + * @brief Helpers for wrapping is finished functor. + */ + void wrapIsFinished( IsFinishedFunction* iff ) + { + if( iff ) + { + iff->wrapped( _iff ); + _iff = iff; + } + } + + virtual JobData* data() = 0; + + protected: + + SendTaskFunction< JobData >* _stf; + HandleResponseFunction< JobData >* _hrf; + ProcessTaskFunction< JobData >* _ptf; + IsFinishedFunction< JobData >* _iff; + }; + + /** + * @example t-mpi-wrapper.cpp + */ + + /** + * @brief Class implementing the centralized job algorithm. + * + * This class handles all the job algorithm. With its store and its assignment (scheduling) algorithm, it + * executes the general algorithm described above, adding some networking, so as to make the global process + * work. It initializes all the functors with the data, then launches the main loop, indicating to workers when + * they will have to work and when they will finish, by sending them a termination message (integer that can be + * customized). As the algorithm is centralized, it is also mandatory to indicate what is the MPI rank of the + * master process, hence the workers will know from who they should receive their commands. + * + * Any of the 3 master functors can launch exception, it will be catched and rethrown as a std::runtime_exception + * to the higher layers. + * + * @ingroup MPI + */ + template< class JobData > + class Job + { + public: + /** + * @brief Main constructor for Job. + * + * @param _algo The used assignment (scheduling) algorithm. It has to be initialized, with its maximum + * possible number of workers (some workers referenced in this algorithm shouldn't be busy). See + * AssignmentAlgorithm for more details. + * + * @param _masterRank The MPI rank of the master. + * + * @param _workerStopCondition Number of the message which will cause the workers to terminate. It could + * be one of the constants defined in eo::mpi::Commands, or any other integer. The user has to be sure + * that a message containing this integer will be sent to each worker on the Commands channel, otherwise + * deadlock will happen. Master sends Finish messages at the end of a simple job, but as a job can + * happen multiples times (multi job), workers don't have to really finish on these messages but on + * another message. This is here where you can configurate it. See also OneShotJob and MultiJob. + * + * @param store The JobStore containing functors and data for this job. + */ + Job( AssignmentAlgorithm& _algo, + int _masterRank, + int _workerStopCondition, + JobStore & _store + ) : + assignmentAlgo( _algo ), + masterRank( _masterRank ), + workerStopCondition( _workerStopCondition ), + comm( Node::comm() ), + // Functors + store( _store ), + sendTask( _store.sendTask() ), + handleResponse( _store.handleResponse() ), + processTask( _store.processTask() ), + isFinished( _store.isFinished() ) + { + _isMaster = Node::comm().rank() == _masterRank; + + sendTask.data( _store.data() ); + handleResponse.data( _store.data() ); + processTask.data( _store.data() ); + isFinished.data( _store.data() ); + } + + protected: + + /** + * @brief Finally block of the main algorithm + * + * Herb Sutter's trick for having a finally block, in a try/catch section: invoke a class at the + * beginning of the try, its destructor will be called in every cases. + * + * This implements the end of the master algorithm: + * - sends to all available workers that they are free, + * - waits for last responses, handles them and sends termination messages to last workers. + */ + struct FinallyBlock + { + FinallyBlock( + int _totalWorkers, + AssignmentAlgorithm& _algo, + Job< JobData > & _that + ) : + totalWorkers( _totalWorkers ), + assignmentAlgo( _algo ), + that( _that ), + // global field + comm( Node::comm() ) + { + // empty + } + + ~FinallyBlock() + { + eo::log << eo::debug << "[M" << comm.rank() << "] Frees all the idle." << std::endl; + + // frees all the idle workers + timerStat.start("master_wait_for_idles"); + std::vector idles = assignmentAlgo.idles(); + for(unsigned int i = 0; i < idles.size(); ++i) + { + comm.send( idles[i], Channel::Commands, Message::Finish ); + } + timerStat.stop("master_wait_for_idles"); + + eo::log << eo::debug << "[M" << comm.rank() << "] Waits for all responses." << std::endl; + + // wait for all responses + timerStat.start("master_wait_for_all_responses"); + while( assignmentAlgo.availableWorkers() != totalWorkers ) + { + bmpi::status status = comm.probe( bmpi::any_source, eo::mpi::Channel::Messages ); + int wrkRank = status.source(); + that.handleResponse( wrkRank ); + comm.send( wrkRank, Channel::Commands, Message::Finish ); + assignmentAlgo.confirm( wrkRank ); + } + timerStat.stop("master_wait_for_all_responses"); + + eo::log << eo::debug << "[M" << comm.rank() << "] Leaving master task." << std::endl; + } + + protected: + + int totalWorkers; + AssignmentAlgorithm& assignmentAlgo; + Job< JobData > & that; + + bmpi::communicator & comm; + }; + + /** + * @brief Master part of the job. + * + * Launches the parallelized job algorithm : while there is something to do (! IsFinished ), get a + * worker who will be the assignee ; if no worker is available, wait for a response, handle it and reask + * for an assignee. Then send the command and the task. + * Once there is no more to do (IsFinished), indicate to all available workers that they're free, wait + * for all the responses and send termination messages (see also FinallyBlock). + */ + void master( ) + { + int totalWorkers = assignmentAlgo.availableWorkers(); + eo::log << eo::debug << "[M" << comm.rank() << "] Have " << totalWorkers << " workers." << std::endl; + + try { + FinallyBlock finally( totalWorkers, assignmentAlgo, *this ); + while( ! isFinished() ) + { + timerStat.start("master_wait_for_assignee"); + int assignee = assignmentAlgo.get( ); + while( assignee <= 0 ) + { + eo::log << eo::debug << "[M" << comm.rank() << "] Waitin' for node..." << std::endl; + + bmpi::status status = comm.probe( bmpi::any_source, eo::mpi::Channel::Messages ); + int wrkRank = status.source(); + + eo::log << eo::debug << "[M" << comm.rank() << "] Node " << wrkRank << " just terminated." << std::endl; + + handleResponse( wrkRank ); + assignmentAlgo.confirm( wrkRank ); + assignee = assignmentAlgo.get( ); + } + timerStat.stop("master_wait_for_assignee"); + + eo::log << eo::debug << "[M" << comm.rank() << "] Assignee : " << assignee << std::endl; + + timerStat.start("master_wait_for_send"); + comm.send( assignee, Channel::Commands, Message::Continue ); + sendTask( assignee ); + timerStat.stop("master_wait_for_send"); + } + } catch( const std::exception & e ) + { + std::string s = e.what(); + s.append( " in eoMpi loop"); + throw std::runtime_error( s ); + } + } + + /** + * @brief Worker part of the algorithm. + * + * The algorithm is more much simpler: wait for an order; if it's termination message, leave. Otherwise, + * prepare to work. + */ + void worker( ) + { + int order; + + timerStat.start("worker_wait_for_order"); + comm.recv( masterRank, Channel::Commands, order ); + timerStat.stop("worker_wait_for_order"); + + while( true ) + { + eo::log << eo::debug << "[W" << comm.rank() << "] Waiting for an order..." << std::endl; + + if ( order == workerStopCondition ) + { + eo::log << eo::debug << "[W" << comm.rank() << "] Leaving worker task." << std::endl; + return; + } else if( order == Message::Continue ) + { + eo::log << eo::debug << "[W" << comm.rank() << "] Processing task..." << std::endl; + processTask( ); + } + + timerStat.start("worker_wait_for_order"); + comm.recv( masterRank, Channel::Commands, order ); + timerStat.stop("worker_wait_for_order"); + } + } + + public: + + /** + * @brief Launches the job algorithm, according to the role of the host (roles are deduced from the + * master rank indicated in the constructor). + */ + void run( ) + { + ( _isMaster ) ? master( ) : worker( ); + } + + /** + * @brief Returns true if the current host is the master, false otherwise. + */ + bool isMaster( ) + { + return _isMaster; + } + + protected: + + AssignmentAlgorithm& assignmentAlgo; + int masterRank; + const int workerStopCondition; + bmpi::communicator& comm; + + JobStore& store; + SendTaskFunction & sendTask; + HandleResponseFunction & handleResponse; + ProcessTaskFunction & processTask; + IsFinishedFunction & isFinished; + + bool _isMaster; + }; + + /** + * @brief Job that will be launched only once. + * + * As explained in eo::mpi documentation, jobs can happen either a well known amount of times or an unknown + * amount of times. This class implements the general case when the job is launched a well known amount of + * times. The job will be terminated on both sides (master and worker) once the master would have said it. + * + * It uses the message Message::Finish as the termination message. + * + * @ingroup MPI + */ + template< class JobData > + class OneShotJob : public Job< JobData > + { + public: + OneShotJob( AssignmentAlgorithm& algo, + int masterRank, + JobStore & store ) + : Job( algo, masterRank, Message::Finish, store ) + { + // empty + } + }; + + /** + * @brief Job that will be launched an unknown amount of times, in worker side. + * + * As explained in eo::mpi documentation, jobs can happen either a well known amount of times or an unknown + * amount of times. This class implements the general case when the job is launched an unknown amount of times, for + * instance in a while loop. The master will run many jobs (or the same job many times), but the workers will + * launch it only once. + * + * It uses the message Message::Kill as the termination message. This message can be launched with an EmptyJob, + * launched only by the master. If no Message::Kill is sent on the Channels::Commands, the worker will wait + * forever, which will cause a deadlock. + * + * @ingroup MPI + */ + template< class JobData > + class MultiJob : public Job< JobData > + { + public: + MultiJob ( AssignmentAlgorithm& algo, + int masterRank, + JobStore & store ) + : Job( algo, masterRank, Message::Kill, store ) + { + // empty + } + }; + } + + /** + * @} + */ +} +# endif // __EO_MPI_H__ + diff --git a/eo/src/mpi/eoMpiAssignmentAlgorithm.cpp b/eo/src/mpi/eoMpiAssignmentAlgorithm.cpp new file mode 100644 index 000000000..39ce02f18 --- /dev/null +++ b/eo/src/mpi/eoMpiAssignmentAlgorithm.cpp @@ -0,0 +1,224 @@ +# include "eoMpiAssignmentAlgorithm.h" +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "eoMpiNode.h" + +namespace eo +{ + namespace mpi + { + const int REST_OF_THE_WORLD = -1; + + /******************************************************** + * DYNAMIC ASSIGNMENT ALGORITHM ************************* + *******************************************************/ + + DynamicAssignmentAlgorithm::DynamicAssignmentAlgorithm( ) + { + for(int i = 1; i < Node::comm().size(); ++i) + { + availableWrk.push_back( i ); + } + } + + DynamicAssignmentAlgorithm::DynamicAssignmentAlgorithm( int unique ) + { + availableWrk.push_back( unique ); + } + + DynamicAssignmentAlgorithm::DynamicAssignmentAlgorithm( const std::vector & workers ) + { + availableWrk = workers; + } + + DynamicAssignmentAlgorithm::DynamicAssignmentAlgorithm( int first, int last ) + { + if( last == REST_OF_THE_WORLD ) + { + last = Node::comm().size() - 1; + } + + for( int i = first; i <= last; ++i) + { + availableWrk.push_back( i ); + } + } + + int DynamicAssignmentAlgorithm::get( ) + { + int assignee = -1; + if (! availableWrk.empty() ) + { + assignee = availableWrk.back(); + availableWrk.pop_back(); + } + return assignee; + } + + int DynamicAssignmentAlgorithm::availableWorkers() + { + return availableWrk.size(); + } + + void DynamicAssignmentAlgorithm::confirm( int rank ) + { + availableWrk.push_back( rank ); + } + + std::vector DynamicAssignmentAlgorithm::idles( ) + { + return availableWrk; + } + + void DynamicAssignmentAlgorithm::reinit( int _ ) + { + ++_; + // nothing to do + } + + /******************************************************** + * STATIC ASSIGNMENT ALGORITHM ************************** + *******************************************************/ + + StaticAssignmentAlgorithm::StaticAssignmentAlgorithm( const std::vector& workers, int runs ) + { + init( workers, runs ); + } + + StaticAssignmentAlgorithm::StaticAssignmentAlgorithm( int first, int last, int runs ) + { + std::vector workers; + + if( last == REST_OF_THE_WORLD ) + { + last = Node::comm().size() - 1; + } + + for(int i = first; i <= last; ++i) + { + workers.push_back( i ); + } + init( workers, runs ); + } + + StaticAssignmentAlgorithm::StaticAssignmentAlgorithm( int runs ) + { + std::vector workers; + for(int i = 1; i < Node::comm().size(); ++i) + { + workers.push_back( i ); + } + + init( workers, runs ); + } + + StaticAssignmentAlgorithm::StaticAssignmentAlgorithm( int unique, int runs ) + { + std::vector workers; + workers.push_back( unique ); + init( workers, runs ); + } + + void StaticAssignmentAlgorithm::init( const std::vector & workers, int runs ) + { + unsigned int nbWorkers = workers.size(); + freeWorkers = nbWorkers; + + busy.clear(); + busy.resize( nbWorkers, false ); + realRank = workers; + + if( runs <= 0 ) + { + return; + } + + attributions.clear(); + attributions.reserve( nbWorkers ); + + // Let be the euclidean division of runs by nbWorkers : + // runs == q * nbWorkers + r, 0 <= r < nbWorkers + // This one liner affects q requests to each worker + for (unsigned int i = 0; i < nbWorkers; attributions[i++] = runs / nbWorkers) ; + // The first line computes r and the one liner affects the remaining + // r requests to workers, in ascending order + unsigned int diff = runs - (runs / nbWorkers) * nbWorkers; + for (unsigned int i = 0; i < diff; ++attributions[i++]); + } + + int StaticAssignmentAlgorithm::get( ) + { + int assignee = -1; + for( unsigned i = 0; i < busy.size(); ++i ) + { + if( !busy[i] && attributions[i] > 0 ) + { + busy[i] = true; + --freeWorkers; + assignee = realRank[ i ]; + break; + } + } + return assignee; + } + + int StaticAssignmentAlgorithm::availableWorkers( ) + { + return freeWorkers; + } + + std::vector StaticAssignmentAlgorithm::idles() + { + std::vector ret; + for(unsigned int i = 0; i < busy.size(); ++i) + { + if( !busy[i] ) + { + ret.push_back( realRank[i] ); + } + } + return ret; + } + + void StaticAssignmentAlgorithm::confirm( int rank ) + { + int i = -1; // i is the real index in table + for( unsigned int j = 0; j < realRank.size(); ++j ) + { + if( realRank[j] == rank ) + { + i = j; + break; + } + } + + --attributions[ i ]; + busy[ i ] = false; + ++freeWorkers; + } + + void StaticAssignmentAlgorithm::reinit( int runs ) + { + init( realRank, runs ); + } + } +} diff --git a/eo/src/mpi/eoMpiAssignmentAlgorithm.h b/eo/src/mpi/eoMpiAssignmentAlgorithm.h new file mode 100644 index 000000000..abe465b8b --- /dev/null +++ b/eo/src/mpi/eoMpiAssignmentAlgorithm.h @@ -0,0 +1,239 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __MPI_ASSIGNMENT_ALGORITHM_H__ +# define __MPI_ASSIGNMENT_ALGORITHM_H__ + +# include // std::vector + +namespace eo +{ + namespace mpi + { + /** + * @brief Constant indicating to use all the resting available workers, in assignment algorithms constructor + * using an interval. + * + * @ingroup MPI + */ + extern const int REST_OF_THE_WORLD; + + /** + * @brief Contains informations on the available workers and allows to find assignees for jobs. + * + * Available workers are workers who aren't processing anything. When they've received an order, workers switch + * from the state "available" to the state "busy", and the master has to wait for their response for considering + * them available again. + * + * @ingroup MPI + */ + struct AssignmentAlgorithm + { + /** + * @brief Gets the rank of an available worker, so as to send it a task. + * + * @return The MPI rank of an available worker, or -1 if there is no available worker. + */ + virtual int get( ) = 0; + + /** + * @brief Gets the number of total available workers. + * + * Before the first call, it is equal to the total number of present workers, as specified in the + * specific assignment algorithm constructor. It allows the Job class to know when all the responses have + * been received, by comparing this number to the total number of workers. + * + * @return Integer indicating how many workers are available. + */ + virtual int availableWorkers( ) = 0; + + /** + * @brief Reinject the worker of indicated rank in the available state. + * + * @param wrkRank The MPI rank of the worker who has finished its job. + */ + virtual void confirm( int wrkRank ) = 0; + + /** + * @brief Indicates who are the workers which do nothing. + * + * At the end of the algorithm, the master has to warn all the workers that it's done. All the workers mean, + * the workers which are currently processing data, and the other ones who could be waiting : the idles. + * This function indicates to the master which worker aren't doing anything. + * + * @return A std::vector containing all the MPI ranks of the idles workers. + */ + virtual std::vector idles( ) = 0; + + /** + * @brief Reinitializes the assignment algorithm with the right number of runs. + * + * In fact, this is only useful for static assignment algorithm, which has to be reinitialized every time + * it's used, in the case of a Multi Job. It's the user's responsability to call this function. + * + * @todo Not really clean. Find a better way to do it. + */ + virtual void reinit( int runs ) = 0; + }; + + /** + * @brief Assignment (scheduling) algorithm which handles workers in a queue. + * + * With this assignment algorithm, workers are put in a queue and may be called an unlimited number of times. + * Whenever a worker returns, it is added to the queue, and it becomes available for the next call to get(). + * The available workers are all located in the queue at any time, so the number of available workers is + * directly equal to the size of the queue. + * + * This kind of assignment is adapted for tasks whose execution time is stochastic or unknown, but without any + * warranty to be faster than other assignments. + * + * @ingroup MPI + */ + struct DynamicAssignmentAlgorithm : public AssignmentAlgorithm + { + public: + + /** + * @brief Uses all the hosts whose rank is higher to 1, inclusive, as workers. + */ + DynamicAssignmentAlgorithm( ); + + /** + * @brief Uses the unique host with given rank as a worker. + * + * @param unique MPI rank of the unique worker. + */ + DynamicAssignmentAlgorithm( int unique ); + + /** + * @brief Uses the workers whose ranks are present in the argument as workers. + * + * @param workers std::vector containing MPI ranks of workers. + */ + DynamicAssignmentAlgorithm( const std::vector & workers ); + + /** + * @brief Uses a range of ranks as workers. + * + * @param first The first worker to be included (inclusive) + * @param last The last worker to be included (inclusive). If last == eo::mpi::REST_OF_THE_WORLD, all + * hosts whose rank is higher than first are taken. + */ + DynamicAssignmentAlgorithm( int first, int last ); + + virtual int get( ); + + int availableWorkers(); + + void confirm( int rank ); + + std::vector idles( ); + + void reinit( int _ ); + + protected: + std::vector< int > availableWrk; + }; + + /** + * @brief Assignment algorithm which gives to each worker a precise number of tasks to do, in a round robin + * fashion. + * + * This scheduling algorithm attributes, at initialization or when calling reinit(), a fixed amount of runs to + * distribute to the workers. The amount of runs is then equally distributed between all workers ; if total + * number of runs is not a direct multiple of workers number, then remainding unaffected runs are distributed to + * workers from the first to the last, in a round-robin fashion. + * + * This scheduling should be used when the amount of runs can be computed or is fixed and when we guess that the + * duration of processing task will be the same for each run. There is no warranty that this algorithm is more + * or less efficient that another one. When having a doubt, use DynamicAssignmentAlgorithm. + * + * @ingroup MPI + */ + struct StaticAssignmentAlgorithm : public AssignmentAlgorithm + { + public: + /** + * @brief Uses a given precise set of workers. + * + * @param workers std::vector of MPI ranks of workers which will be used. + * @param runs Fixed amount of runs, strictly positive. + */ + StaticAssignmentAlgorithm( const std::vector& workers, int runs ); + + /** + * @brief Uses a range of workers. + * + * @param first The first MPI rank of worker to use + * @param last The last MPI rank of worker to use. If it's equal to REST_OF_THE_WORLD, then all the + * workers from the first one are taken as workers. + * @param runs Fixed amount of runs, strictly positive. + */ + StaticAssignmentAlgorithm( int first, int last, int runs ); + + /** + * @brief Uses all the hosts whose rank is higher than 1 (inclusive) as workers. + * + * @param runs Fixed amount of runs, strictly positive. If it's not set, you'll have to call reinit() + * later. + */ + StaticAssignmentAlgorithm( int runs = 0 ); + + /** + * @brief Uses an unique host as worker. + * + * @param unique The MPI rank of the host which will be the worker. + * @param runs Fixed amount of runs, strictly positive. + */ + StaticAssignmentAlgorithm( int unique, int runs ); + + private: + /** + * @brief Initializes the static scheduling. + * + * Gives to each worker an equal attribution number, equal to runs / workers.size(), eventually plus one + * if number of workers is not a divisor of runs. + * + * @param workers Vector of hosts' ranks + * @param runs Fixed amount of runs, strictly positive. + */ + void init( const std::vector & workers, int runs ); + + public: + int get( ); + + int availableWorkers( ); + + std::vector idles(); + + void confirm( int rank ); + + void reinit( int runs ); + + private: + std::vector attributions; + std::vector realRank; + std::vector busy; + unsigned int freeWorkers; + }; + } +} +# endif // __MPI_ASSIGNMENT_ALGORITHM_H__ diff --git a/eo/src/mpi/eoMpiNode.cpp b/eo/src/mpi/eoMpiNode.cpp new file mode 100644 index 000000000..69f06576b --- /dev/null +++ b/eo/src/mpi/eoMpiNode.cpp @@ -0,0 +1,40 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "eoMpiNode.h" + +namespace eo +{ + namespace mpi + { + void Node::init( int argc, char** argv ) + { + static bmpi::environment env( argc, argv ); + } + + bmpi::communicator& Node::comm() + { + return _comm; + } + + bmpi::communicator Node::_comm; + } +} diff --git a/eo/src/mpi/eoMpiNode.h b/eo/src/mpi/eoMpiNode.h new file mode 100644 index 000000000..c370e1c0b --- /dev/null +++ b/eo/src/mpi/eoMpiNode.h @@ -0,0 +1,65 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __MPI_NODE_H__ +# define __MPI_NODE_H__ + +# include "implMpi.h" +namespace bmpi = mpi; + +namespace eo +{ + namespace mpi + { + /** + * @brief Global object used to reach mpi::communicator everywhere. + * + * mpi::communicator is the main object used to send and receive messages between the different hosts of + * a MPI algorithm. + * + * @ingroup MPI + */ + class Node + { + public: + + /** + * @brief Initializes the MPI environment with argc and argv. + * + * Should be called at the beginning of every parallel program. + * + * @param argc Main's argc + * @param argv Main's argv + */ + static void init( int argc, char** argv ); + + /** + * @brief Returns the global mpi::communicator + */ + static bmpi::communicator& comm(); + + protected: + static bmpi::communicator _comm; + }; + } +} +# endif // __MPI_NODE_H__ + diff --git a/eo/src/mpi/eoMultiStart.h b/eo/src/mpi/eoMultiStart.h new file mode 100644 index 000000000..23a8cc04a --- /dev/null +++ b/eo/src/mpi/eoMultiStart.h @@ -0,0 +1,515 @@ +# ifndef __EO_MULTISTART_H__ +# define __EO_MULTISTART_H__ + +# include +# include "eoMpi.h" + +/** + * @ingroup MPI + * @{ + */ + +/** + * @file eoMultiStart.h + * + * Contains implementation of a MPI job which consists in a multi start, which basically consists in the following: + * the same eoAlgo is launched on computers of a clusters, with different seeds for each. As the eoAlgo are most of + * the time stochastics, the results won't be the same. It is fully equivalent to launch the same program but with + * different seeds. + * + * It follows the structure of a MPI job, as described in eoMpi.h. The basic algorithm is trivial: + * - Loop while we have a run to perform. + * - Worker performs runs and send their best solution (individual with best fitness) to the master. + * - Master retrieves the best solution and adds it to a eoPop of best solutions (the user can chooses what he does + * with this population, for instance: retrieve the best element, etc.) + * + * The principal concerns about this algorithm are: + * - How do we reinitialize the algorithm? An eoAlgo can have several forms, and initializations have to be performed + * before each "start". We can hence decide whether we reinits the population or keep the same population obtained + * after the previous start, we have to reinitialize continuator, etc. This is customizable in the store. + * + * - Which seeds should be chosen? If we want the run to be re-runnable with the same results, we need to be sure that + * the seeds are the same. But user can not care about this, and just want random seeds. This is customizable in the + * store. + * + * These concerns are handled by functors, inheriting from MultiStartStore::ResetAlgo (for the first concern), and + * MultiStartStore::GetSeeds (for the second one). There are default implementations, but there is no problem about + * specializing them or coding your own, by directly inheriting from them. + * + * @ingroup MPI + */ + +namespace eo +{ + namespace mpi + { + /** + * @brief Data used by the Multi Start job. + * + * This data is shared between the different Job functors. More details are given for each attribute. + */ + template< class EOT > + struct MultiStartData + { + typedef eoUF< eoPop&, void> ResetAlgo; + + MultiStartData( + bmpi::communicator& _comm, + eoAlgo& _algo, + int _masterRank, + ResetAlgo & _resetAlgo ) + : + runs( 0 ), bests(), pop(), + comm( _comm ), algo( _algo ), resetAlgo( _resetAlgo ), masterRank( _masterRank ) + { + // empty + } + + // dynamic parameters + /** + * @brief Total remaining number of runs. + * + * It's decremented as the runs are performed. + */ + int runs; + + /** + * @brief eoPop of the best individuals, which are the one sent by the workers. + */ + eoPop< EOT > bests; + + /** + * @brief eoPop on which the worker is working. + */ + eoPop< EOT > pop; + + // static parameters + /** + * @brief Communicator, used to send and retrieve messages. + */ + bmpi::communicator& comm; + + /** + * @brief Algorithm which will be performed by the worker. + */ + eoAlgo& algo; + + /** + * @brief Reset Algo functor, which defines how to reset the algo (above) before re running it. + */ + ResetAlgo& resetAlgo; + + // Rank of master + int masterRank; + }; + + /** + * @brief Send task (master side) in the Multi Start job. + * + * It only consists in decrementing the number of runs, as the worker already have the population and + * all the necessary parameters to run the eoAlgo. + */ + template< class EOT > + class SendTaskMultiStart : public SendTaskFunction< MultiStartData< EOT > > + { + public: + using SendTaskFunction< MultiStartData< EOT > >::_data; + + void operator()( int wrkRank ) + { + wrkRank++; // unused + --(_data->runs); + } + }; + + /** + * @brief Handle Response (master side) in the Multi Start job. + * + * It consists in retrieving the best solution sent by the worker and adds it to a population of best + * solutions. + */ + template< class EOT > + class HandleResponseMultiStart : public HandleResponseFunction< MultiStartData< EOT > > + { + public: + using HandleResponseFunction< MultiStartData< EOT > >::_data; + + void operator()( int wrkRank ) + { + EOT individual; + MultiStartData< EOT >& d = *_data; + d.comm.recv( wrkRank, eo::mpi::Channel::Messages, individual ); + d.bests.push_back( individual ); + } + }; + + /** + * @brief Process Task (worker side) in the Multi Start job. + * + * Consists in resetting the algorithm and launching it on the population, then + * send the best individual (the one with the best fitness) to the master. + */ + template< class EOT > + class ProcessTaskMultiStart : public ProcessTaskFunction< MultiStartData< EOT > > + { + public: + using ProcessTaskFunction< MultiStartData >::_data; + + void operator()() + { + _data->resetAlgo( _data->pop ); + _data->algo( _data->pop ); + _data->comm.send( _data->masterRank, eo::mpi::Channel::Messages, _data->pop.best_element() ); + } + }; + + /** + * @brief Is Finished (master side) in the Multi Start job. + * + * The job is finished if and only if all the runs have been performed. + */ + template< class EOT > + class IsFinishedMultiStart : public IsFinishedFunction< MultiStartData< EOT > > + { + public: + using IsFinishedFunction< MultiStartData< EOT > >::_data; + + bool operator()() + { + return _data->runs <= 0; + } + }; + + /** + * @brief Store for the Multi Start job. + * + * Contains the data used by the workers (algo,...) and functor to + * send the seeds. + */ + template< class EOT > + class MultiStartStore : public JobStore< MultiStartData< EOT > > + { + public: + + /** + * @brief Generic functor to reset an algorithm before it's launched by + * the worker. + * + * This reset algorithm should reinits population (if necessary), continuator, etc. + */ + typedef typename MultiStartData::ResetAlgo ResetAlgo; + + /** + * @brief Generic functor which returns a vector of seeds for the workers. + * + * If this vector hasn't enough seeds to send, random ones are generated and + * sent to the workers. + */ + typedef eoUF< int, std::vector > GetSeeds; + + /** + * @brief Default ctor for MultiStartStore. + * + * @param algo The algorithm to launch in parallel + * @param masterRank The MPI rank of the master + * @param resetAlgo The ResetAlgo functor + * @param getSeeds The GetSeeds functor + */ + MultiStartStore( + eoAlgo & algo, + int masterRank, + ResetAlgo & resetAlgo, + GetSeeds & getSeeds + ) + : _data( eo::mpi::Node::comm(), algo, masterRank, resetAlgo ), + _getSeeds( getSeeds ), + _masterRank( masterRank ) + { + // Default job functors for this one. + this->_iff = new IsFinishedMultiStart< EOT >; + this->_iff->needDelete(true); + this->_stf = new SendTaskMultiStart< EOT >; + this->_stf->needDelete(true); + this->_hrf = new HandleResponseMultiStart< EOT >; + this->_hrf->needDelete(true); + this->_ptf = new ProcessTaskMultiStart< EOT >; + this->_ptf->needDelete(true); + } + + /** + * @brief Send new seeds to the workers before a job. + * + * Uses the GetSeeds functor given in constructor. If there's not + * enough seeds to send, random seeds are sent to the workers. + * + * @param workers Vector of MPI ranks of the workers + * @param runs The number of runs to perform + */ + void init( const std::vector& workers, int runs ) + { + _data.runs = runs; + + unsigned nbWorkers = workers.size(); + std::vector< int > seeds = _getSeeds( nbWorkers ); + if( eo::mpi::Node::comm().rank() == _masterRank ) + { + if( seeds.size() < nbWorkers ) + { + // Random seeds + for( unsigned i = seeds.size(); i < nbWorkers; ++i ) + { + seeds.push_back( eo::rng.rand() ); + } + } + + for( unsigned i = 0 ; i < nbWorkers ; ++i ) + { + int wrkRank = workers[i]; + eo::mpi::Node::comm().send( wrkRank, eo::mpi::Channel::Commands, seeds[ i ] ); + } + } else + { + int seed; + eo::mpi::Node::comm().recv( _masterRank, eo::mpi::Channel::Commands, seed ); + eo::log << eo::debug << eo::mpi::Node::comm().rank() << "- Seed: " << seed << std::endl; + eo::rng.reseed( seed ); + } + } + + MultiStartData* data() + { + return &_data; + } + + private: + MultiStartData< EOT > _data; + GetSeeds & _getSeeds; + int _masterRank; + }; + + /** + * @brief MultiStart job, created for convenience. + * + * This is an OneShotJob, which means workers leave it along with + * the master. + */ + template< class EOT > + class MultiStart : public OneShotJob< MultiStartData< EOT > > + { + public: + + MultiStart( AssignmentAlgorithm & algo, + int masterRank, + MultiStartStore< EOT > & store, + // dynamic parameters + int runs ) : + OneShotJob< MultiStartData< EOT > >( algo, masterRank, store ) + { + store.init( algo.idles(), runs ); + } + + /** + * @brief Returns the best solution, at the end of the job. + * + * Warning: if you call this function from a worker, or from the master before the + * launch of the job, you will only get an empty population! + * + * @return Population of best individuals retrieved by the master. + */ + eoPop& best_individuals() + { + return this->store.data()->bests; + } + }; + + /************************************* + * DEFAULT GET SEEDS IMPLEMENTATIONS * + ************************************/ + + /** + * @brief Uses the internal default seed generator to get seeds, + * which means: random seeds are sent. + */ + template + struct DummyGetSeeds : public MultiStartStore::GetSeeds + { + std::vector operator()( int n ) + { + return std::vector(); + } + }; + + /** + * @brief Sends seeds to the workers, which are multiple of a number + * given by the master. If no number is given, a random one is used. + * + * This functor ensures that even if the same store is used with + * different jobs, the seeds will be different. + */ + template + struct MultiplesOfNumber : public MultiStartStore::GetSeeds + { + MultiplesOfNumber ( int n = 0 ) + { + while( n == 0 ) + { + n = eo::rng.rand(); + } + _seed = n; + _i = 0; + } + + std::vector operator()( int n ) + { + std::vector ret; + for( unsigned int i = 0; i < n; ++i ) + { + ret.push_back( (++_i) * _seed ); + } + return ret; + } + + private: + + unsigned int _seed; + unsigned int _i; + }; + + /** + * @brief Returns random seeds to the workers. We can controle which seeds are generated + * by precising the seed of the master. + */ + template + struct GetRandomSeeds : public MultiStartStore::GetSeeds + { + GetRandomSeeds( int seed ) + { + eo::rng.reseed( seed ); + } + + std::vector operator()( int n ) + { + std::vector ret; + for(int i = 0; i < n; ++i) + { + ret.push_back( eo::rng.rand() ); + } + return ret; + } + }; + + /************************************** + * DEFAULT RESET ALGO IMPLEMENTATIONS * + **************************************/ + + /** + * @brief For a Genetic Algorithm, reinits the population by copying the original one + * given in constructor, and reinits the continuator. + * + * The evaluator should also be given, as the population needs to be evaluated + * before each run. + */ + template + struct ReuseOriginalPopEA: public MultiStartStore::ResetAlgo + { + ReuseOriginalPopEA( + eoCountContinue & continuator, + const eoPop& originalPop, + eoEvalFunc& eval) : + _continuator( continuator ), + _originalPop( originalPop ), + _pop_eval( eval ) + { + // empty + } + + ReuseOriginalPopEA( + eoCountContinue & continuator, + const eoPop& originalPop, + eoPopEvalFunc& pop_eval + ) : + _continuator( continuator ), + _originalPop( originalPop ), + _pop_eval( pop_eval ) + { + // empty + } + + void operator()( eoPop& pop ) + { + pop = _originalPop; // copies the original population + _pop_eval( pop, pop ); + _continuator.reset(); + } + + private: + eoCountContinue & _continuator; + const eoPop& _originalPop; + eoPopEvalFunc& _pop_eval; + }; + + /** + * @brief For a Genetic Algorithm, reuses the same population without + * modifying it after a run. + * + * This means, if you launch a run after another one, you'll make evolve + * the same population. + * + * The evaluator should also be sent, as the population needs to be evaluated + * at the first time. + */ + template< class EOT > + struct ReuseSamePopEA : public MultiStartStore::ResetAlgo + { + ReuseSamePopEA( + eoCountContinue& continuator, + const eoPop& originalPop, + eoEvalFunc& eval + ) : + _continuator( continuator ), + _originalPop( originalPop ), + _firstTime( true ) + { + for( unsigned i = 0, size = originalPop.size(); + i < size; ++i ) + { + eval(_originalPop[i]); + } + } + + ReuseSamePopEA( + eoCountContinue& continuator, + const eoPop& originalPop, + eoPopEvalFunc& pop_eval + ) : + _continuator( continuator ), + _originalPop( originalPop ), + _firstTime( true ) + { + pop_eval( _originalPop, _originalPop ); + } + + void operator()( eoPop& pop ) + { + if( _firstTime ) + { + pop = _originalPop; + _firstTime = false; + } + _continuator.reset(); + } + + protected: + + eoCountContinue& _continuator; + eoPop _originalPop; + bool _firstTime; + }; + } // namespace mpi +} // namespace eo + +/** + * @} + */ + +# endif // __EO_MULTISTART_H__ diff --git a/eo/src/mpi/eoParallelApply.h b/eo/src/mpi/eoParallelApply.h new file mode 100644 index 000000000..671c3843f --- /dev/null +++ b/eo/src/mpi/eoParallelApply.h @@ -0,0 +1,387 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EO_PARALLEL_APPLY_H__ +# define __EO_PARALLEL_APPLY_H__ + +# include "eoMpi.h" + +# include // eoUF +# include // std::vector population + +/** + * @file eoParallelApply.h + * + * @brief Applies a functor with single parameter to elements of a table, in a parallel fashion. + * + * This file contains all the required classes to do a parallel apply of a table, in a parallel fashion. This can be + * very useful when applying the function can be made without any dependances within the data. In EO, it occurs in + * particular during the evaluation: the number of individuals to evaluate can be really high, and the evaluation of one + * individual is independant from the evaluation of other individuals. + * + * Elements in the table are directly replaced, as the table is given by reference. No new table is made during the + * process. + * + * User can tune this job, indicating how many elements of the table should be sent and evaluated by a worker, at a + * time: this is called the "packet size", as individuals are groupped into a packet of individuals which are sent to + * the worker before evaluation. The problem of choosing the optimal packet size is beyond the purposes of this documentation + * and deserves a theoritical study. + * + * This job is the parallel equivalent to the function apply, defined in apply.h. It just applies the function to + * every element of a table. In Python or Javascript, it's the equivalent of the function Map. + */ + +namespace eo +{ + namespace mpi + { + /** + * @brief Structure used to save assignment to a worker, i.e which slice of the table it has to process. + * + * This slice is defined by the index of the first evaluated argument and the number of processed elements. + */ + struct ParallelApplyAssignment + { + int index; + int size; + }; + + /** + * @brief Data useful for a parallel apply (map). + * + * A parallel apply needs at least the functor to apply to every element of the table, and the table itself, + * whereas it can be set later with the function init(). Master rank is also needed, to send it informations and + * receive informations from it, inside the functors (the job knows these values, but the functors don't). The + * size of a packet can be tuned here. + * + * Internal attributes contain: + * - (useful for master) the index of the next element to be evaluated. + * - (useful for master) a map containing links between MPI ranks and slices of the table which the worker with + * this rank has evaluated. Without this map, when receiving results from a worker, the master couldn't be + * able to replace the right elements in the table. + * + * @ingroup MPI + */ + template + struct ParallelApplyData + { + /** + * @brief Ctor for Parallel apply (map) data. + * + * @param _proc The functor to apply on each element in the table + * @param _masterRank The MPI rank of the master + * @param _packetSize The number of elements on which the function will be applied by the worker, at a time. + * @param table The table to apply. If this value is NULL, user will have to call init() before launching the + * job. + */ + ParallelApplyData( + eoUF & _proc, + int _masterRank, + int _packetSize, + std::vector * table = 0 + ) : + _table( table ), func( _proc ), index( 0 ), packetSize( _packetSize ), masterRank( _masterRank ), comm( Node::comm() ) + { + if ( _packetSize <= 0 ) + { + throw std::runtime_error("Packet size should not be negative."); + } + + if( table ) + { + size = table->size(); + } + } + + /** + * @brief Reinitializes the data for a new table to evaluate. + */ + void init( std::vector& table ) + { + index = 0; + size = table.size(); + _table = &table; + assignedTasks.clear(); + } + + std::vector& table() + { + return *_table; + } + + // All elements are public since functors will often use them. + std::vector * _table; + eoUF & func; + int index; + int size; + std::map< int /* worker rank */, ParallelApplyAssignment /* last assignment */> assignedTasks; + int packetSize; + std::vector tempArray; + + int masterRank; + bmpi::communicator& comm; + }; + + /** + * @brief Send task functor implementation for the parallel apply (map) job. + * + * Master side: Sends a slice of the table to evaluate to the worker. + * + * Implementation details: + * Finds the next slice of data to send to the worker, sends first the size and then the data, and memorizes + * that this slice has been distributed to the worker, then updates the next position of element to evaluate. + */ + template< class EOT > + class SendTaskParallelApply : public SendTaskFunction< ParallelApplyData > + { + public: + using SendTaskFunction< ParallelApplyData >::_data; + + SendTaskParallelApply( SendTaskParallelApply * w = 0 ) : SendTaskFunction< ParallelApplyData >( w ) + { + // empty + } + + void operator()(int wrkRank) + { + int futureIndex; + + if( _data->index + _data->packetSize < _data->size ) + { + futureIndex = _data->index + _data->packetSize; + } else { + futureIndex = _data->size; + } + + int sentSize = futureIndex - _data->index ; + + _data->comm.send( wrkRank, eo::mpi::Channel::Messages, sentSize ); + + eo::log << eo::debug << "Evaluating individual " << _data->index << std::endl; + + _data->assignedTasks[ wrkRank ].index = _data->index; + _data->assignedTasks[ wrkRank ].size = sentSize; + + _data->comm.send( wrkRank, eo::mpi::Channel::Messages, & ( (_data->table())[ _data->index ] ) , sentSize ); + _data->index = futureIndex; + } + }; + + /** + * @brief Handle response functor implementation for the parallel apply (map) job. + * + * Master side: Replaces the slice of data attributed to the worker in the table. + */ + template< class EOT > + class HandleResponseParallelApply : public HandleResponseFunction< ParallelApplyData > + { + public: + using HandleResponseFunction< ParallelApplyData >::_data; + + HandleResponseParallelApply( HandleResponseParallelApply * w = 0 ) : HandleResponseFunction< ParallelApplyData >( w ) + { + // empty + } + + void operator()(int wrkRank) + { + _data->comm.recv( wrkRank, eo::mpi::Channel::Messages, & (_data->table()[ _data->assignedTasks[wrkRank].index ] ), _data->assignedTasks[wrkRank].size ); + } + }; + + /** + * @brief Process task functor implementation for the parallel apply (map) job. + * + * Worker side: apply the function to the given slice of data. + * + * Implementation details: retrieves the number of elements to evaluate, retrieves them, applies the function + * and then returns the results. + */ + template< class EOT > + class ProcessTaskParallelApply : public ProcessTaskFunction< ParallelApplyData > + { + public: + using ProcessTaskFunction< ParallelApplyData >::_data; + + ProcessTaskParallelApply( ProcessTaskParallelApply * w = 0 ) : ProcessTaskFunction< ParallelApplyData >( w ) + { + // empty + } + + void operator()() + { + int recvSize; + + _data->comm.recv( _data->masterRank, eo::mpi::Channel::Messages, recvSize ); + _data->tempArray.resize( recvSize ); + _data->comm.recv( _data->masterRank, eo::mpi::Channel::Messages, & _data->tempArray[0] , recvSize ); + timerStat.start("worker_processes"); + for( int i = 0; i < recvSize ; ++i ) + { + _data->func( _data->tempArray[ i ] ); + } + timerStat.stop("worker_processes"); + _data->comm.send( _data->masterRank, eo::mpi::Channel::Messages, & _data->tempArray[0], recvSize ); + } + }; + + /** + * @brief Is finished functor implementation for the parallel apply (map) job. + * + * Master side: returns true if and only if the whole table has been evaluated. The job is also terminated only + * when the whole table has been evaluated. + */ + template< class EOT > + class IsFinishedParallelApply : public IsFinishedFunction< ParallelApplyData > + { + public: + using IsFinishedFunction< ParallelApplyData >::_data; + + IsFinishedParallelApply( IsFinishedParallelApply * w = 0 ) : IsFinishedFunction< ParallelApplyData >( w ) + { + // empty + } + + bool operator()() + { + return _data->index == _data->size; + } + }; + + /** + * @brief Store containing all the datas and the functors for the parallel apply (map) job. + * + * User can tune functors when constructing the object. For each functor which is not given, a default one is + * generated. + * + * @ingroup MPI + */ + template< class EOT > + struct ParallelApplyStore : public JobStore< ParallelApplyData > + { + using JobStore< ParallelApplyData >::_stf; + using JobStore< ParallelApplyData >::_hrf; + using JobStore< ParallelApplyData >::_ptf; + using JobStore< ParallelApplyData >::_iff; + + /** + * @brief Main constructor for the parallel apply (map) job. + * + * @param _proc The procedure to apply to each element of the table. + * @param _masterRank The rank of the master process. + * @param _packetSize The number of elements of the table to be evaluated at a time, by the worker. + * @param stpa Pointer to Send Task parallel apply functor descendant. If null, a default one is used. + * @param hrpa Pointer to Handle Response parallel apply functor descendant. If null, a default one is used. + * @param ptpa Pointer to Process Task parallel apply functor descendant. If null, a default one is used. + * @param ifpa Pointer to Is Finished parallel apply functor descendant. If null, a default one is used. + */ + ParallelApplyStore( + eoUF & _proc, + int _masterRank, + int _packetSize = 1, + // JobStore functors + SendTaskParallelApply * stpa = 0, + HandleResponseParallelApply* hrpa = 0, + ProcessTaskParallelApply* ptpa = 0, + IsFinishedParallelApply* ifpa = 0 + ) : + _data( _proc, _masterRank, _packetSize ) + { + if( stpa == 0 ) { + stpa = new SendTaskParallelApply; + stpa->needDelete( true ); + } + + if( hrpa == 0 ) { + hrpa = new HandleResponseParallelApply; + hrpa->needDelete( true ); + } + + if( ptpa == 0 ) { + ptpa = new ProcessTaskParallelApply; + ptpa->needDelete( true ); + } + + if( ifpa == 0 ) { + ifpa = new IsFinishedParallelApply; + ifpa->needDelete( true ); + } + + _stf = stpa; + _hrf = hrpa; + _ptf = ptpa; + _iff = ifpa; + } + + ParallelApplyData* data() { return &_data; } + + /** + * @brief Reinits the store with a new table to evaluate. + * + * @param _pop The table of elements to be evaluated. + */ + void data( std::vector& _pop ) + { + _data.init( _pop ); + } + + virtual ~ParallelApplyStore() // for inheritance purposes only + { + } + + protected: + ParallelApplyData _data; + }; + + /** + * @brief Parallel apply job. Present for convenience only. + * + * A typedef wouldn't have been working, as typedef on templates don't work in C++. Traits would be a + * disgraceful overload for the user. + * + * @ingroup MPI + * @see eoParallelApply.h + */ + template< typename EOT > + class ParallelApply : public MultiJob< ParallelApplyData > + { + public: + + ParallelApply( + AssignmentAlgorithm & algo, + int _masterRank, + ParallelApplyStore & store + ) : + MultiJob< ParallelApplyData >( algo, _masterRank, store ) + { + // empty + } + }; + + /** + * @example t-mpi-parallelApply.cpp + * @example t-mpi-multipleRoles.cpp + */ + } +} +# endif // __EO_PARALLEL_APPLY_H__ + + diff --git a/eo/src/mpi/eoTerminateJob.h b/eo/src/mpi/eoTerminateJob.h new file mode 100644 index 000000000..fe231f0e3 --- /dev/null +++ b/eo/src/mpi/eoTerminateJob.h @@ -0,0 +1,140 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EO_TERMINATE_H__ +# define __EO_TERMINATE_H__ + +# include "eoMpi.h" + +namespace eo +{ + namespace mpi + { + /** + * @ingroup MPI + * @{ + */ + + /** + * @brief Send task functor which does nothing. + */ + struct DummySendTaskFunction : public SendTaskFunction + { + void operator()( int _ ) + { + ++_; + } + }; + + /** + * @brief Handle response functor which does nothing. + */ + struct DummyHandleResponseFunction : public HandleResponseFunction + { + void operator()( int _ ) + { + ++_; + } + }; + + /** + * @brief Process task functor which does nothing. + */ + struct DummyProcessTaskFunction : public ProcessTaskFunction + { + void operator()() + { + // nothing! + } + }; + + /** + * @brief Is finished functor which returns true everytime. + */ + struct DummyIsFinishedFunction : public IsFinishedFunction + { + bool operator()() + { + return true; + } + }; + + /** + * @brief Job store containing all dummy functors and containing no data. + */ + struct DummyJobStore : public JobStore + { + using JobStore::_stf; + using JobStore::_hrf; + using JobStore::_ptf; + using JobStore::_iff; + + DummyJobStore() + { + _stf = new DummySendTaskFunction; + _stf->needDelete( true ); + _hrf = new DummyHandleResponseFunction; + _hrf->needDelete( true ); + _ptf = new DummyProcessTaskFunction; + _ptf->needDelete( true ); + _iff = new DummyIsFinishedFunction; + _iff->needDelete( true ); + } + + void* data() { return 0; } + }; + + /** + * @brief Job to run after a Multi Job, so as to indicate that every workers should terminate. + */ + struct EmptyJob : public OneShotJob + { + /** + * @brief Main EmptyJob ctor + * + * @param algo Assignment (scheduling) algorithm used. + * @param masterRank The rank of the master process. + */ + EmptyJob( AssignmentAlgorithm& algo, int masterRank ) : + OneShotJob( algo, masterRank, *(new DummyJobStore) ) + // the job store is deleted on destructor + { + // empty + } + + ~EmptyJob() + { + std::vector< int > idles = assignmentAlgo.idles(); + for(unsigned i = 0, size = idles.size(); i < size; ++i) + { + comm.send( idles[i], Channel::Commands, Message::Kill ); + } + delete & this->store; + } + }; + + /** + * @} + */ + } +} + +# endif // __EO_TERMINATE_H__ diff --git a/eo/src/mpi/implMpi.cpp b/eo/src/mpi/implMpi.cpp new file mode 100644 index 000000000..6ae0c0996 --- /dev/null +++ b/eo/src/mpi/implMpi.cpp @@ -0,0 +1,166 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "implMpi.h" + +namespace mpi +{ + const int any_source = MPI_ANY_SOURCE; + const int any_tag = MPI_ANY_TAG; + + environment::environment(int argc, char**argv) + { + MPI_Init(&argc, &argv); + } + + environment::~environment() + { + MPI_Finalize(); + } + + status::status( const MPI_Status & s ) + { + _source = s.MPI_SOURCE; + _tag = s.MPI_TAG; + _error = s.MPI_ERROR; + } + + communicator::communicator( ) + { + _rank = -1; + _size = -1; + + _buf = 0; + _bufsize = -1; + } + + communicator::~communicator() + { + if( _buf ) + { + delete _buf; + _buf = 0; + } + } + + int communicator::rank() + { + if ( _rank == -1 ) + { + MPI_Comm_rank( MPI_COMM_WORLD, &_rank ); + } + return _rank; + } + + int communicator::size() + { + if ( _size == -1 ) + { + MPI_Comm_size( MPI_COMM_WORLD, &_size ); + } + return _size; + } + + /* + * SEND / RECV INT + */ + void communicator::send( int dest, int tag, int n ) + { + MPI_Send( &n, 1, MPI_INT, dest, tag, MPI_COMM_WORLD ); + } + + void communicator::recv( int src, int tag, int& n ) + { + MPI_Status stat; + MPI_Recv( &n, 1, MPI_INT, src, tag, MPI_COMM_WORLD , &stat ); + } + + /* + * SEND / RECV STRING + */ + void communicator::send( int dest, int tag, const std::string& str ) + { + int size = str.size() + 1; + send( dest, tag, size ); + MPI_Send( (char*)str.c_str(), size, MPI_CHAR, dest, tag, MPI_COMM_WORLD); + } + + void communicator::recv( int src, int tag, std::string& str ) + { + int size = -1; + MPI_Status stat; + recv( src, tag, size ); + + if( _buf == 0 ) + { + _buf = new char[ size ]; + _bufsize = size; + } else if( _bufsize < size ) + { + delete [] _buf; + _buf = new char[ size ]; + _bufsize = size; + } + MPI_Recv( _buf, size, MPI_CHAR, src, tag, MPI_COMM_WORLD, &stat ); + str.assign( _buf ); + } + + /* + * SEND / RECV Objects + */ + void communicator::send( int dest, int tag, const eoserial::Persistent & persistent ) + { + eoserial::Object* obj = persistent.pack(); + std::stringstream ss; + obj->print( ss ); + delete obj; + send( dest, tag, ss.str() ); + } + + void communicator::recv( int src, int tag, eoserial::Persistent & persistent ) + { + std::string asText; + recv( src, tag, asText ); + eoserial::Object* obj = eoserial::Parser::parse( asText ); + persistent.unpack( obj ); + delete obj; + } + + /* + * Other methods + */ + status communicator::probe( int src, int tag ) + { + MPI_Status stat; + MPI_Probe( src, tag, MPI_COMM_WORLD , &stat ); + return status( stat ); + } + + void communicator::barrier() + { + MPI_Barrier( MPI_COMM_WORLD ); + } + + void broadcast( communicator & comm, int value, int root ) + { + MPI_Bcast( &value, 1, MPI_INT, root, MPI_COMM_WORLD ); + } +} diff --git a/eo/src/mpi/implMpi.h b/eo/src/mpi/implMpi.h new file mode 100644 index 000000000..b7c1cd4ba --- /dev/null +++ b/eo/src/mpi/implMpi.h @@ -0,0 +1,322 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EO_IMPL_MPI_HPP__ +# define __EO_IMPL_MPI_HPP__ + +# include +# include + +/** + * This namespace contains reimplementations of some parts of the Boost::MPI API in C++, so as to be used in + * EO without any dependance to Boost. Historically, EO's parallelization module used the + * boost library to add a layer over MPI. After having noticed that just some functions + * were really used, we decided to reimplement our own C++-like implementation of MPI. + * + * Because the Boost::MPI API is really clean, we reused it in this module. However, all + * the functions of Boost::MPI were not used, hence a subset of the API is reused. For + * instance, users can just send integer, std::string or eoserial::Persistent objects; + * furthermore, only eoserial::Persistent objects can sent in a table. + * + * The documentation of the functions is exactly the same as the official Boost::MPI + * documentation. You can find it on www.boost.org/doc/libs/1_49_0/doc/html/mpi/ + * The entities are here shortly described, if you need further details, don't hesitate + * to visit the boost URL. + */ + +namespace mpi +{ + /** + * @ingroup Parallel + * @{ + */ + + /** + * @brief Constant indicating that a message can come from any process. + */ + extern const int any_source; + + /** + * @brief Constant indicating that a message can come from any tag (channel). + */ + extern const int any_tag; + + /** + * @brief Wrapper class to have a MPI environment. + * + * Instead of calling MPI_Init and MPI_Finalize, it is only necessary to instantiate + * this class once, in the global context. + */ + class environment + { + public: + + /** + * @brief Inits MPI context. + * + * @param argc Number of params in command line (same as one in main) + * @param argv Strings containing params (same as one in main) + */ + environment(int argc, char**argv); + + /** + * @brief Closes MPI context. + */ + ~environment(); + }; + + /** + * @brief Wrapper class for MPI_Status + * + * Consists only in a C++ wrapper class, giving getters on status attributes. + */ + class status + { + public: + + /** + * @brief Converts a MPI_Status into a status. + */ + status( const MPI_Status & s ); + + /** + * @brief Returns the tag of the associated communication. + */ + int tag() { return _tag; } + + /** + * @brief Indicates which error number we obtained in the associated communication. + */ + int error() { return _error; } + + /** + * @brief Returns the MPI rank of the source of the associated communication. + */ + int source() { return _source; } + + private: + int _source; + int _tag; + int _error; + }; + + /** + * @brief Main object, used to send / receive messages, get informations about the rank and the size of the world, + * etc. + */ + class communicator + { + public: + + /** + * Creates the communicator, using the whole world as a MPI_Comm. + * + * @todo Allow the user to precise which MPI_Comm to use + */ + communicator( ); + + ~communicator(); + + /** + * @brief Returns the MPI rank of the current process. + */ + int rank(); + + /** + * @brief Returns the size of the MPI cluster. + */ + int size(); + + /* + * SEND / RECV INT + */ + + /** + * @brief Sends an integer to dest on channel "tag". + * + * @param dest MPI rank of the receiver + * @param tag MPI tag of message + * @param n The integer to send + */ + void send( int dest, int tag, int n ); + + /* + * @brief Receives an integer from src on channel "tag". + * + * @param src MPI rank of the sender + * @param tag MPI tag of message + * @param n Where to save the received integer + */ + void recv( int src, int tag, int& n ); + + /* + * SEND / RECV STRING + */ + + /** + * @brief Sends a string to dest on channel "tag". + * + * @param dest MPI rank of the receiver + * @param tag MPI tag of message + * @param str The std::string to send + */ + void send( int dest, int tag, const std::string& str ); + + /* + * @brief Receives a string from src on channel "tag". + * + * @param src MPI rank of the sender + * @param tag MPI tag of message + * @param std::string Where to save the received string + */ + void recv( int src, int tag, std::string& str ); + + /* + * SEND / RECV Objects + */ + + /** + * @brief Sends an eoserial::Persistent to dest on channel "tag". + * + * @param dest MPI rank of the receiver + * @param tag MPI tag of message + * @param persistent The object to send (it must absolutely implement eoserial::Persistent) + */ + void send( int dest, int tag, const eoserial::Persistent & persistent ); + + /** + * @brief Sends an array of eoserial::Persistent to dest on channel "tag". + * + * @param dest MPI rank of the receiver + * @param tag MPI tag of message + * @param table The array of eoserial::Persistent objects + * @param size The number of elements to send (no check is done, the user has to be sure that the size won't + * overflow!) + */ + template< class T > + void send( int dest, int tag, T* table, int size ) + { + // Puts all the values into an array + eoserial::Array* array = new eoserial::Array; + + for( int i = 0; i < size; ++i ) + { + array->push_back( table[i].pack() ); + } + + // Encapsulates the array into an object + eoserial::Object* obj = new eoserial::Object; + obj->add( "array", array ); + std::stringstream ss; + obj->print( ss ); + delete obj; + + // Sends the object as a string + send( dest, tag, ss.str() ); + } + + /* + * @brief Receives an eoserial::Persistent object from src on channel "tag". + * + * @param src MPI rank of the sender + * @param tag MPI tag of message + * @param persistent Where to unpack the serialized object? + */ + void recv( int src, int tag, eoserial::Persistent & persistent ); + + /* + * @brief Receives an array of eoserial::Persistent from src on channel "tag". + * + * @param src MPI rank of the sender + * @param tag MPI tag of message + * @param table The table in which we're saving the received objects. It must have been allocated by the user, + * as no allocation is performed here. + * @param size The number of elements to receive (no check is done, the user has to be sure that the size won't + * overflow!) + */ + template< class T > + void recv( int src, int tag, T* table, int size ) + { + // Receives the string which contains the object + std::string asText; + recv( src, tag, asText ); + + // Parses the object and retrieves the table + eoserial::Object* obj = eoserial::Parser::parse( asText ); + eoserial::Array* array = static_cast( (*obj)["array"] ); + + // Retrieves all the values from the array + for( int i = 0; i < size; ++i ) + { + eoserial::unpackObject( *array, i, table[i] ); + } + delete obj; + } + + /* + * Other methods + */ + + /** + * @brief Wrapper for MPI_Probe + * + * Waits for a message to come from process having rank src, on the channel + * tag. + * + * @param src MPI rank of the sender (any_source if it can be any sender) + * @param tag MPI tag of the expected message (any_tag if it can be any tag) + */ + status probe( int src = any_source, int tag = any_tag ); + + /** + * @brief Wrapper for MPI_Barrier + * + * + */ + void barrier(); + + private: + int _rank; + int _size; + + char* _buf; // temporary buffer for sending and receiving strings. Avoids reallocations + int _bufsize; // size of the above temporary buffer + }; + + /** + * @brief Wrapper for MPI_Bcast + * + * Broadcasts an integer value on the communicator comm, from the process having the MPI rank root. + * + * @param comm The communicator on which to broadcast + * @param value The integer value to send + * @param root The MPI rank of the broadcaster + * + * @todo Actually comm isn't used and broadcast is performed on the whole MPI_COMM_WORLD. TODO: Use comm instead + */ + void broadcast( communicator & comm, int value, int root ); + + /** + * @} + */ +} // namespace mpi + +# endif //__EO_IMPL_MPI_HPP__ diff --git a/eo/src/pyeo/CMakeLists.txt b/eo/src/pyeo/CMakeLists.txt index 962692161..05d5ec459 100644 --- a/eo/src/pyeo/CMakeLists.txt +++ b/eo/src/pyeo/CMakeLists.txt @@ -15,49 +15,49 @@ # # ---------------------------------------------------------------------------- -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) +cmake_minimum_required(VERSION 2.8) -PROJECT(PyEO) +project(PyEO) -FIND_PACKAGE(Boost 1.42 COMPONENTS python) -FIND_PACKAGE(PythonLibs) +find_package(Boost 1.42 COMPONENTS python) +find_package(PythonLibs) -INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) -INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) +include_directories(${Boost_INCLUDE_DIRS}) +include_directories(${PYTHON_INCLUDE_PATH}) -LINK_DIRECTORIES(${Boost_LIBRARY_DIRS}) +link_directories(${Boost_LIBRARY_DIRS}) -IF(APPLE) +if(APPLE) # osx internal - FIND_LIBRARY(APPLE_CARBON Carbon) -ENDIF(APPLE) + find_library(APPLE_CARBON Carbon) +endif(APPLE) # includes -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) -#INCLUDE_DIRECTORIES(../) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +#include_directories(../) # source -FILE(GLOB SOURCES *.cpp) +file(GLOB SOURCES *.cpp) # EO dependencies -SET(EO_SOURCES - ${EO_SOURCE_DIR}/src/eoFunctorStore.cpp - ${EO_SOURCE_DIR}/src/utils/eoLogger.cpp - ${EO_SOURCE_DIR}/src/utils/eoParallel.cpp +set(EO_SOURCES + ${EO_SRC_DIR}/src/eoFunctorStore.cpp + ${EO_SRC_DIR}/src/utils/eoLogger.cpp + ${EO_SRC_DIR}/src/utils/eoParallel.cpp ) # shared library -ADD_LIBRARY(PyEO MODULE ${SOURCES} ${EO_SOURCES}) -INSTALL(TARGETS PyEO LIBRARY DESTINATION ${LIB} COMPONENT libraries) +add_library(PyEO MODULE ${SOURCES} ${EO_SOURCES}) +install(TARGETS PyEO LIBRARY DESTINATION local/${LIB} COMPONENT libraries) # python 2.5 must have pyd -IF(WIN32 AND NOT CYGWIN) - SET_TARGET_PROPERTIES(PyEO PROPERTIES SUFFIX ".pyd") -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + 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}) -ELSE(APPLE) - TARGET_LINK_LIBRARIES(PyEO ${PYTHON_LIBRARY} ${Boost_LIBRARIES}) -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) diff --git a/eo/src/serial/Array.cpp b/eo/src/serial/Array.cpp new file mode 100644 index 000000000..180aad16b --- /dev/null +++ b/eo/src/serial/Array.cpp @@ -0,0 +1,58 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "Array.h" + +namespace eoserial +{ + std::ostream& Array::print( std::ostream& out ) const + { + out << "["; + bool first = true; + for (ArrayChildren::const_iterator it = begin(), + end = this->end(); + it != end; + ++it) + { + if ( first ) + { + first = false; + } else { + out << ", "; + } + (*it)->print( out ); + } + out << "]\n"; + return out; + } + + Array::~Array() + { + for (ArrayChildren::iterator it = begin(), + end = this->end(); + it != end; + ++it) + { + delete *it; + } + } + +} // namespace eoserial diff --git a/eo/src/serial/Array.h b/eo/src/serial/Array.h new file mode 100644 index 000000000..d453add99 --- /dev/null +++ b/eo/src/serial/Array.h @@ -0,0 +1,170 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_ARRAY_H__ +# define __EOSERIAL_ARRAY_H__ + +# include + +# include "Entity.h" +# include "Serializable.h" +# include "Object.h" + +namespace eoserial +{ + + // Forward declaration for below declarations. + class Array; + + /* + * Declarations of functions present in Utils.h + * These are put here to avoid instead of including the file Utils.h, which would + * cause a circular inclusion. + */ + + template< class T > + void unpack( const Array & array, unsigned int index, T & value ); + + void unpackObject( const Array & array, unsigned int index, Persistent & value ); + + template< class Container, template class UnpackAlgorithm > + void unpackArray( const Array & array, unsigned int index, Container & container ); + + /** + * @brief Represents a JSON array. + * + * Wrapper for an array, so as to be used as a JSON object. + * + * @ingroup Serialization + */ + class Array : public eoserial::Entity, public std::vector< eoserial::Entity* > + { + protected: + typedef std::vector< eoserial::Entity* > ArrayChildren; + + public: + /** + * @brief Adds the serializable object as a JSON object. + * @param obj Object which implemnets JsonSerializable. + */ + void push_back( const eoserial::Printable* obj ) + { + ArrayChildren::push_back( obj->pack() ); + } + + /** + * @brief Proxy for vector::push_back. + */ + void push_back( eoserial::Entity* json ) + { + ArrayChildren::push_back( json ); + } + + /** + * @brief Prints the JSON array into the given stream. + * @param out The stream + */ + virtual std::ostream& print( std::ostream& out ) const; + + /** + * @brief Dtor + */ + ~Array(); + + /* + * The following parts allows the user to automatically deserialize an eoserial::Array into a + * standard container, by giving the algorithm which will be used to deserialize contained entities. + */ + + /** + * @brief Functor which determines how to retrieve the real value contained in a eoserial::Entity at + * a given place. + * + * It will be applied for each contained variable in the array. + */ + template + struct BaseAlgorithm + { + /** + * @brief Main operator. + * + * @param array The eoserial::Array from which we're reading. + * @param i The index of the contained value. + * @param container The standard (STL) container in which we'll push back the read value. + */ + virtual void operator()( const eoserial::Array& array, unsigned int i, Container & container ) const = 0; + }; + + /** + * @brief BaseAlgorithm for retrieving primitive variables. + * + * This one should be used to retrieve primitive (and types which implement operator>>) variables, for instance + * int, double, std::string, etc... + */ + template + struct UnpackAlgorithm : public BaseAlgorithm + { + void operator()( const eoserial::Array& array, unsigned int i, C & container ) const + { + typename C::value_type t; + unpack( array, i, t ); + container.push_back( t ); + } + }; + + /** + * @brief BaseAlgorithm for retrieving eoserial::Persistent objects. + * + * This one should be used to retrieve objects which implement eoserial::Persistent. + */ + template + struct UnpackObjectAlgorithm : public BaseAlgorithm + { + void operator()( const eoserial::Array& array, unsigned int i, C & container ) const + { + typename C::value_type t; + unpackObject( array, i, t ); + container.push_back( t ); + } + }; + + /** + * @brief General algorithm for array deserialization. + * + * Applies the BaseAlgorithm to each contained variable in the eoserial::Array. + */ + template class UnpackAlgorithm> + inline void deserialize( Container & array ) + { + UnpackAlgorithm< Container > algo; + for( unsigned int i = 0, size = this->size(); + i < size; + ++i) + { + algo( *this, i, array ); + } + } + }; + +} // namespace eoserial + +# endif // __EOSERIAL_ARRAY_H__ + diff --git a/eo/src/serial/CMakeLists.txt b/eo/src/serial/CMakeLists.txt new file mode 100644 index 000000000..43d1ce451 --- /dev/null +++ b/eo/src/serial/CMakeLists.txt @@ -0,0 +1,35 @@ +###################################################################################### +### 1) Include the sources +###################################################################################### + +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Define the eoserial target +###################################################################################### + +set(EOSERIAL_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${EOSERIAL_LIB_OUTPUT_PATH}) + +set(EOSERIAL_SOURCES + Array.cpp + Object.cpp + Parser.cpp + String.cpp + ) + +add_library(eoserial STATIC ${EOSERIAL_SOURCES}) +install(TARGETS eoserial ARCHIVE DESTINATION lib COMPONENT libraries) + +file(GLOB HDRS *.h) +install(FILES ${HDRS} DESTINATION include/eo/serial COMPONENT headers) + +###################################################################################### +### 3) Optionnal +###################################################################################### + +set(EOSERIAL_VERSION ${GLOBAL_VERSION}) +set_target_properties(eoserial PROPERTIES VERSION "${EOSERIAL_VERSION}") + +###################################################################################### diff --git a/eo/src/serial/Entity.h b/eo/src/serial/Entity.h new file mode 100644 index 000000000..50155e13a --- /dev/null +++ b/eo/src/serial/Entity.h @@ -0,0 +1,70 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_ENTITY_H__ +# define __EOSERIAL_ENTITY_H__ + +# include // ostream + + +/** + * @brief Contains all the necessary entities to serialize eo objects into JSON objects. + * + * Allows serialization from user objects into JSON objects, if they implement the interface + * eoserial::Serializable or eoserial::Persistent. The following user objects can be serialized: + * - primitive types (int, std::string, ...), in particular every type that can be written into a + * std::stringstream. + * - objects which implement eoserial::Serializable. + * - array of serializable things (primitive or serializable objects). + * + * @ingroup Utilities + * @defgroup Serialization Serialization helpers +**/ +namespace eoserial +{ + +/** + * @brief JSON entity + * + * This class represents a JSON entity, which can be JSON objects, + * strings or arrays. It is the base class for the JSON hierarchy. + * + * @ingroup Serialization + */ +class Entity +{ +public: + + /** + * Virtual dtor (base class). + */ + virtual ~Entity() { /* empty */ } + + /** + * @brief Prints the content of a JSON object into a stream. + * @param out The stream in which we're printing. + */ + virtual std::ostream& print( std::ostream& out ) const = 0; +}; + +} // namespace eoserial + +# endif // __ENTITY_H__ diff --git a/eo/src/serial/Object.cpp b/eo/src/serial/Object.cpp new file mode 100644 index 000000000..dd859052e --- /dev/null +++ b/eo/src/serial/Object.cpp @@ -0,0 +1,60 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "Object.h" + +using namespace eoserial; + +namespace eoserial +{ + std::ostream& Object::print( std::ostream& out ) const + { + out << '{'; + bool first = true; + for(JsonValues::const_iterator it = begin(), end = this->end(); + it != end; + ++it) + { + if ( first ) + { + first = false; + } else { + out << ", "; + } + + out << '"' << it->first << "\":"; // key + it->second->print( out ); // value + } + out << "}\n"; + return out; + } + + Object::~Object() + { + for(JsonValues::iterator it = begin(), end = this->end(); + it != end; + ++it) + { + delete it->second; + } + } + +} // namespace eoserial diff --git a/eo/src/serial/Object.h b/eo/src/serial/Object.h new file mode 100644 index 000000000..9424f1c4c --- /dev/null +++ b/eo/src/serial/Object.h @@ -0,0 +1,88 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_OBJECT_H__ +# define __EOSERIAL_OBJECT_H__ + +# include +# include + +# include "Entity.h" +# include "Serializable.h" + +namespace eoserial +{ + /** + * @brief JSON Object + * + * This class represents a JSON object, which is basically a dictionnary + * of keys (strings) and values (JSON entities). + * + * @ingroup Serialization + */ + class Object : public eoserial::Entity, public std::map< std::string, eoserial::Entity* > + { + public: + typedef std::map JsonValues; + + /** + * @brief Adds a pair into the JSON object. + * @param key The key associated with the eoserial object + * @param json The JSON object as created with framework. + */ + void add( const std::string& key, eoserial::Entity* json ) + { + (*this)[ key ] = json; + } + + /** + * @brief Adds a pair into the JSON object. + * @param key The key associated with the eoserial object + * @param obj A JSON-serializable object + */ + void add( const std::string& key, const eoserial::Printable* obj ) + { + (*this)[ key ] = obj->pack(); + } + + /** + * @brief Deserializes a Serializable class instance from this JSON object. + * @param obj The object we want to rebuild. + */ + void deserialize( eoserial::Persistent & obj ) + { + obj.unpack( this ); + } + + /** + * @brief Dtor + */ + ~Object(); + + /** + * @brief Prints the content of a JSON object into a stream. + */ + virtual std::ostream& print( std::ostream& out ) const; + }; + +} // namespace eoserial +# endif // __EOSERIAL_OBJECT_H__ + diff --git a/eo/src/serial/Parser.cpp b/eo/src/serial/Parser.cpp new file mode 100644 index 000000000..258174c86 --- /dev/null +++ b/eo/src/serial/Parser.cpp @@ -0,0 +1,171 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include + +# include "Parser.h" + +# include "Array.h" +# include "Object.h" +# include "String.h" + +// in debug mode only +// # define DEBUG(x) std::cout << x << std::endl; +# define DEBUG(x) + +using namespace eoserial; + +namespace eoserial +{ + +/** + * @brief Parses a string contained between double quotes. + * + * Strings can contain escaped double quotes. + * @param str The string we're parsing. + * @param pos The index of current position in parsed string. + * This index will be updated so as to allow the parser to + * continue. + */ +static std::string parseString(const std::string& str, size_t & pos) +{ + // example : "hello" + // example 2 : "\"world\"" + // for hello: + // firstQuote == 0, secondQuote == 6 + // sub string should be from firstQuote+1 to secondQuote-1 + // so its size should be (secondQuote-1 -(firstQuote+1) + 1) + std::string value; + size_t firstQuote = str.find( '"', pos ); + size_t secondQuote; + + /* instead of just seeking the second quote, we need to ensure + // that there is no escaped quote before this one. + // actually this is harder than that. Using backslashes + // to escape double quotes mean that backslashes have to be + // escaped to. + // example : "text\\" to symbolize : text\ + // example : "text\\\" to symbolize : text\" + // In fact, we should find if number of backslashes is odd; in this case, + // the double quotes are escaped and we should find the next one. + */ + int backslashesCount; + do { + ++pos; + secondQuote = str.find( '"', pos ); + size_t i = secondQuote - 1; + + // Find the backslashes + backslashesCount = 0; + while ( str[ i ] == '\\' ) + { + --i; + ++backslashesCount; + } + pos = secondQuote; + } while( backslashesCount % 2 == 1 ); + + value = str.substr( firstQuote+1, secondQuote-firstQuote-1 ); + pos = secondQuote + 1; + return value; +} + +/** + * @brief Moves the given index pos to the next character which is + * neither a coma, a space nor a new line. + * + * @param str The string in which we want to ignores those characters. + * @param pos The index of current position in parsed string. + */ +static void ignoreChars(const std::string& str, size_t & pos) +{ + // ignore white spaces and comas + for (char current = str[ pos ]; + current == ',' || current == ' ' || current == '\n'; + current = str[ ++pos ]); +} + +String* Parser::parseJsonString(const std::string & str, size_t & pos) +{ + return new String( parseString( str, pos ) ); +} + +Object* Parser::parse(const std::string & str) +{ + size_t initial(0); // we begin at position 0 + return static_cast( parseRight(str, initial) ); +} + +Entity* Parser::parseRight(const std::string & str, size_t & pos) +{ + Entity* value = 0; + + if ( str[ pos ] == '{' ) + { + // next one is an object + DEBUG("We read an object.") + Object* obj = new Object; + pos += 1; + while( pos < str.size() && str[ pos ] != '}' ) + { + parseLeft( str, pos, obj ); + ignoreChars( str, pos ); + } + DEBUG("We just finished to read an object ! ") + pos += 1; // we're on the }, go to the next char + value = obj; + } + else if ( str[ pos ] == '"' ) + { + // next one is a string + DEBUG("We read a string") + value = parseJsonString( str, pos ); + } + else if ( str[ pos ] == '[' ) + { + // next one is an array + DEBUG("We read an array") + Array* array = new Array; + pos += 1; + while( pos < str.size() && str[ pos ] != ']' ) + { + Entity* child = parseRight( str, pos ); + if ( child ) + array->push_back( child ); + } + DEBUG("We've finished to read our array.") + pos += 1; // we're on the ], go to the next char + value = array; + } + ignoreChars( str, pos ); + return value; +} + +void Parser::parseLeft(const std::string & str, size_t & pos, Object* eoserial) +{ + std::string key = parseString(str, pos); + ++pos; // the colon + DEBUG("We've read the key ") + (*eoserial)[ key ] = parseRight( str, pos ); +} + +} // namespace eoserial + diff --git a/eo/src/serial/Parser.h b/eo/src/serial/Parser.h new file mode 100644 index 000000000..20f6a1bb2 --- /dev/null +++ b/eo/src/serial/Parser.h @@ -0,0 +1,103 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_PARSER_H__ +# define __EOSERIAL_PARSER_H__ + +# include "Entity.h" +# include "String.h" +# include "Object.h" + +/** + * @file Parser.h + * + * This file contains a tiny JSON parser used in DAE. This parser just handles + * a subset of JSON grammar, with the following restrictions : + * - all strings must be surrounded by double quotes. + * - everything which is not an object or an array is considered to be a string + * (even integers, booleans,...). + * - no syntax check is done. We trust the programmer and he has to ensure that + * every JSON string he produces is valid. + * + * @author Benjamin BOUVIER + */ + +namespace eoserial +{ + +/** + * @brief Parser from a JSON source. + * + * This parser does just retrieve values and does NOT check the structure of + * the input. This implies that if the input is not correct, the result is undefined + * and can result to a failure on execution. + * + * @ingroup Serialization + */ +class Parser +{ + public: + + /** + * @brief Parses the given string and returns the JSON object read. + */ + static eoserial::Object* parse(const std::string & str); + + protected: + + /** + * @brief Parses the right part of a JSON object as a string. + * + * The right part of an object can be a string (for instance : + * "key":"value"), a JSON array (for instance: "key":["1"]) or + * another JSON object (for instance: "key":{"another_key":"value"}). + * + * The right parts are found after keys (which are parsed by parseLeft) + * and in arrays. + * + * @param str The string we're parsing. + * @param pos The index of the current position in the string. + * @return The JSON object matching the right part. + */ + static eoserial::Entity* parseRight(const std::string & str, size_t & pos); + + /** + * @brief Parses the left value of a key-value pair, which is the key. + * + * @param str The string we're parsing. + * @param pos The index of the current position in the string. + * @param json The current JSON object for which we're adding a key-value pair. + */ + static void parseLeft(const std::string & str, size_t & pos, eoserial::Object* json); + + /** + * @brief Retrieves a string in a JSON content. + * + * @param str The string we're parsing. + * @param pos The index of the current position of parsing, + * which will be updated. + */ + static eoserial::String* parseJsonString(const std::string & str, size_t & pos); +}; + +} // namespace eoserial + +# endif // __EOSERIAL_PARSER_H__ diff --git a/eo/src/serial/Serializable.h b/eo/src/serial/Serializable.h new file mode 100644 index 000000000..715e9c973 --- /dev/null +++ b/eo/src/serial/Serializable.h @@ -0,0 +1,66 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_SERIALIZABLE_H__ +# define __EOSERIAL_SERIALIZABLE_H__ + +namespace eoserial +{ + class Object; // to avoid recursive inclusion with JsonObject + + /** + * @brief Interface showing that object can be written to a eoserial type + * (currently JSON). + * + * @ingroup Serialization + */ + class Printable + { + public: + /** + * @brief Serializes the object to JSON format. + * @return A JSON object created with new. + */ + virtual eoserial::Object* pack() const = 0; + }; + + /** + * @brief Interface showing that object can be eoserialized (written and read + * from an input). + * + * Note : Persistent objects should have a default non-arguments constructor. + * + * @ingroup Serialization + */ + class Persistent : public Printable + { + public: + /** + * @brief Loads class fields from a JSON object. + * @param json A JSON object. Programmer doesn't have to delete it, it + * is automatically done. + */ + virtual void unpack(const eoserial::Object* json) = 0; + }; + +} // namespace eoserial + +# endif // __EOSERIAL_SERIALIZABLE_H__ diff --git a/eo/src/serial/String.cpp b/eo/src/serial/String.cpp new file mode 100644 index 000000000..c50882786 --- /dev/null +++ b/eo/src/serial/String.cpp @@ -0,0 +1,32 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# include "String.h" + +namespace eoserial +{ + std::ostream& String::print( std::ostream& out ) const + { + out << '"' << *this << '"'; + return out; + } +} // namespace eoserial + diff --git a/eo/src/serial/String.h b/eo/src/serial/String.h new file mode 100644 index 000000000..526cab365 --- /dev/null +++ b/eo/src/serial/String.h @@ -0,0 +1,103 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_STRING_H__ +# define __EOSERIAL_STRING_H__ + +# include +# include +# include + +# include "Entity.h" + +namespace eoserial +{ + /** + * @brief JSON String + * + * Wrapper for string, so as to be used as a JSON object. + * + * @ingroup Serialization + */ + class String : public eoserial::Entity, public std::string + { + public: + + /** + * @brief Default ctor. + * @param str The string we want to wrap. + */ + String( const std::string& str ) : std::string( str ) {} + + /** + * @brief Ctor used only when parsing. + */ + String( ) {} + + /** + * @brief Prints out the string. + */ + virtual std::ostream& print( std::ostream& out ) const; + + /** + * @brief Deserializes the current String into a given primitive type value. + * @param value The value in which we're writing. + */ + template + inline void deserialize( T & value ); + + protected: + // Copy and reaffectation are forbidden + explicit String( const String& _ ); + String& operator=( const String& _ ); + }; + + /** + * @brief Casts a eoserial::String into a primitive value, or in a type which at + * least overload operator>>. + * + * @param value A reference to the variable we're writing into. + * + * It's not necessary to specify the variable type, which can be infered by compiler when + * invoking. + */ + template + inline void String::deserialize( T & value ) + { + std::stringstream ss; + ss.precision(std::numeric_limits::digits10 + 1); + ss << *this; + ss >> value; + } + + /** + * @brief Specialization for strings, which don't need to be converted through + * a stringstream. + */ + template<> + inline void String::deserialize( std::string & value ) + { + value = *this; + } + +} // namespace eoserial + +# endif // __EOSERIAL_STRING_H__ diff --git a/eo/src/serial/Utils.h b/eo/src/serial/Utils.h new file mode 100644 index 000000000..33172a747 --- /dev/null +++ b/eo/src/serial/Utils.h @@ -0,0 +1,189 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_UTILS_H__ +# define __EOSERIAL_UTILS_H__ + +# include "Array.h" +# include "Object.h" +# include "String.h" + +namespace eoserial +{ + /* *************************** + * DESERIALIZATION FUNCTIONS * + ***************************** + These functions are useful for casting eoserial::objects into simple, primitive + variables or into class instance which implement eoserial::Persistent. + + The model is always quite the same : + - the first argument is the containing object (which is a eoserial::Entity, + an object or an array) + - the second argument is the key or index, + - the last argument is the value in which we're writing. + */ + + template< class T > + inline void unpack( const Object & obj, const std::string & key, T & value ) + { + static_cast( obj.find( key )->second )->deserialize( value ); + } + + inline void unpackObject( const Object & obj, const std::string & key, Persistent & value ) + { + static_cast( obj.find( key )->second )->deserialize( value ); + } + + template< class Container, template class UnpackAlgorithm > + inline void unpackArray( const Object & obj, const std::string & key, Container & array ) + { + static_cast( obj.find( key )->second )->deserialize< Container, UnpackAlgorithm >( array ); + } + + template< class T > + inline void unpack( const Array & array, unsigned int index, T & value ) + { + static_cast( array[ index ] )->deserialize( value ); + } + + inline void unpackObject( const Array & array, unsigned int index, Persistent & value ) + { + static_cast( array[ index ] )->deserialize( value ); + } + + template< class Container, template class UnpackAlgorithm > + inline void unpackArray( const Array & array, unsigned int index, Container & container ) + { + static_cast( array[ index ] )->deserialize< Container, UnpackAlgorithm >( container ); + } + + /* ***************************** + *** SERIALIZATION FUNCTIONS *** + ******************************* + These functions are useful for casting classic objects and + eoserial::Persistent objects into eoserial entities which + can be manipulated by the framework. + */ + + /** + * @brief Casts a value of a stream-serializable type (i.e, which implements + * operator <<) into a JsonString. + * + * This is used when serializing the objects : all primitives types should be + * converted into strings to get more easily manipulated. + * + * @param value The value we're converting. + * @return JsonString wrapper for the value. + */ + template + String* make( const T & value ) + { + std::stringstream ss; + ss.precision(std::numeric_limits::digits10 + 1); + ss << value; + return new String( ss.str() ); + } + + /** + * @brief Specialization for strings : no need to convert as they're still + * usable as strings. + */ + template<> + inline String* make( const std::string & value ) + { + return new String( value ); + } + + /* + * These functions are useful for automatically serializing STL containers into + * eoserial arrays which could be used by the framework. + **/ + + /** + * @brief Functor which explains how to push the value into the eoserial::Array. + */ + template< class T > + struct PushAlgorithm + { + /** + * @brief Main operator. + * + * @param array The eoserial::array in which we're writing. + * @param value The variable we are writing. + */ + virtual void operator()( Array & array, const T & value ) = 0; + }; + + /** + * @brief Push algorithm for primitive variables. + * + * This one should be used when inserting primitive (and types which implement + * operator<<) variables. + */ + template< class T > + struct MakeAlgorithm : public PushAlgorithm + { + void operator()( Array & array, const T & value ) + { + array.push_back( make( value ) ); + } + }; + + /** + * @brief Push algorithm for eoserial::Persistent variables. + */ + template< class T > + struct SerializablePushAlgorithm : public PushAlgorithm + { + void operator()( Array & array, const T & obj ) + { + // obj address is not saved into array.push_back. + array.push_back( &obj ); + } + }; + + /** + * @brief Casts a STL container (vector or list, for instance) + * into a eoserial::Array. + * + * @þaram PushAlgorithm The algorithm used for inserting new element in the eoserial::Array. + * This algorithm is directly called, so it is its own charge to invoke push_back on the + * eoserial::Array. + */ + template< class Container, template class PushAlgorithm > + Array* makeArray( const Container & array ) + { + Array* returned_array = new Array; + typedef typename Container::const_iterator iterator; + typedef typename Container::value_type Type; + PushAlgorithm< Type > algo; + for ( + iterator it = array.begin(), end = array.end(); + it != end; + ++it) + { + algo( *returned_array, *it ); + } + return returned_array; + } +} // namespace eoserial + +# endif //__EOSERIAL_UTILS_H__ diff --git a/eo/src/serial/eoSerial.h b/eo/src/serial/eoSerial.h new file mode 100644 index 000000000..55a116f0c --- /dev/null +++ b/eo/src/serial/eoSerial.h @@ -0,0 +1,33 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EOSERIAL_HEADERS__ +# define __EOSERIAL_HEADERS__ + +# include "Object.h" +# include "Serializable.h" +# include "Array.h" +# include "Object.h" +# include "String.h" +# include "Parser.h" +# include "Utils.h" + +# endif // __EOSERIAL_HEADERS__ diff --git a/eo/src/serial/json_example b/eo/src/serial/json_example new file mode 100644 index 000000000..7ecb3edda --- /dev/null +++ b/eo/src/serial/json_example @@ -0,0 +1,8 @@ +{"a":"b", +"obj": + {"obj_a":"obj_}b","subobj_a": + {"subk":"subv"} + }, +"c":"d", +"array":["1","2",{"\"array\"_obj\"":"array_ov]"}, ["3"], "4"] +} diff --git a/eo/src/utils/CMakeLists.txt b/eo/src/utils/CMakeLists.txt index ab1a6c826..e64cf5e4c 100644 --- a/eo/src/utils/CMakeLists.txt +++ b/eo/src/utils/CMakeLists.txt @@ -2,17 +2,17 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Define the ga target ###################################################################################### -SET(EOUTILS_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) -SET(LIBRARY_OUTPUT_PATH ${EOUTILS_LIB_OUTPUT_PATH}) +set(EOUTILS_LIB_OUTPUT_PATH ${EO_BIN_DIR}/lib) +set(LIBRARY_OUTPUT_PATH ${EOUTILS_LIB_OUTPUT_PATH}) -SET(EOUTILS_SOURCES +set(EOUTILS_SOURCES eoData.cpp eoFileMonitor.cpp eoGnuplot.cpp @@ -32,15 +32,15 @@ SET(EOUTILS_SOURCES eoSignal.cpp ) -ADD_LIBRARY(eoutils STATIC ${EOUTILS_SOURCES}) -INSTALL(TARGETS eoutils ARCHIVE DESTINATION ${LIB} COMPONENT libraries) +add_library(eoutils STATIC ${EOUTILS_SOURCES}) +install(TARGETS eoutils ARCHIVE DESTINATION local/${LIB} COMPONENT libraries) ###################################################################################### ### 3) Optionnal ###################################################################################### -SET(EOUTILS_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(eoutils PROPERTIES VERSION "${EOUTILS_VERSION}") +set(EOUTILS_VERSION ${GLOBAL_VERSION}) +set_target_properties(eoutils PROPERTIES VERSION "${EOUTILS_VERSION}") ###################################################################################### diff --git a/eo/src/utils/eoLogger.h b/eo/src/utils/eoLogger.h index e5faf8f34..9ac1c2115 100644 --- a/eo/src/utils/eoLogger.h +++ b/eo/src/utils/eoLogger.h @@ -116,7 +116,7 @@ namespace eo */ struct file { - file(const std::string f); + explicit file(const std::string f); const std::string _f; }; @@ -126,8 +126,8 @@ namespace eo */ struct setlevel { - setlevel(const std::string v); - setlevel(const Levels lvl); + explicit setlevel(const std::string v); + explicit setlevel(const Levels lvl); const std::string _v; const Levels _lvl; }; diff --git a/eo/src/utils/eoOStreamMonitor.cpp b/eo/src/utils/eoOStreamMonitor.cpp index 3365301e9..6836f337e 100644 --- a/eo/src/utils/eoOStreamMonitor.cpp +++ b/eo/src/utils/eoOStreamMonitor.cpp @@ -37,6 +37,7 @@ eoMonitor& eoOStreamMonitor::operator()(void) } // if firstime // ok, now the real saving. write out + // FIXME deprecated, remove in next release //! @todo old verbose formatting, do we still need it? /* for (iterator it = vec.begin (); it != vec.end (); ++it) { diff --git a/eo/src/utils/eoOStreamMonitor.h b/eo/src/utils/eoOStreamMonitor.h index b941b05f2..982c954f9 100644 --- a/eo/src/utils/eoOStreamMonitor.h +++ b/eo/src/utils/eoOStreamMonitor.h @@ -44,14 +44,17 @@ Authors: class eoOStreamMonitor : public eoMonitor { public : - eoOStreamMonitor( std::ostream & _out, bool /*_verbose*/=true, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + /* FIXME remove in next release + eoOStreamMonitor( std::ostream & _out, bool _verbose=true, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) { #ifndef DEPRECATED_MESSAGES eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release" << std::endl; #pragma message "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release" #endif // !DEPRECATED_MESSAGES + } + */ eoOStreamMonitor( std::ostream & _out, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index d9d09c38b..cae5e8c41 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -21,22 +21,25 @@ Contact: http://eodev.sourceforge.net Authors: -Caner Candan + Caner Candan */ +#ifdef _OPENMP #include +#endif #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' ), + _isDynamic( true, "parallelize-dynamic", "Enable dynamic memory shared parallelization", '\0' ), _prefix( "results", "parallelize-prefix", "Here's the prefix filename where the results are going to be stored", '\0' ), _nthreads( 0, "parallelize-nthreads", "Define the number of threads you want to use, nthreads = 0 means you want to use all threads available", '\0' ), _enableResults( false, "parallelize-enable-results", "Enable the generation of results", '\0' ), _doMeasure( false, "parallelize-do-measure", "Do some measures during execution", '\0' ), + _packetSize( 1U, "parallelize-packet-size", "Number of elements which should be sent in a single message during a parallel evaluation based on message passing.", '\0'), _t_start(0) { } @@ -90,6 +93,7 @@ void eoParallel::_createParameters( eoParser& parser ) parser.processParam( _nthreads, section ); parser.processParam( _enableResults, section ); parser.processParam( _doMeasure, section ); + parser.processParam( _packetSize, section ); } void make_parallel(eoParser& parser) diff --git a/eo/src/utils/eoParallel.h b/eo/src/utils/eoParallel.h index 3f22f6c43..c7a15a4f9 100644 --- a/eo/src/utils/eoParallel.h +++ b/eo/src/utils/eoParallel.h @@ -20,8 +20,7 @@ Contact: http://eodev.sourceforge.net Authors: -Caner Candan - + Caner Candan */ /** @defgroup Parallel Parallel @@ -54,6 +53,7 @@ public: std::string prefix() const; inline unsigned int nthreads() const { return _nthreads.value(); } + inline unsigned int packetSize() const { return _packetSize.value(); } inline bool enableResults() const { return _enableResults.value(); } inline bool doMeasure() const { return _doMeasure.value(); } @@ -70,6 +70,7 @@ private: eoValueParam _nthreads; eoValueParam _enableResults; eoValueParam _doMeasure; + eoValueParam _packetSize; double _t_start; }; diff --git a/eo/src/utils/eoRNG.h b/eo/src/utils/eoRNG.h index 984e76271..78223c35a 100644 --- a/eo/src/utils/eoRNG.h +++ b/eo/src/utils/eoRNG.h @@ -150,7 +150,8 @@ public : initialize(2*s); } - /** Re-initializes the Random Number Generator + /* FIXME remove in next release + ** Re-initializes the Random Number Generator This is the traditional seeding procedure. This version is deprecated and only provided for compatibility with old code. In new projects you should @@ -159,11 +160,12 @@ public : @see reseed for details on usage of the seeding value. @version old version (deprecated) - */ + * void oldReseed(uint32_t s) { initialize(s); } + */ /** Random number from unifom distribution diff --git a/eo/src/utils/eoStat.h b/eo/src/utils/eoStat.h index 32c3bf9f6..fd26ec228 100644 --- a/eo/src/utils/eoStat.h +++ b/eo/src/utils/eoStat.h @@ -32,6 +32,7 @@ Contact: http://eodev.sourceforge.net #ifndef _eoStat_h #define _eoStat_h +#include #include // accumulate #include @@ -176,18 +177,27 @@ private : }; /** - Average fitness + Std. dev. of a population, fitness needs to be scalar. + Average fitness + Std. dev. of a population, fitness HAVE TO BE to be scalar. */ template -class eoSecondMomentStats : public eoStat > +// FIXME find a way to use generic Fitness types instead of scala fitness here : +// class eoSecondMomentStats : public eoStat > + // Here, I failed to find a way to overload eoValueParam::getValue and setValue, + // because there is no way to use the partial specializations located in eoParam.h + // Indeed, eoValueParam is templatized on a ValueType, but the getValue signature does not + // contain this type. + // Thus, in order to use partial specializations the user would have to specify getValue(), + // which is not the case in most of the existing code. + // Overloading getValue in this class does not seems to work, the call falls to eoValueParam::getValue + // and fails on the output stream. +class eoSecondMomentStats : public eoStat > { public : + // typedef typename EOT::Fitness FitT; + typedef double FitT; - using eoStat >::value; - - typedef typename EOT::Fitness fitness_type; - - typedef std::pair SquarePair; + using eoStat >::value; + typedef std::pair SquarePair; eoSecondMomentStats(std::string _description = "Average & Stdev") : eoStat(std::make_pair(0.0,0.0), _description) @@ -195,7 +205,7 @@ public : static SquarePair sumOfSquares(SquarePair _sq, const EOT& _eo) { - double fitness = _eo.fitness(); + FitT fitness = _eo.fitness(); _sq.first += fitness; _sq.second += fitness * fitness; @@ -211,9 +221,11 @@ public : value().second = sqrt( (result.second - n * value().first * value().first) / (n - 1.0)); // stdev } - virtual std::string className(void) const { return "eoSecondMomentStats"; } + virtual std::string className(void) const { return "eoSecondMomentStats"; } + }; + /** The n_th element fitness in the population (see eoBestFitnessStat) */ @@ -244,6 +256,7 @@ public : virtual std::string className(void) const { return "eoNthElementFitnessStat"; } private : + /* Very old code... struct CmpFitness { CmpFitness(unsigned _whichElement, bool _maxim) : whichElement(_whichElement), maxim(_maxim) {} @@ -259,6 +272,7 @@ private : unsigned whichElement; bool maxim; }; + */ // for everything else template @@ -329,6 +343,7 @@ public: private : + /* Very old code... struct CmpFitness { CmpFitness(unsigned _which, bool _maxim) : which(_which), maxim(_maxim) {} @@ -344,6 +359,7 @@ private : unsigned which; bool maxim; }; + */ // default template @@ -356,6 +372,39 @@ private : /** @example t-eoSSGA.cpp */ + +/** Keep the best individual found so far + */ +template +class eoBestIndividualStat : public eoStat +{ +public: + using eoStat::value; + + eoBestIndividualStat(std::string _description = "BestIndiv ") + : eoStat( EOT(), _description ) + {} + + void operator()(const eoPop& pop) + { + EOT best = pop.best_element(); + // on the first call, value() is invalid + if( value().invalid() ) { + // thus we cannot compare it to something else + value() = best; + } else { + // keep the best individual found so far + if( best.fitness() > value().fitness() ) { + value() = best; + } + } + } + + virtual std::string className(void) const { return "eoBestIndividualStat"; } +}; + + + template class eoDistanceStat : public eoStat { diff --git a/eo/src/utils/eoState.cpp b/eo/src/utils/eoState.cpp index d9d06d99e..c6d385001 100644 --- a/eo/src/utils/eoState.cpp +++ b/eo/src/utils/eoState.cpp @@ -18,7 +18,7 @@ using namespace std; -void removeComment(string& str, string comment) +void eoState::removeComment(string& str, string comment) { string::size_type pos = str.find(comment); @@ -28,21 +28,23 @@ void removeComment(string& str, string comment) } } -bool is_section(const string& str, string& name) +bool eoState::is_section(const string& str, string& name) { - string::size_type pos = str.find("\\section{"); + string::size_type pos = str.find(_tag_section_so); if (pos == string::npos) return false; //else - string::size_type end = str.find("}"); + string::size_type end = str.find(_tag_section_sc); if (end == string::npos) return false; // else - name = str.substr(pos + 9, end-9); + // affect name, passed by reference + // Note: substr( start, count ) + name = str.substr( pos + _tag_section_so.size(), end - _tag_section_so.size() ); return true; } @@ -84,6 +86,7 @@ void eoState::load(const string& _filename) load(is); } +// FIXME implement parsing and loading of other formats void eoState::load(std::istream& is) { string str; @@ -158,16 +161,49 @@ void eoState::save(const string& filename) const save(os); } -void eoState::save(std::ostream& os) const -{ // saves in order of insertion - for (vector::const_iterator it = creationOrder.begin(); it != creationOrder.end(); ++it) - { - os << "\\section{" << (*it)->first << "}\n"; - (*it)->second->printOn(os); - os << '\n'; - } +//void eoState::save(std::ostream& os) const +//{ // saves in order of insertion +// for (vector::const_iterator it = creationOrder.begin(); it != creationOrder.end(); ++it) +// { +// os << "\\section{" << (*it)->first << "}\n"; +// (*it)->second->printOn(os); +// os << '\n'; +// } +//} + +void eoState::saveSection( std::ostream& os, vector::const_iterator it) const +{ + os << _tag_section_so << (*it)->first << _tag_section_sc; + + os << _tag_content_s; + (*it)->second->printOn(os); + os << _tag_content_e; + + os << _tag_section_e; } + +void eoState::save(std::ostream& os) const +{ + os << _tag_state_so << _tag_state_name << _tag_state_sc; + + // save the first section + assert( creationOrder.size() > 0 ); + // saves in order of insertion + vector::const_iterator it = creationOrder.begin(); + saveSection(os,it); + it++; + + while( it != creationOrder.end() ) { + // add a separator only before [1,n] elements + os << _tag_section_sep; + saveSection(os, it); + it++; + } + os << _tag_state_e; +} + + string eoState::createObjectName(eoObject* obj) { if (obj == 0) diff --git a/eo/src/utils/eoState.h b/eo/src/utils/eoState.h index 53c3a83d5..256dcd965 100644 --- a/eo/src/utils/eoState.h +++ b/eo/src/utils/eoState.h @@ -31,6 +31,7 @@ #include #include #include +#include #include @@ -56,10 +57,50 @@ class eoState : public eoFunctorStore { public : - eoState(void) {} + eoState(std::string name="") : + _tag_state_so(""), + _tag_state_name(name), + _tag_state_sc(""), + _tag_section_so("\\section{"), + _tag_section_sc("}\n"), + _tag_content_s(""), + _tag_content_e(""), + _tag_section_sep(""), + _tag_section_e("\n"), + _tag_state_e("") + {} ~eoState(void); + void formatLatex(std::string name) + { + _tag_state_so = ""; + _tag_state_name = name; + _tag_state_sc = ""; + _tag_section_so = "\\section{"; + _tag_section_sc = "}\n"; + _tag_content_s = ""; + _tag_content_e = ""; + _tag_section_sep = ""; + _tag_section_e = "\n"; + _tag_state_e = ""; + } + + void formatJSON(std::string name) + { + _tag_state_so = "{ \""; + _tag_state_name = name; + _tag_state_sc = "\":\n"; + _tag_section_so = "\t{ \""; + _tag_section_sc = "\":\n"; + _tag_content_s = "\""; + _tag_content_e = "\""; + _tag_section_sep = ",\n"; + _tag_section_e = "\t}\n"; + _tag_state_e = "}\n"; + } + + /** * Object registration function, note that it does not take ownership! */ @@ -131,6 +172,43 @@ private : eoState(const eoState&); eoState& operator=(const eoState&); + /* \@{ + * s=start, e=end + * o=open, c=close + * + * { "my_state": + * { + * "section_pop":"…", + * "section_rng":"…" + * } + * } + * + * // JSON LATEX (default) + */ + std::string _tag_state_so; // { " + std::string _tag_state_name; // my_state + std::string _tag_state_sc; // ": + + std::string _tag_section_so; // { " \\section{ + std::string _tag_section_sc; // ": }\n + + std::string _tag_content_s; // " + std::string _tag_content_e; // " + + std::string _tag_section_sep;// , + + std::string _tag_section_e; // } \n + + std::string _tag_state_e; // } + /** \@} */ + + void removeComment( std::string& str, std::string comment); + + bool is_section(const std::string& str, std::string& name); + +protected: + void saveSection( std::ostream& os, std::vector::const_iterator it) const; + }; /** @example t-eoStateAndParser.cpp */ diff --git a/eo/src/utils/eoStdoutMonitor.h b/eo/src/utils/eoStdoutMonitor.h index 07c5a02f6..d886aed3a 100644 --- a/eo/src/utils/eoStdoutMonitor.h +++ b/eo/src/utils/eoStdoutMonitor.h @@ -43,6 +43,7 @@ Authors: class eoStdoutMonitor : public eoOStreamMonitor { public : + /* FIXME remove in next release eoStdoutMonitor(bool _verbose, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : eoOStreamMonitor( std::cout, _verbose, _delim, _width, _fill) { @@ -50,6 +51,7 @@ public : eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoStdoutMonitor constructor is deprecated and will be removed in the next release" << std::endl; #endif // !DEPRECATED_MESSAGES } + */ eoStdoutMonitor(std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : eoOStreamMonitor( std::cout, _delim, _width, _fill) diff --git a/eo/src/utils/eoTimer.h b/eo/src/utils/eoTimer.h new file mode 100644 index 000000000..4ff451b48 --- /dev/null +++ b/eo/src/utils/eoTimer.h @@ -0,0 +1,329 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ +# ifndef __EO_TIMER_H__ +# define __EO_TIMER_H__ + +# include // time() +# include // rusage() + +# include // std::vector +# include // std::map + +# include "utils/eoParallel.h" // eo::parallel + +# include "serial/eoSerial.h" // eo::Persistent + +/** + * @brief Timer allowing to measure time between a start point and a stop point. + * + * This timer allows the user to measure user time, system time and wallclock time + * between two points. Basically, user time is time spent in developer code ; system + * time is time spent during the IO wait and system calls ; wallclock is the difference + * of time we could observe by measuring time with a watch. + * + * @ingroup Utilities + */ +class eoTimer +{ + public: + + /** + * @brief Default ctor. Begins all the timers. + */ + eoTimer() + { + uuremainder = 0; + usremainder = 0; + restart(); + } + + /** + * @brief Restarts all the timers and launch the measure. + */ + void restart() + { + wc_start = time(NULL); + getrusage( RUSAGE_SELF, &_start ); + } + + /** + * @brief Measures the user time spent since the last restart(). + * + * If the number of elapsed seconds is zero, the spent milliseconds are + * added to a remainder. If the remainder exceeds one second, it is + * added to the number of elapsed seconds. + * + * @return Number of seconds elapsed in user space. + */ + long int usertime() + { + struct rusage _now; + getrusage( RUSAGE_SELF, &_now ); + + long int result = _now.ru_utime.tv_sec - _start.ru_utime.tv_sec; + long int remainder = _now.ru_utime.tv_usec - _start.ru_utime.tv_usec; + if( remainder >= 0 ) + { + uuremainder += remainder; + } else + { + uuremainder += ( 1000000 - remainder ); + --result; + } + + if( uuremainder >= 1000000 ) + { + uuremainder -= 1000000; + ++result; + } + return result; + } + + /** + * @brief Measures the system time spent since the last restart(). + * + * If the number of elapsed seconds is zero, the spent milliseconds are + * added to a remainder. If the remainder exceeds one second, it is + * added to the number of elapsed seconds. + * + * @return Number of seconds elapsed in system (kernel) space. + */ + long int systime() + { + struct rusage _now; + getrusage( RUSAGE_SELF, &_now ); + + long int result = _now.ru_stime.tv_sec - _start.ru_stime.tv_sec; + long int remainder = _now.ru_stime.tv_usec - _start.ru_stime.tv_usec; + if( remainder >= 0 ) + { + usremainder += remainder; + } else + { + usremainder += ( 1000000 - remainder ); + --result; + } + + if( usremainder >= 1000000 ) + { + usremainder -= 1000000; + ++result; + } + return result; + } + + /** + * @brief Measures the wallclock time spent since the last restart(). + * + * @return Number of seconds elapsed, as a double. + */ + double wallclock() + { + return std::difftime( std::time(NULL) , wc_start ); + } + + protected: + // Structure used to measure user and system time. + struct rusage _start; + // Remainder (in milliseconds) for user time. + long int uuremainder; + // Remainder (in milliseconds) for system time. + long int usremainder; + // Structure used to measure wallclock time. + time_t wc_start; +}; + +/** + * @brief Registers a group of statistics, each statistic corresponding to user, system and wallclock times distribution. + * + * This class helps the user to measure time in different parts of an application. A name is associated to a statistic, + * on each call to start() and stop() for this name, a new number is added to the statistic, for each of the three + * measured times. + * + * The statistics are only registered if the option "--parallelized-do-measure" is set to true, which can be checked + * thanks to global object eo::parallel. + * + * This shows how the eoTimerStat can be used : + * @code + * eoTimerStat timerStat; + * timerStat.start("first_point"); + * for( int i = 0; i < 1000; ++i ) + * { + * timerStat.start("single_computation"); + * single_computation( i ); + * timerStat.stop("single_computation"); + * } + * // After this loop, timerStat contains a statistic of key "single_computation" which contains 1000 measures for + * // each type of time. + * timerStat.stop("first_point"); + * // After this line, timerStat contains another statistic of key "first_point" which counted the duration of the + * // whole loop. + * + * int singleComputationUsertimeMean = 0; + * for( int i = 0; i < 1000; ++i ) + * { + * singleComputationUsertimeMean += timerStat.stats()["single_computation"].utime[i]; + * } + * std::cout << "Mean of user time spent in single computation: " << singleComputationUsertimeMean / 1000. << std::endl; + * @endcode + * + * When using MPI, these statistics can be readily be serialized, so as to be sent over a network, for instance. + * + * Implementation details: this eoTimerStat is in fact a map of strings (key) / Stat (value). Stat is an internal + * structure directly defined in the class, which contains three vectors modeling the distributions of the different + * types of elapsed times. Another map of strings (key) / eoTimer (value) allows to effectively retrieve the different + * times. The struct Stat will be exposed to client, which will use its members ; however, + * the client doesn't have anything to do directly with the timer, that's why the two maps are splitted. + * + * @ingroup Utilities + */ +class eoTimerStat +# ifdef WITH_MPI + : public eoserial::Persistent +# endif +{ + public: + + /** + * @brief Statistic related to a key (name). + * + * This structure is the value in the map saved in the eoTimerStat. It contains the statistic bound to a key, + * which are the user time distribution, the system time distribution and the wallclock time distribution, as + * std::vector s. + * + * It can readily be serialized with boost when compiling with mpi. + */ + struct Stat +# ifdef WITH_MPI + : public eoserial::Persistent +# endif + { + std::vector utime; + std::vector stime; + std::vector wtime; +#ifdef WITH_MPI + void unpack( const eoserial::Object* obj ) + { + utime.clear(); + static_cast< eoserial::Array* >(obj->find("utime")->second) + ->deserialize< std::vector, eoserial::Array::UnpackAlgorithm >( utime ); + + stime.clear(); + static_cast< eoserial::Array* >(obj->find("stime")->second) + ->deserialize< std::vector, eoserial::Array::UnpackAlgorithm >( stime ); + + wtime.clear(); + static_cast< eoserial::Array* >(obj->find("wtime")->second) + ->deserialize< std::vector, eoserial::Array::UnpackAlgorithm >( wtime ); + } + + eoserial::Object* pack( void ) const + { + eoserial::Object* obj = new eoserial::Object; + obj->add("utime", eoserial::makeArray< std::vector, eoserial::MakeAlgorithm >( utime ) ); + obj->add("stime", eoserial::makeArray< std::vector, eoserial::MakeAlgorithm >( stime ) ); + obj->add("wtime", eoserial::makeArray< std::vector, eoserial::MakeAlgorithm >( wtime ) ); + return obj; + } +# endif + }; + +#ifdef WITH_MPI + void unpack( const eoserial::Object* obj ) + { + _stats.clear(); + for( eoserial::Object::const_iterator it = obj->begin(), final = obj->end(); + it != final; + ++it) + { + eoserial::unpackObject( *obj, it->first, _stats[ it->first ] ); + } + } + + eoserial::Object* pack( void ) const + { + eoserial::Object* obj = new eoserial::Object; + for( std::map::const_iterator it = _stats.begin(), final = _stats.end(); + it != final; + ++it) + { + obj->add( it->first, it->second.pack() ); + } + return obj; + } +# endif + + /** + * @brief Starts a new measure for the given key. + * + * This is only performed if parallel.doMeasure() is true, which is equivalent to the fact that + * parser found "--parallel-do-measure=1" in command line args. + * + * @param key The key of the statistic. + */ + void start( const std::string & key ) + { + if( eo::parallel.doMeasure() ) + { + _timers[ key ].restart(); + } + } + + /** + * @brief Stops the mesure for the given key and saves the elapsed times. + * + * Must follow a call of start with the same key. + * + * This is only performed if parallel.doMeasure() is true, which is equivalent to the fact that + * parser found "--parallel-do-measure=1" in command line args. + * + * @param key The key of the statistic. + */ + void stop( const std::string& key ) + { + if( eo::parallel.doMeasure() ) + { + Stat & s = _stats[ key ]; + eoTimer & t = _timers[ key ]; + s.utime.push_back( t.usertime() ); + s.stime.push_back( t.systime() ); + s.wtime.push_back( t.wallclock() ); + } + } + + /** + * @brief Getter for the statistics map. + */ + std::map< std::string, Stat >& stats() + { + return _stats; + } + + protected: + // Statistics map: links a key (string) to a statistic. + std::map< std::string, Stat > _stats; + // Timers map: links a key to its timer. + std::map< std::string, eoTimer > _timers; +}; + +# endif // __TIMER_H__ + diff --git a/eo/test/CMakeLists.txt b/eo/test/CMakeLists.txt index 860968ffb..6f05ecde9 100644 --- a/eo/test/CMakeLists.txt +++ b/eo/test/CMakeLists.txt @@ -9,22 +9,22 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/contrib) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/contrib/MGE) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EO_SRC_DIR}/contrib) +include_directories(${EO_SRC_DIR}/contrib/MGE) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) +link_directories(${EO_BIN_DIR}/lib) ###################################################################################### ### 3) Define your targets and link the librairies ###################################################################################### -SET (TEST_LIST +set (TEST_LIST t-eofitness t-eoRandom t-eobin @@ -72,45 +72,45 @@ SET (TEST_LIST ) -FOREACH (test ${TEST_LIST}) - SET ("T_${test}_SOURCES" "${test}.cpp") -ENDFOREACH (test) +foreach (test ${TEST_LIST}) + set ("T_${test}_SOURCES" "${test}.cpp") +endforeach (test) -IF(ENABLE_MINIMAL_CMAKE_TESTING) +if(ENABLE_MINIMAL_CMAKE_TESTING) - SET (MIN_TEST_LIST t-eoEasyPSO) - FOREACH (mintest ${MIN_TEST_LIST}) - SET ("T_${mintest}_SOURCES" "${mintest}.cpp") - ADD_EXECUTABLE(${mintest} ${T_${mintest}_SOURCES}) - ADD_TEST(${mintest} ${mintest}) - TARGET_LINK_LIBRARIES(${mintest} ga es cma eoutils eo) - ENDFOREACH (mintest) + set (MIN_TEST_LIST t-eoEasyPSO) + foreach (mintest ${MIN_TEST_LIST}) + set ("T_${mintest}_SOURCES" "${mintest}.cpp") + add_executable(${mintest} ${T_${mintest}_SOURCES}) + add_test(${mintest} ${mintest}) + target_link_libraries(${mintest} ga es cma eoutils eo) + endforeach (mintest) -ELSEIF(ENABLE_CMAKE_TESTING) +elseif(ENABLE_CMAKE_TESTING) - FOREACH (test ${TEST_LIST}) - ADD_EXECUTABLE(${test} ${T_${test}_SOURCES}) - ADD_TEST(${test} ${test}) - TARGET_LINK_LIBRARIES(${test} ga es cma eoutils eo) - INSTALL(TARGETS ${test} RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/test COMPONENT test) - ENDFOREACH (test) + foreach (test ${TEST_LIST}) + add_executable(${test} ${T_${test}_SOURCES}) + add_test(${test} ${test}) + target_link_libraries(${test} ga es cma eoutils eo) + install(TARGETS ${test} RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/test COMPONENT test) + endforeach (test) - SET(RESOURCES + set(RESOURCES boxplot.py boxplot_to_png.py boxplot_to_pdf.py t-openmp.py ) - FOREACH(file ${RESOURCES}) - EXECUTE_PROCESS( + foreach(file ${RESOURCES}) + execute_process( COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/${file} ${CMAKE_CURRENT_BINARY_DIR}/${file} ) - ENDFOREACH(file) + endforeach(file) -ENDIF(ENABLE_MINIMAL_CMAKE_TESTING) +endif(ENABLE_MINIMAL_CMAKE_TESTING) ###################################################################################### diff --git a/eo/test/mpi/CMakeLists.txt b/eo/test/mpi/CMakeLists.txt new file mode 100644 index 000000000..325056da7 --- /dev/null +++ b/eo/test/mpi/CMakeLists.txt @@ -0,0 +1,54 @@ +############################################################################### +## +## CMakeLists file for eo/test/mpi +## +############################################################################### + +###################################################################################### +### 1) Include the sources +###################################################################################### + +message("EO SOURCE DIR: ${EO_SRC_DIR}") +message("OMPI: ${MPI_DIR}") + +include_directories(${MPI_DIR}/include) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +###################################################################################### +### 2) Specify where CMake can find the libraries +###################################################################################### + +link_directories(${EO_BIN_DIR}/lib) +link_directories(${MPI_DIR}/lib) + +###################################################################################### +### 3) Define your targets and link the librairies +###################################################################################### + +set (TEST_LIST + t-mpi-parallelApply + t-mpi-wrapper + t-mpi-multipleRoles + t-mpi-eval + t-mpi-multistart + t-mpi-distrib-exp + ) + +foreach (test ${TEST_LIST}) + set ("T_${test}_SOURCES" "${test}.cpp") +endforeach (test) + +set(CMAKE_CXX_COMPILER "mpicxx") +add_definitions(-DWITH_MPI) + +if(ENABLE_CMAKE_TESTING) + foreach (test ${TEST_LIST}) + add_executable(${test} ${T_${test}_SOURCES}) + add_test(${test} ${test}) + target_link_libraries(${test} eoutils eompi eoserial eo) + install(TARGETS ${test} RUNTIME DESTINATION share/eo/test COMPONENT test) + endforeach (test) +endif() + +###################################################################################### diff --git a/eo/test/mpi/t-mpi-common.h b/eo/test/mpi/t-mpi-common.h new file mode 100644 index 000000000..c862a05c1 --- /dev/null +++ b/eo/test/mpi/t-mpi-common.h @@ -0,0 +1,51 @@ +# ifndef __T_MPI_COMMON_H__ +# define __T_MPI_COMMON_H__ + +#include + +/** + * @file t-mpi-common.h + * + * This file shows an example of serialization of a primitive type, so as to be used in a parallel algorithm. + * It is fully compatible with the basic type, by implementing conversion operator and constructor based on type. + * It can contain any simple type which can be written in a std::ostream. + */ + +template< class T > +struct SerializableBase : public eoserial::Persistent +{ + public: + + operator T&() + { + return _value; + } + + SerializableBase() : _value() + { + // empty + } + + SerializableBase( T base ) : _value( base ) + { + // empty + } + + void unpack( const eoserial::Object* obj ) + { + eoserial::unpack( *obj, "value", _value ); + } + + eoserial::Object* pack(void) const + { + eoserial::Object* obj = new eoserial::Object; + obj->add("value", eoserial::make( _value ) ); + return obj; + } + + private: + T _value; +}; + + +# endif // __T_MPI_COMMON_H__ diff --git a/eo/test/mpi/t-mpi-distrib-exp.cpp b/eo/test/mpi/t-mpi-distrib-exp.cpp new file mode 100644 index 000000000..4fad9d44c --- /dev/null +++ b/eo/test/mpi/t-mpi-distrib-exp.cpp @@ -0,0 +1,135 @@ +# include // usleep + +# include +# include +# include + +# include + +# include +# include "../test/mpi/t-mpi-common.h" + +using namespace eo::mpi; + +typedef SerializableBase type; + +struct Wait : public eoUF< type &, void > +{ + void operator()( type & milliseconds ) + { + std::cout << "Sleeping for " << milliseconds << "ms..." << std::endl; + // usleep takes an input in microseconds + usleep( milliseconds * 1000 ); + } +} wait; + +class Distribution : public std::vector< type > +{ + public: + + /** + * @brief Really fills the vector with the distribution values. + */ + void fill( unsigned size ) + { + for( unsigned i = 0; i < size; ++i ) + { + push_back( next_element() ); + } + } + + /** + * @brief Returns the next element of the distribution to put in the + * vector. + * + * @returns Number of milliseconds to wait + */ + virtual int next_element() = 0; + + // Idea for function name: enlarge_your_parser + /** + * @brief Creates params and retrieves values from parser + */ + virtual void make_parser( eoParser & parser ) = 0; + + /** + * @brief Returns true if this distribution has been activated by the + * command line. + * + * Serves to main program to check if at least one distribution has been + * activated. + */ + bool isActive() { return _active; } + + protected: + + bool _active; +}; + +class UniformDistribution : public Distribution +{ + public: + + UniformDistribution() : _rng(0) + { + // empty + } + + void make_parser( eoParser & parser ) + { + _active = parser.createParam( false, "uniform", "Uniform distribution", '\0', "Uniform").value(); + _min = parser.createParam( 0.0, "uniform-min", "Minimum for uniform distribution", '\0', "Uniform").value(); + _max = parser.createParam( 1.0, "uniform-max", "Maximum for uniform distribution", '\0', "Uniform").value(); + } + + int next_element() + { + return std::floor( 1000. * _rng.uniform( _min, _max ) ); + } + + protected: + + eoRng _rng; + + double _min; + double _max; + +} uniformDistribution; + +int main( int argc, char** argv ) +{ + Node::init( argc, argv ); + eoParser parser( argc, argv ); + + // TODO for each available distribution, check if activated. + // If no distribution is activated, show an error message + // If two distributions or more are activated, show an error message + // Otherwise, use the activated distribution as distrib + Distribution & distrib = uniformDistribution; + // Make parser of distribution here + distrib.make_parser( parser ); + + unsigned size = parser.createParam( 10U, "size", "Number of elements to distribute.", 's', "Distribution").value(); + unsigned packet_size = parser.createParam( 1U, "packet_size", "Number of elements to distribute at each time for a single worker.", 'p', "Parallelization").value(); + + make_parallel( parser ); + make_help( parser ); + + ParallelApplyStore< type> store( wait, DEFAULT_MASTER, packet_size ); + + // Fill distribution + distrib.fill( size ); + store.data( distrib ); + + DynamicAssignmentAlgorithm scheduling; + ParallelApply< type > job( scheduling, DEFAULT_MASTER, store ); + + job.run(); + + if( job.isMaster() ) + { + EmptyJob( scheduling, DEFAULT_MASTER ); // to terminate parallel apply + } + + return 0; +} diff --git a/eo/test/mpi/t-mpi-eval.cpp b/eo/test/mpi/t-mpi-eval.cpp new file mode 100644 index 000000000..fb97701d2 --- /dev/null +++ b/eo/test/mpi/t-mpi-eval.cpp @@ -0,0 +1,206 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ + +/* + * This file shows an example of parallel evaluation of a population, when using an eoEasyEA algorithm. + * Moreover, we add a basic wrapper on the parallel evaluation, so as to show how to retrieve the best solutions. + */ +//----------------------------------------------------------------------------- + +#include +#include + +#include +#include "../real_value.h" + +#include + +#include +using namespace std; + +//----------------------------------------------------------------------------- + +class eoRealSerializable : public eoReal< eoMinimizingFitness >, public eoserial::Persistent +{ + public: + + eoRealSerializable(unsigned size = 0, double value = 0.0): + eoReal(size, value) {} + + eoserial::Object* pack() const + { + eoserial::Object* obj = new eoserial::Object; + obj->add( "array", + eoserial::makeArray< vector, eoserial::MakeAlgorithm > + ( *this ) + ); + + bool invalidFitness = invalid(); + obj->add("invalid", eoserial::make( invalidFitness ) ); + if( !invalidFitness ) + { + double fitnessVal = fitness(); + obj->add("fitness", eoserial::make( fitnessVal ) ); + } + return obj; + } + + void unpack( const eoserial::Object* obj ) + { + this->clear(); + eoserial::unpackArray< vector, eoserial::Array::UnpackAlgorithm > + ( *obj, "array", *this ); + + bool invalidFitness; + eoserial::unpack( *obj, "invalid", invalidFitness ); + if( invalidFitness ) { + invalidate(); + } else { + double fitnessVal; + eoserial::unpack( *obj, "fitness", fitnessVal ); + fitness( fitnessVal ); + } + } +}; + +typedef eoRealSerializable EOT; + +/* + * Wrapper for HandleResponse: shows the best answer, as it is found. + * + * Finding the best solution is an associative operation (as it is based on a "min" function, which is associative too) + * and that's why we can perform it here. Indeed, the min element of 5 elements is the min element of the 3 first + * elements and the min element of the 2 last elements: + * min(1, 2, 3, 4, 5) = min( min(1, 2, 3), min(4, 5) ) + * + * This is a reduction. See MapReduce example to have another examples of reduction. + */ +struct CatBestAnswers : public eo::mpi::HandleResponseParallelApply +{ + CatBestAnswers() + { + best.fitness( 1000000000. ); + } + + /* + our structure inherits the member _wrapped from HandleResponseFunction, + which is a HandleResponseFunction pointer; + + it inherits also the member _d (like Data), which is a pointer to the + ParallelApplyData used in the HandleResponseParallelApply<EOT>. Details + of this data are contained in the file eoParallelApply. We need just to know that + it contains a member assignedTasks which maps a worker rank and the sent slice + to be processed by the worker, and a reference to the processed table via the + call of the data() function. + */ + + // if EOT were a template, we would have to do: (thank you C++ :) + // using eo::mpi::HandleResponseParallelApply::_wrapped; + // using eo::mpi::HandleResponseParallelApply::d; + + void operator()(int wrkRank) + { + eo::mpi::ParallelApplyData * d = _data; + // Retrieve informations about the slice processed by the worker + int index = d->assignedTasks[wrkRank].index; + int size = d->assignedTasks[wrkRank].size; + // call to the wrapped function HERE + (*_wrapped)( wrkRank ); + // Compare fitnesses of evaluated individuals with the best saved + for(int i = index; i < index+size; ++i) + { + if( best.fitness() < d->table()[ i ].fitness() ) + { + eo::log << eo::quiet << "Better solution found:" << d->table()[i].fitness() << std::endl; + best = d->table()[ i ]; + } + } + } + + protected: + + EOT best; +}; + +int main(int ac, char** av) +{ + eo::mpi::Node::init( ac, av ); + // eo::log << eo::setlevel( eo::debug ); + eo::log << eo::setlevel( eo::quiet ); + + 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 ); + + // until this point, everything (but eo::mpi::Node::init) is exactly as in an sequential version. + // We then instanciate the parallel algorithm. The store is directly used by the eoParallelPopLoopEval, which + // internally uses parallel apply. + int rank = eo::mpi::Node::comm().rank(); + eo::mpi::DynamicAssignmentAlgorithm assign; + if( rank == eo::mpi::DEFAULT_MASTER ) + { + eoPop< EOT > pop( popSize, init ); + + eo::log << "Size of population : " << popSize << std::endl; + + eo::mpi::ParallelApplyStore< EOT > store( eval, eo::mpi::DEFAULT_MASTER ); + store.wrapHandleResponse( new CatBestAnswers ); + + eoParallelPopLoopEval< EOT > popEval( assign, eo::mpi::DEFAULT_MASTER, &store ); + + //eoParallelPopLoopEval< EOT > popEval( assign, eo::mpi::DEFAULT_MASTER, eval, 5 ); + + eo::log << eo::quiet << "Before first evaluation." << std::endl; + popEval( pop, pop ); + eo::log << eo::quiet << "After first evaluation." << std::endl; + + pop = eoPop< EOT >( popSize, init ); + popEval( pop, pop ); + eo::log << eo::quiet << "After second evaluation." << std::endl; + + eo::log << eo::quiet << "DONE!" << std::endl; + } else + { + eoPop< EOT > pop; // the population doesn't have to be initialized, as it is not used by workers. + eoParallelPopLoopEval< EOT > popEval( assign, eo::mpi::DEFAULT_MASTER, eval ); + popEval( pop, pop ); + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/mpi/t-mpi-multipleRoles.cpp b/eo/test/mpi/t-mpi-multipleRoles.cpp new file mode 100644 index 000000000..3a525126b --- /dev/null +++ b/eo/test/mpi/t-mpi-multipleRoles.cpp @@ -0,0 +1,196 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ + +/* + * This file shows an example of how to make a hierarchy between nodes, when using a parallel apply. In this basic + * test, the master delegates the charge of finding workers to 2 "sub" masters, which then send part of the table to + * their workers. + * + * It's convenient to establish a role map, so as to clearly identify every role: + * - The node 0 is the general master, that delegates the job. It sends the table to the 2 submasters, and waits for the + * results. + * - Nodes 1 and 2 are the worker of the first job: the delegates. They receive the elements of the table and + * retransmit them to the subworkers. They play the roles of worker in the delegating job, and master in the plus one + * job. + * - Following nodes (3 to 6) are workers of the plus one job. They do the real job. Nodes 3 and 5 are attached to + * submaster 1, 4 and 6 to submaster 2. + * + * This test requires exactly 7 hosts. If the size is bigger, an exception will be thrown at the beginning. + **/ + +# include +# include +# include + +# include "t-mpi-common.h" + +# include + +# include +using namespace std; + +using namespace eo::mpi; + +/* + * This class allows the user to easily serialize a vector of elements which implement eoserial::Persistent too. + * + * T is the type of the contained element, which must implement eoserial::Persistent too. + * + * Here, it contains SerializableBase, which is a serializable integer that can be used as an integer. + */ +template< class T > +struct SerializableVector : public std::vector, public eoserial::Persistent +{ + public: + + void unpack( const eoserial::Object* obj ) + { + this->clear(); + eoserial::Array* vector = static_cast( obj->find("vector")->second ); + vector->deserialize< std::vector, eoserial::Array::UnpackObjectAlgorithm >( *this ); + } + + eoserial::Object* pack( void ) const + { + eoserial::Object* obj = new eoserial::Object; + obj->add("vector", eoserial::makeArray< std::vector, eoserial::SerializablePushAlgorithm >( *this ) ); + return obj; + } +}; + +// The real job to execute, for the subworkers: add one to each element of a table. +struct SubWork: public eoUF< SerializableBase&, void > +{ + void operator() ( SerializableBase & x ) + { + cout << "Subwork phase." << endl; + ++x; + } +}; + +// Function called by both subworkers and delegates. +// v is the vector to process, rank is the MPI rank of the sub master +void subtask( vector< SerializableBase >& v, int rank ) +{ + // Attach workers according to nodes. + // Submaster with rank 1 will have ranks 3 and 5 as subworkers. + // Submaster with rank 2 will have ranks 4 and 6 as subworkers. + vector workers; + workers.push_back( rank + 2 ); + workers.push_back( rank + 4 ); + DynamicAssignmentAlgorithm algo( workers ); + SubWork sw; + + // Launch the job! + ParallelApplyStore< SerializableBase > store( sw, rank ); + store.data( v ); + ParallelApply< SerializableBase > job( algo, rank, store ); + job.run(); + EmptyJob stop( algo, rank ); +} + +// Functor applied by submasters. Wait for the subworkers responses and then add some random processing (here, multiply +// each result by two). +// Note that this work receives a vector of integers as an entry, while subworkers task's operator receives a simple +// integer. +struct Work: public eoUF< SerializableVector< SerializableBase >&, void > +{ + void operator() ( SerializableVector< SerializableBase >& v ) + { + cout << "Work phase..." << endl; + subtask( v, Node::comm().rank() ); + for( unsigned i = 0; i < v.size(); ++i ) + { + v[i] *= 2; + } + } +}; + +int main(int argc, char** argv) +{ + // eo::log << eo::setlevel( eo::debug ); + Node::init( argc, argv ); + if( Node::comm().size() != 7 ) { + throw std::runtime_error("World size should be 7."); + } + + SerializableVector< SerializableBase > v; + + v.push_back(1); + v.push_back(3); + v.push_back(3); + v.push_back(7); + v.push_back(42); + + // As submasters' operator receives a vector as an input, and ParallelApply takes a vector of + // operator's input as an input, we have to deal with a vector of vector of integers for the master task. + vector< SerializableVector< SerializableBase > > metaV; + // Here, we send twice the same vector. We could also have splitted the first vector into two vectors, one + // containing the beginning and another one containing the end. + metaV.push_back( v ); + metaV.push_back( v ); + + // Assigning roles is done by comparing MPI ranks. + switch( Node::comm().rank() ) + { + // Nodes from 0 to 2 are implicated into the delegating task. + case 0: + case 1: + case 2: + { + Work w; + DynamicAssignmentAlgorithm algo( 1, 2 ); + ParallelApplyStore< SerializableVector< SerializableBase > > store( w, 0 ); + store.data( metaV ); + ParallelApply< SerializableVector< SerializableBase > > job( algo, 0, store ); + job.run(); + if( job.isMaster() ) + { + EmptyJob stop( algo, 0 ); + v = metaV[0]; + cout << "Results : " << endl; + for(unsigned i = 0; i < v.size(); ++i) + { + cout << v[i] << ' '; + } + cout << endl; + } + } + break; + + // Other nodes are implicated into the subwork task. + default: + { + // all the other nodes are sub workers + int rank = Node::comm().rank(); + if ( rank == 3 or rank == 5 ) + { + subtask( v, 1 ); + } else { + subtask( v, 2 ); + } + } + break; + } + + return 0; +} diff --git a/eo/test/mpi/t-mpi-multistart.cpp b/eo/test/mpi/t-mpi-multistart.cpp new file mode 100644 index 000000000..fb614e8ee --- /dev/null +++ b/eo/test/mpi/t-mpi-multistart.cpp @@ -0,0 +1,169 @@ +# include +using namespace eo::mpi; + +#include +#include +#include + +#include +#include + +/* + * This file is based on the tutorial lesson 1. We'll consider that you know all the EO + * related parts of the algorithm and we'll focus our attention on parallelization. + * + * This file shows an example of multistart applied to a eoSGA (simple genetic + * algorithm). As individuals need to be serialized, we implement a class inheriting + * from eoReal (which is the base individual), so as to manipulate individuals as they + * were eoReal AND serialize them. + * + * The main function shows how to launch a multistart job, with default functors. If you + * don't know which functors to use, these ones should fit the most of your purposes. + */ + +using namespace std; + +/* + * eoReal is a vector of double: we just have to serializes the value and the fitness. + */ +class SerializableEOReal: public eoReal, public eoserial::Persistent +{ +public: + + SerializableEOReal(unsigned size = 0, double value = 0.0) : + eoReal(size, value) + { + // empty + } + + void unpack( const eoserial::Object* obj ) + { + this->clear(); + eoserial::unpackArray + < std::vector, eoserial::Array::UnpackAlgorithm > + ( *obj, "vector", *this ); + + bool invalidFitness; + eoserial::unpack( *obj, "invalid_fitness", invalidFitness ); + if( invalidFitness ) + { + this->invalidate(); + } else + { + double f; + eoserial::unpack( *obj, "fitness", f ); + this->fitness( f ); + } + } + + eoserial::Object* pack( void ) const + { + eoserial::Object* obj = new eoserial::Object; + obj->add( "vector", eoserial::makeArray< std::vector, eoserial::MakeAlgorithm >( *this ) ); + + bool invalidFitness = this->invalid(); + obj->add( "invalid_fitness", eoserial::make( invalidFitness ) ); + if( !invalidFitness ) + { + obj->add( "fitness", eoserial::make( this->fitness() ) ); + } + + return obj; + } +}; + +// REPRESENTATION +//----------------------------------------------------------------------------- +// define your individuals +typedef SerializableEOReal Indi; + +// EVAL +//----------------------------------------------------------------------------- +// a simple fitness function that computes the euclidian norm of a real vector +// @param _indi A real-valued individual + +double real_value(const Indi & _indi) +{ + double sum = 0; + for (unsigned i = 0; i < _indi.size(); i++) + sum += _indi[i]*_indi[i]; + return (-sum); // maximizing only +} + +/************************** PARALLELIZATION JOB *******************************/ +int main(int argc, char **argv) +{ + Node::init( argc, argv ); + + // PARAMETRES + // all parameters are hard-coded! + const unsigned int SEED = 133742; // seed for random number generator + const unsigned int VEC_SIZE = 8; // Number of object variables in genotypes + const unsigned int POP_SIZE = 100; // Size of population + const unsigned int T_SIZE = 3; // size for tournament selection + const unsigned int MAX_GEN = 100; // Maximum number of generation before STOP + const float CROSS_RATE = 0.8; // Crossover rate + const double EPSILON = 0.01; // range for real uniform mutation + const float MUT_RATE = 0.5; // mutation rate + + eoEvalFuncPtr eval( real_value ); + eoPop pop; + eoUniformGenerator< double > generator; + eoInitFixedLength< Indi > init( VEC_SIZE, generator ); + pop = eoPop( POP_SIZE, init ); + + eoDetTournamentSelect select(T_SIZE); + eoSegmentCrossover xover; + eoUniformMutation mutation(EPSILON); + + eoGenContinue continuator(MAX_GEN); + /* Does work too with a steady fit continuator. */ + // eoSteadyFitContinue< Indi > continuator( 10, 50 ); + + eoSGA gga(select, xover, CROSS_RATE, mutation, MUT_RATE, + eval, continuator); + + /* How to assign tasks, which are starts? */ + DynamicAssignmentAlgorithm assignmentAlgo; + /* Before a worker starts its algorithm, how does it reinits the population? + * There are a few default usable functors, defined in eoMultiStart.h. + * + * This one (ReuseSamePopEA) doesn't modify the population after a start, so + * the same population is reevaluated on each multistart: the solution tend + * to get better and better. + */ + ReuseSamePopEA< Indi > resetAlgo( continuator, pop, eval ); + /** + * How to send seeds to the workers, at the beginning of the parallel job? + * This functors indicates that seeds should be random values. + */ + GetRandomSeeds< Indi > getSeeds( SEED ); + + // Builds the store + MultiStartStore< Indi > store( + gga, + DEFAULT_MASTER, + resetAlgo, + getSeeds); + + // Creates the multistart job and runs it. + // The last argument indicates that we want to launch 5 runs. + MultiStart< Indi > msjob( assignmentAlgo, DEFAULT_MASTER, store, 5 ); + msjob.run(); + + if( msjob.isMaster() ) + { + msjob.best_individuals().sort(); + std::cout << "Global best individual has fitness " << msjob.best_individuals().best_element().fitness() << std::endl; + } + + MultiStart< Indi > msjob10( assignmentAlgo, DEFAULT_MASTER, store, 10 ); + msjob10.run(); + + if( msjob10.isMaster() ) + { + msjob10.best_individuals().sort(); + std::cout << "Global best individual has fitness " << msjob10.best_individuals().best_element().fitness() << std::endl; + } + return 0; +} diff --git a/eo/test/mpi/t-mpi-parallelApply.cpp b/eo/test/mpi/t-mpi-parallelApply.cpp new file mode 100644 index 000000000..559505bd1 --- /dev/null +++ b/eo/test/mpi/t-mpi-parallelApply.cpp @@ -0,0 +1,220 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ + +/* + * This file shows an example of use of parallel apply, in the following context: each element of a table is + * incremented... in a parallel fashion. While this operation is very easy to perform even on a single host, it's just + * an example for parallel apply use. + * + * The table of integers has to be serialized before it's sent. The wrapper object SerializableBase allows to serialize + * any type and manipulate it like this type: SerializableBase can be exactly be used as an integer. + * + * Besides, this is also a test for assignment (scheduling) algorithms, in different cases. The test succeeds if and + * only if the program terminates without any segfault ; otherwise, there could be a deadlock which prevents the end or + * a segfault at any time. + * + * One important thing is to instanciate an EmptyJob after having launched a ParallelApplyJob, so as the workers to be + * aware that the job is done (as it's a MultiJob). + * + * This test needs at least 3 processes to be launched. Under this size, it will directly throw an exception, at the + * beginning; + */ + +# include +# include +# include + +# include "t-mpi-common.h" + +# include +# include + +# include +using namespace std; + +using namespace eo::mpi; + +/* + * The function to be called on each element of the table: just increment the value. + */ +struct plusOne : public eoUF< SerializableBase&, void > +{ + void operator() ( SerializableBase & x ) + { + ++x; // implicit conversion of SerializableBase in the integer it contains + } +}; + +/* + * Internal structure representating a test. + */ +struct Test +{ + AssignmentAlgorithm * assign; // used assignment algorithm for this test. + string description; // textual description of the test + int requiredNodesNumber; // number of required nodes. NB : chosen nodes ranks must be sequential +}; + +int main(int argc, char** argv) +{ + // eo::log << eo::setlevel( eo::debug ); // if you like tty full of rainbows, decomment this line and comment the following one. + eo::log << eo::setlevel( eo::quiet ); + + bool launchOnlyOne = false ; // Set this to true if you wanna launch only the first test. + + Node::init( argc, argv ); + + // Initializes a vector with random values. + srand( time(0) ); + vector< SerializableBase > v; + for( int i = 0; i < 1000; ++i ) + { + v.push_back( rand() ); + } + + // We need to be sure the values are correctly incremented between each test. So as to check this, we save the + // original vector into a variable originalV, and put an offset variable to 0. After each test, the offset is + // incremented and we can compare the returned value of each element to the value of each element in originalV + + // offset. If the two values are different, there has been a problem. + int offset = 0; + vector< SerializableBase > originalV = v; + + // Instanciates the functor to apply on each element + plusOne plusOneInstance; + + vector< Test > tests; + + const int ALL = Node::comm().size(); + if( ALL < 3 ) { + throw std::runtime_error("Needs at least 3 processes to be launched!"); + } + + // Tests are auto described thanks to member "description" + Test tIntervalStatic; + tIntervalStatic.assign = new StaticAssignmentAlgorithm( 1, REST_OF_THE_WORLD, v.size() ); + tIntervalStatic.description = "Correct static assignment with interval."; // workers have ranks from 1 to size - 1 + tIntervalStatic.requiredNodesNumber = ALL; + tests.push_back( tIntervalStatic ); + + if( !launchOnlyOne ) + { + Test tWorldStatic; + tWorldStatic.assign = new StaticAssignmentAlgorithm( v.size() ); + tWorldStatic.description = "Correct static assignment with whole world as workers."; + tWorldStatic.requiredNodesNumber = ALL; + tests.push_back( tWorldStatic ); + + Test tStaticOverload; + tStaticOverload.assign = new StaticAssignmentAlgorithm( v.size()+100 ); + tStaticOverload.description = "Static assignment with too many runs."; + tStaticOverload.requiredNodesNumber = ALL; + tests.push_back( tStaticOverload ); + + Test tUniqueStatic; + tUniqueStatic.assign = new StaticAssignmentAlgorithm( 1, v.size() ); + tUniqueStatic.description = "Correct static assignment with unique worker."; + tUniqueStatic.requiredNodesNumber = 2; + tests.push_back( tUniqueStatic ); + + Test tVectorStatic; + vector workers; + workers.push_back( 1 ); + workers.push_back( 2 ); + tVectorStatic.assign = new StaticAssignmentAlgorithm( workers, v.size() ); + tVectorStatic.description = "Correct static assignment with precise workers specified."; + tVectorStatic.requiredNodesNumber = 3; + tests.push_back( tVectorStatic ); + + Test tIntervalDynamic; + tIntervalDynamic.assign = new DynamicAssignmentAlgorithm( 1, REST_OF_THE_WORLD ); + tIntervalDynamic.description = "Dynamic assignment with interval."; + tIntervalDynamic.requiredNodesNumber = ALL; + tests.push_back( tIntervalDynamic ); + + Test tUniqueDynamic; + tUniqueDynamic.assign = new DynamicAssignmentAlgorithm( 1 ); + tUniqueDynamic.description = "Dynamic assignment with unique worker."; + tUniqueDynamic.requiredNodesNumber = 2; + tests.push_back( tUniqueDynamic ); + + Test tVectorDynamic; + tVectorDynamic.assign = new DynamicAssignmentAlgorithm( workers ); + tVectorDynamic.description = "Dynamic assignment with precise workers specified."; + tVectorDynamic.requiredNodesNumber = tVectorStatic.requiredNodesNumber; + tests.push_back( tVectorDynamic ); + + Test tWorldDynamic; + tWorldDynamic.assign = new DynamicAssignmentAlgorithm; + tWorldDynamic.description = "Dynamic assignment with whole world as workers."; + tWorldDynamic.requiredNodesNumber = ALL; + tests.push_back( tWorldDynamic ); + } + + for( unsigned int i = 0; i < tests.size(); ++i ) + { + // Instanciates a store with the functor, the master rank and size of packet (see ParallelApplyStore doc). + ParallelApplyStore< SerializableBase > store( plusOneInstance, eo::mpi::DEFAULT_MASTER, 3 ); + // Updates the contained data + store.data( v ); + // Creates the job with the assignment algorithm, the master rank and the store + ParallelApply< SerializableBase > job( *(tests[i].assign), eo::mpi::DEFAULT_MASTER, store ); + + // Only master writes information + if( job.isMaster() ) + { + cout << "Test : " << tests[i].description << endl; + } + + // Workers whose rank is inferior to required nodes number have to run the test, the other haven't anything to + // do. + if( Node::comm().rank() < tests[i].requiredNodesNumber ) + { + job.run(); + } + + // After the job run, the master checks the result with offset and originalV + if( job.isMaster() ) + { + // This job has to be instanciated, not launched, so as to tell the workers they're done with the parallel + // job. + EmptyJob stop( *(tests[i].assign), eo::mpi::DEFAULT_MASTER ); + ++offset; + for(unsigned i = 0; i < v.size(); ++i) + { + cout << v[i] << ' '; + if( originalV[i] + offset != v[i] ) + { + cout << " <-- ERROR at this point." << endl; + exit( EXIT_FAILURE ); + } + } + cout << endl; + } + + // MPI synchronization (all the processes wait to be here). + Node::comm().barrier(); + + delete tests[i].assign; + } + return 0; +} + diff --git a/eo/test/mpi/t-mpi-wrapper.cpp b/eo/test/mpi/t-mpi-wrapper.cpp new file mode 100644 index 000000000..7e5fa4d2f --- /dev/null +++ b/eo/test/mpi/t-mpi-wrapper.cpp @@ -0,0 +1,133 @@ +/* +(c) Thales group, 2012 + + This library is free software; you 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: + Benjamin Bouvier +*/ + +/* + * This file shows an example of how to wrap a handler of a job store. Here, the wrapped handler is the "IsFinished" + * one. The only function that has been added is that the wrapper prints a message on standard output, indicating what + * the wrapped function returns as a result. + * + * This test is performed on a parallel apply job, the same as in parallelApply. The main difference is when + * instanciating the store. + */ + +# include +# include +# include + +# include "t-mpi-common.h" + +# include +# include + +# include +using namespace std; + +using namespace eo::mpi; + +// Job functor. +struct plusOne : public eoUF< SerializableBase&, void > +{ + void operator() ( SerializableBase& x ) + { + ++x; + } +}; + +/* + * Shows the wrapped result of IsFinished, prints a message and returns the wrapped value. + * times is an integer counting how many time the wrapper (hence the wrapped too) has been called. + */ +template< class EOT > +struct ShowWrappedResult : public IsFinishedParallelApply +{ + using IsFinishedParallelApply::_wrapped; + + ShowWrappedResult ( IsFinishedParallelApply * w = 0 ) : IsFinishedParallelApply( w ), times( 0 ) + { + // empty + } + + bool operator()() + { + bool wrappedValue = _wrapped->operator()(); // (*_wrapped)(); + cout << times << ") Wrapped function would say that it is " << ( wrappedValue ? "":"not ") << "finished" << std::endl; + ++times; + return wrappedValue; + } + + private: + int times; +}; + +int main(int argc, char** argv) +{ + // eo::log << eo::setlevel( eo::debug ); + eo::log << eo::setlevel( eo::quiet ); + + Node::init( argc, argv ); + + srand( time(0) ); + vector< SerializableBase > v; + for( int i = 0; i < 1000; ++i ) + { + v.push_back( rand() ); + } + + int offset = 0; + vector< SerializableBase > originalV = v; + + plusOne plusOneInstance; + + StaticAssignmentAlgorithm assign( v.size() ); + + ParallelApplyStore< SerializableBase > store( plusOneInstance, eo::mpi::DEFAULT_MASTER, 1 ); + store.data( v ); + // This is the only thing which changes: we wrap the IsFinished function. + // According to RAII, we'll delete the invokated wrapper at the end of the main ; the store won't delete it + // automatically. + ShowWrappedResult< SerializableBase > wrapper; + store.wrapIsFinished( &wrapper ); + + ParallelApply< SerializableBase > job( assign, eo::mpi::DEFAULT_MASTER, store ); + // Equivalent to: + // Job< ParallelApplyData > job( assign, 0, store ); + job.run(); + EmptyJob stop( assign, eo::mpi::DEFAULT_MASTER ); + + if( job.isMaster() ) + { + ++offset; + for(unsigned i = 0; i < v.size(); ++i) + { + cout << v[i] << ' '; + if( originalV[i] + offset != v[i] ) + { + cout << " <-- ERROR at this point." << endl; + exit( EXIT_FAILURE ); + } + } + cout << endl; + } + + return 0; +} + diff --git a/eo/test/mpi/template-job.cpp b/eo/test/mpi/template-job.cpp new file mode 100644 index 000000000..3d25e9736 --- /dev/null +++ b/eo/test/mpi/template-job.cpp @@ -0,0 +1,104 @@ +# include + +using namespace eo::mpi; + +/* + * This file is a template for a new eo::mpi::Job. You have everything that should be necessary to implement a new + * parallelized algorithm. + * + * Replace __TEMPLATE__ by the name of your algorithm (for instance: MultiStart, ParallelApply, etc.). + */ + +template< class EOT > +struct __TEMPLATE__Data +{ + +}; + +template< class EOT > +class SendTask__TEMPLATE__ : public SendTaskFunction< __TEMPLATE__Data< EOT > > +{ + public: + + using SendTaskFunction< __TEMPLATE__Data< EOT > >::_data; + + void operator()( int wrkRank ) + { + // TODO implement me + } +}; + +template< class EOT > +class HandleResponse__TEMPLATE__ : public HandleResponseFunction< __TEMPLATE__Data< EOT > > +{ + public: + + using HandleResponseFunction< __TEMPLATE__Data< EOT > >::_data; + + void operator()( int wrkRank ) + { + // TODO implement me + } +}; + +template< class EOT > +class ProcessTask__TEMPLATE__ : public ProcessTaskFunction< __TEMPLATE__Data< EOT > > +{ + public: + using ProcessTaskFunction< __TEMPLATE__Data >::_data; + + void operator()() + { + // TODO implement me + } +}; + +template< class EOT > +class IsFinished__TEMPLATE__ : public IsFinishedFunction< __TEMPLATE__Data< EOT > > +{ + public: + + using IsFinishedFunction< __TEMPLATE__Data< EOT > >::_data; + + bool operator()() + { + // TODO implement me + } +}; + +template< class EOT > +class __TEMPLATE__Store : public JobStore< __TEMPLATE__Data< EOT > > +{ + public: + + __TEMPLATE__Data* data() + { + // TODO implement me + return 0; + } +}; + +template< class EOT > +class __TEMPLATE__ : public MultiJob< __TEMPLATE__Data< EOT > > +{ + public: + + __TEMPLATE__( AssignmentAlgorithm & algo, + int masterRank, + __TEMPLATE__Store< EOT > & store ) : + MultiJob< __TEMPLATE__Data< EOT > >( algo, masterRank, store ) + { + // TODO implement me + } +}; + +/* +int main(int argc, char **argv) +{ + Node::init( argc, argv ); + + DynamicAssignmentAlgorithm assignmentAlgo; + __TEMPLATE__Store store; + __TEMPLATE__ job( assignmentAlgo, DEFAULT_MASTER, store ); +} +*/ diff --git a/eo/test/t-MGE-control.cpp b/eo/test/t-MGE-control.cpp index 240dd3688..d2d4d224d 100644 --- a/eo/test/t-MGE-control.cpp +++ b/eo/test/t-MGE-control.cpp @@ -69,7 +69,8 @@ int main() // Terminators eoGenContinue continuator1(10); eoFitContinue continuator2(CHROM_SIZE); - eoCombinedContinue continuator(continuator1, continuator2); + eoCombinedContinue continuator(continuator1); + continuator.add( continuator2 ); eoCheckPoint checkpoint(continuator); eoStdoutMonitor monitor; checkpoint.add(monitor); diff --git a/eo/test/t-MGE.cpp b/eo/test/t-MGE.cpp index a122b5e70..275847e18 100644 --- a/eo/test/t-MGE.cpp +++ b/eo/test/t-MGE.cpp @@ -73,7 +73,8 @@ int main() // Terminators eoGenContinue continuator1(10); eoFitContinue continuator2(CHROM_SIZE); - eoCombinedContinue continuator(continuator1, continuator2); + eoCombinedContinue continuator(continuator1); + continuator.add( continuator2); eoCheckPoint checkpoint(continuator); eoStdoutMonitor monitor; checkpoint.add(monitor); diff --git a/eo/test/t-MGE1bit.cpp b/eo/test/t-MGE1bit.cpp index 842f5cd77..6ef1c874c 100644 --- a/eo/test/t-MGE1bit.cpp +++ b/eo/test/t-MGE1bit.cpp @@ -72,7 +72,8 @@ int main() // Terminators eoGenContinue continuator1(10); eoFitContinue continuator2(CHROM_SIZE); - eoCombinedContinue continuator(continuator1, continuator2); + eoCombinedContinue continuator(continuator1); + continuator.add(continuator2); eoCheckPoint checkpoint(continuator); eoStdoutMonitor monitor; checkpoint.add(monitor); diff --git a/eo/test/t-eoEvalKeepBest.cpp b/eo/test/t-eoEvalKeepBest.cpp new file mode 100644 index 000000000..fdcdae866 --- /dev/null +++ b/eo/test/t-eoEvalKeepBest.cpp @@ -0,0 +1,78 @@ +#include + +#include +#include +#include +#include "real_value.h" + +using namespace std; + +int main(int argc, char* argv[]) +{ + + typedef eoReal EOT; + + eoParser parser(argc, argv); // for user-parameter reading + eoState state; // keeps all things allocated + + + /********************************************* + * problem or representation dependent stuff * + *********************************************/ + + // The evaluation fn - encapsulated into an eval counter for output + eoEvalFuncPtr&> + main_eval( real_value ); // use a function defined in real_value.h + + // wrap the evaluation function in a call counter + eoEvalFuncCounter eval_counter(main_eval); + + // the genotype - through a genotype initializer + eoRealInitBounded& init = make_genotype(parser, state, EOT()); + + // Build the variation operator (any seq/prop construct) + eoGenOp& op = make_op(parser, state, init); + + + /********************************************* + * Now the representation-independent things * + *********************************************/ + + + // initialize the population - and evaluate + // yes, this is representation indepedent once you have an eoInit + eoPop& pop = make_pop(parser, state, init); + + // stopping criteria + eoContinue & term = make_continue(parser, state, eval_counter); + + // things that are called at each generation + eoCheckPoint & checkpoint = make_checkpoint(parser, state, eval_counter, term); + + // wrap the evaluator in another one that will keep the best individual + // evaluated so far + eoEvalKeepBest eval_keep( eval_counter ); + + // algorithm + eoAlgo& ea = make_algo_scalar(parser, state, eval_keep, checkpoint, op); + + + /*************************************** + * Now, call functors and DO something * + ***************************************/ + + // to be called AFTER all parameters have been read! + make_help(parser); + + // evaluate intial population AFTER help and status in case it takes time + apply(eval_keep, pop); + + std::clog << "Best individual after initialization and " << eval_counter.value() << " evaluations" << std::endl; + std::cout << eval_keep.best_element() << std::endl; + + ea(pop); // run the ea + + std::cout << "Best individual after search and " << eval_counter.value() << " evaluations" << std::endl; + // you can also call value(), because it is an eoParam + std::cout << eval_keep.value() << std::endl; +} diff --git a/eo/test/t-eoInitVariableLength.cpp b/eo/test/t-eoInitVariableLength.cpp new file mode 100644 index 000000000..68dee1b9c --- /dev/null +++ b/eo/test/t-eoInitVariableLength.cpp @@ -0,0 +1,98 @@ +#include +#include +#include + +// An adhoc atom type of our own +class Quad : public std::vector +{ + public: + // Just four times zero + Quad() : std::vector(4,0) {} +}; + +// EO somewhat forces you to implement a way to read/print your atom type +// You can either inherit from eoPrintable and overload readFrom/printOn +// or, just like here, directly overload stream operators. + +// read +std::istream& operator>>( std::istream& is, Quad& q ) +{ + for( unsigned int i=0, n=4; i> q[i]; + } + return is; +} + +// print +std::ostream& operator<<( std::ostream& os, const Quad& q ) +{ + os << q[0]; + for( unsigned int i=1, n=4; i +{ + public: + // this is the API: an init modify the solution + void operator()( Quad& q ) { + for( unsigned int i=0, n=4; i +{}; + + +int main() +{ + unsigned int vec_size_min = 1; + unsigned int vec_size_max = 10; + unsigned int pop_size = 10; + + // Fix a seed for the random generator, + // thus, the results are predictable. + // Set it to zero if you want pseudo-random numbers + // that changes at each calls. + rng.reseed( 1 ); + + // The operator that produce a random vector of four values. + QuadInit atom_init; + + // The operator that produces a random vector of a (vector of four values). + eoInitVariableLength vec_init( vec_size_min, vec_size_max, atom_init ); + + // You can initialize a population of N individuals by passing an initializer to it. + eoPop pop( pop_size, vec_init ); + + // eoPop can be printed easily, + // thanks to the overloadings above. + std::cout << pop << std::endl; + +// With a seed at 1, this should output: +/* +10 +INVALID 6 5 9 5 9 0 1 6 0 4 8 9 0 6 9 4 9 5 5 3 6 3 0 2 8 +INVALID 9 9 2 0 3 2 4 3 3 6 2 8 2 4 5 4 7 5 3 0 5 4 9 8 3 2 7 7 9 4 4 4 6 6 3 9 2 +INVALID 1 1 4 1 4 +INVALID 5 3 8 9 8 8 1 4 1 6 6 5 4 3 2 7 5 1 2 6 1 +INVALID 3 7 8 1 4 0 9 1 0 6 4 2 1 +INVALID 6 7 4 6 8 1 2 6 0 5 1 2 6 9 2 6 8 6 1 5 5 4 1 0 3 +INVALID 5 2 7 7 6 1 4 0 7 5 5 9 7 2 4 7 1 6 1 9 0 +INVALID 3 5 5 3 9 2 9 9 1 1 7 2 1 +INVALID 6 9 9 9 0 0 7 1 7 9 7 8 5 3 7 5 6 7 3 6 7 6 3 3 5 +INVALID 1 6 2 4 3 +*/ +} diff --git a/eo/test/t-eobin.cpp b/eo/test/t-eobin.cpp index d857dd822..2a36d0ee1 100644 --- a/eo/test/t-eobin.cpp +++ b/eo/test/t-eobin.cpp @@ -139,7 +139,8 @@ void main_function() eoGenContinue continuator1(50); eoFitContinue continuator2(65535.f); - eoCombinedContinue continuator(continuator1, continuator2); + eoCombinedContinue continuator(continuator1); + continuator.add( continuator2); eoCheckPoint checkpoint(continuator); diff --git a/eo/tutorial/Lesson1/CMakeLists.txt b/eo/tutorial/Lesson1/CMakeLists.txt index 9f707750b..96619394d 100644 --- a/eo/tutorial/Lesson1/CMakeLists.txt +++ b/eo/tutorial/Lesson1/CMakeLists.txt @@ -2,63 +2,63 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EO_SRC_DIR}/src/ga) +include_directories(${EO_SRC_DIR}/src/utils) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) -ENDIF(NOT WIN32 OR CYGWIN) +if(NOT WIN32 OR CYGWIN) + link_directories(${EO_BIN_DIR}/lib) +endif(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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) -ADD_DEPENDENCIES(exercise1.3 ga eo eoutils) +add_dependencies(FirstBitGA ga eo eoutils) +add_dependencies(FirstRealGA ga eo eoutils) +add_dependencies(exercise1.3 ga eo eoutils) ###################################################################################### ### 4) Optionnal ###################################################################################### -SET(FIRSTBITGA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(FirstBitGA PROPERTIES VERSION "${FIRSTBITGA_VERSION}") +set(FIRSTBITGA_VERSION ${GLOBAL_VERSION}) +set_target_properties(FirstBitGA PROPERTIES VERSION "${FIRSTBITGA_VERSION}") -SET(FIRSTREALGA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(FirstRealGA PROPERTIES VERSION "${FIRSTREALGA_VERSION}") +set(FIRSTREALGA_VERSION ${GLOBAL_VERSION}) +set_target_properties(FirstRealGA PROPERTIES VERSION "${FIRSTREALGA_VERSION}") -SET(EXERCICE13_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(exercise1.3 PROPERTIES VERSION "${EXERCICE13_VERSION}") +set(EXERCICE13_VERSION ${GLOBAL_VERSION}) +set_target_properties(exercise1.3 PROPERTIES VERSION "${EXERCICE13_VERSION}") ###################################################################################### ### 5) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(FirstBitGA ga eo eoutils) -TARGET_LINK_LIBRARIES(FirstRealGA ga eo eoutils) -TARGET_LINK_LIBRARIES(exercise1.3 ga eo eoutils) +target_link_libraries(FirstBitGA ga eo eoutils) +target_link_libraries(FirstRealGA ga eo eoutils) +target_link_libraries(exercise1.3 ga eo eoutils) ###################################################################################### ### 6) Configure project installation paths ###################################################################################### -INSTALL(TARGETS FirstBitGA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) -INSTALL(TARGETS FirstRealGA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) -INSTALL(TARGETS exercise1.3 RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) +install(TARGETS FirstBitGA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) +install(TARGETS FirstRealGA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) +install(TARGETS exercise1.3 RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson1 COMPONENT examples) ###################################################################################### diff --git a/eo/tutorial/Lesson2/CMakeLists.txt b/eo/tutorial/Lesson2/CMakeLists.txt index 28b4fada8..519e8a0e7 100644 --- a/eo/tutorial/Lesson2/CMakeLists.txt +++ b/eo/tutorial/Lesson2/CMakeLists.txt @@ -2,59 +2,59 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EO_SRC_DIR}/src/ga) +include_directories(${EO_SRC_DIR}/src/utils) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) -ENDIF(NOT WIN32 OR CYGWIN) +if(NOT WIN32 OR CYGWIN) + link_directories(${EO_BIN_DIR}/lib) +endif(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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 ###################################################################################### -SET(FIRSTBITEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(FirstBitEA PROPERTIES VERSION "${FIRSTBITEA_VERSION}") +set(FIRSTBITEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(FirstBitEA PROPERTIES VERSION "${FIRSTBITEA_VERSION}") -SET(FIRSTREALEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(FirstRealEA PROPERTIES VERSION "${FIRSTREALEA_VERSION}") +set(FIRSTREALEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(FirstRealEA PROPERTIES VERSION "${FIRSTREALEA_VERSION}") -SET(EXERCICE23_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(exercise2.3 PROPERTIES VERSION "${EXERCICE23_VERSION}") +set(EXERCICE23_VERSION ${GLOBAL_VERSION}) +set_target_properties(exercise2.3 PROPERTIES VERSION "${EXERCICE23_VERSION}") ###################################################################################### ### 5) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(FirstBitEA ga eo eoutils) -TARGET_LINK_LIBRARIES(FirstRealEA ga eo eoutils) -TARGET_LINK_LIBRARIES(exercise2.3 ga eo eoutils) +target_link_libraries(FirstBitEA ga eo eoutils) +target_link_libraries(FirstRealEA ga eo eoutils) +target_link_libraries(exercise2.3 ga eo eoutils) ###################################################################################### ### 6) Configure project installation paths ###################################################################################### -INSTALL(TARGETS FirstBitEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) -INSTALL(TARGETS FirstRealEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) -INSTALL(TARGETS exercise2.3 RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) +install(TARGETS FirstBitEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) +install(TARGETS FirstRealEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) +install(TARGETS exercise2.3 RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson2 COMPONENT examples) ###################################################################################### diff --git a/eo/tutorial/Lesson3/CMakeLists.txt b/eo/tutorial/Lesson3/CMakeLists.txt index 0d5467d45..d4d7563b2 100644 --- a/eo/tutorial/Lesson3/CMakeLists.txt +++ b/eo/tutorial/Lesson3/CMakeLists.txt @@ -2,63 +2,63 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EO_SRC_DIR}/src/ga) +include_directories(${EO_SRC_DIR}/src/utils) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) -ENDIF(NOT WIN32 OR CYGWIN) +if(NOT WIN32 OR CYGWIN) + link_directories(${EO_BIN_DIR}/lib) +endif(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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) -ADD_DEPENDENCIES(exercise3.1 ga eoutils eo) +add_dependencies(SecondBitEA ga eoutils eo) +add_dependencies(SecondRealEA ga eoutils eo) +add_dependencies(exercise3.1 ga eoutils eo) ###################################################################################### ### 4) Optionnal ###################################################################################### -SET(SECONDBITEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(SecondBitEA PROPERTIES VERSION "${SECONDBITEA_VERSION}") +set(SECONDBITEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(SecondBitEA PROPERTIES VERSION "${SECONDBITEA_VERSION}") -SET(SECONDREALEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(SecondRealEA PROPERTIES VERSION "${SECONDREALEA_VERSION}") +set(SECONDREALEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(SecondRealEA PROPERTIES VERSION "${SECONDREALEA_VERSION}") -SET(EXERCICE31_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(exercise3.1 PROPERTIES VERSION "${EXERCICE31_VERSION}") +set(EXERCICE31_VERSION ${GLOBAL_VERSION}) +set_target_properties(exercise3.1 PROPERTIES VERSION "${EXERCICE31_VERSION}") ###################################################################################### ### 5) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(SecondBitEA ga eoutils eo) -TARGET_LINK_LIBRARIES(SecondRealEA ga eoutils eo) -TARGET_LINK_LIBRARIES(exercise3.1 ga eoutils eo) +target_link_libraries(SecondBitEA ga eoutils eo) +target_link_libraries(SecondRealEA ga eoutils eo) +target_link_libraries(exercise3.1 ga eoutils eo) ###################################################################################### ### 6) Configure project installation paths ###################################################################################### -INSTALL(TARGETS SecondBitEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) -INSTALL(TARGETS SecondRealEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) -INSTALL(TARGETS exercise3.1 RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) +install(TARGETS SecondBitEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) +install(TARGETS SecondRealEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) +install(TARGETS exercise3.1 RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson3 COMPONENT examples) ###################################################################################### diff --git a/eo/tutorial/Lesson4/CMakeLists.txt b/eo/tutorial/Lesson4/CMakeLists.txt index f85b2898d..5042796fe 100644 --- a/eo/tutorial/Lesson4/CMakeLists.txt +++ b/eo/tutorial/Lesson4/CMakeLists.txt @@ -2,97 +2,97 @@ ### 0) Copy the ESEA.param and RealEA.param files in the build directory for an easy use. ###################################################################################### -EXECUTE_PROCESS( +execute_process( COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param - ${EO_BINARY_DIR}/tutorial/Lesson4/ESEA.param + ${EO_SRC_DIR}/tutorial/Lesson4/ESEA.param + ${EO_BIN_DIR}/tutorial/Lesson4/ESEA.param COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param - ${EO_BINARY_DIR}/tutorial/Lesson4/RealEA.param + ${EO_SRC_DIR}/tutorial/Lesson4/RealEA.param + ${EO_BIN_DIR}/tutorial/Lesson4/RealEA.param ) ############## # OLD_TARGETS ############## -#ADD_CUSTOM_TARGET(param DEPENDS ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param) -#ADD_CUSTOM_COMMAND( +#add_custom_target(param DEPENDS ${EO_SRC_DIR}/tutorial/Lesson4/ESEA.param) +#add_custom_command( # TARGET param # POST_BUILD # COMMAND ${CMAKE_COMMAND} # ARGS -E copy_if_different -# ${EO_SOURCE_DIR}/tutorial/Lesson4/ESEA.param -# ${EO_BINARY_DIR}/tutorial/Lesson4) -#ADD_CUSTOM_TARGET(param DEPENDS ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param) -#ADD_CUSTOM_COMMAND( +# ${EO_SRC_DIR}/tutorial/Lesson4/ESEA.param +# ${EO_BIN_DIR}/tutorial/Lesson4) +#add_custom_target(param DEPENDS ${EO_SRC_DIR}/tutorial/Lesson4/RealEA.param) +#add_custom_command( # TARGET param # POST_BUILD # COMMAND ${CMAKE_COMMAND} # ARGS -E copy_if_different -# ${EO_SOURCE_DIR}/tutorial/Lesson4/RealEA.param -# ${EO_BINARY_DIR}/tutorial/Lesson4) +# ${EO_SRC_DIR}/tutorial/Lesson4/RealEA.param +# ${EO_BIN_DIR}/tutorial/Lesson4) ###################################################################################### ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/es) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/utils) -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src/ga) +include_directories(${EO_SRC_DIR}/src) +include_directories(${EO_SRC_DIR}/src/es) +include_directories(${EO_SRC_DIR}/src/utils) +include_directories(${EO_SRC_DIR}/src/ga) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) -ENDIF(NOT WIN32 OR CYGWIN) +if(NOT WIN32 OR CYGWIN) + link_directories(${EO_BIN_DIR}/lib) +endif(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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) -#ADD_DEPENDENCIES(ESEA es ga eo eoutils) +#add_dependencies(BitEA es ga eo eoutils) +#add_dependencies(RealEA es ga eo eoutils) +#add_dependencies(ESEA es ga eo eoutils) ###################################################################################### ### 4) Optionnal ###################################################################################### -SET(BITEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(BitEA PROPERTIES VERSION "${BITEA_VERSION}") +set(BITEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(BitEA PROPERTIES VERSION "${BITEA_VERSION}") -SET(REALEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(RealEA PROPERTIES VERSION "${REALEA_VERSION}") +set(REALEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(RealEA PROPERTIES VERSION "${REALEA_VERSION}") -SET(ESEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(ESEA PROPERTIES VERSION "${ESEA_VERSION}") +set(ESEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(ESEA PROPERTIES VERSION "${ESEA_VERSION}") ###################################################################################### ### 5) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(BitEA es ga eo eoutils) -TARGET_LINK_LIBRARIES(RealEA es ga eo eoutils) -TARGET_LINK_LIBRARIES(ESEA es ga eo eoutils) +target_link_libraries(BitEA es ga eo eoutils) +target_link_libraries(RealEA es ga eo eoutils) +target_link_libraries(ESEA es ga eo eoutils) ###################################################################################### ### 6) Configure project installation paths ###################################################################################### -INSTALL(TARGETS BitEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) -INSTALL(TARGETS RealEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) -INSTALL(TARGETS ESEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) +install(TARGETS BitEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) +install(TARGETS RealEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) +install(TARGETS ESEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson4 COMPONENT examples) ###################################################################################### diff --git a/eo/tutorial/Lesson5/CMakeLists.txt b/eo/tutorial/Lesson5/CMakeLists.txt index c79c45875..2987b041e 100644 --- a/eo/tutorial/Lesson5/CMakeLists.txt +++ b/eo/tutorial/Lesson5/CMakeLists.txt @@ -2,55 +2,55 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${EO_SRC_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) -ENDIF(NOT WIN32 OR CYGWIN) +if(NOT WIN32 OR CYGWIN) + link_directories(${EO_BIN_DIR}/lib) +endif(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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) +add_dependencies(OneMaxEA es ga eo eoutils) +add_dependencies(OneMaxLibEA es ga eo eoutils) ###################################################################################### ### 4) Optionnal ###################################################################################### -SET(ONEMAXEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(OneMaxEA PROPERTIES VERSION "${ONEMAXEA_VERSION}") +set(ONEMAXEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(OneMaxEA PROPERTIES VERSION "${ONEMAXEA_VERSION}") -SET(ONEMAXLIBEA_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(OneMaxLibEA PROPERTIES VERSION "${ONEMAXLIBEA_VERSION}") +set(ONEMAXLIBEA_VERSION ${GLOBAL_VERSION}) +set_target_properties(OneMaxLibEA PROPERTIES VERSION "${ONEMAXLIBEA_VERSION}") ###################################################################################### ### 5) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(OneMaxEA es ga eo eoutils) -TARGET_LINK_LIBRARIES(OneMaxLibEA es ga eo eoutils) +target_link_libraries(OneMaxEA es ga eo eoutils) +target_link_libraries(OneMaxLibEA es ga eo eoutils) ###################################################################################### ### 6) Configure project installation paths ###################################################################################### -INSTALL(TARGETS OneMaxEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson5 COMPONENT examples) -INSTALL(TARGETS OneMaxLibEA RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson5 COMPONENT examples) +install(TARGETS OneMaxEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson5 COMPONENT examples) +install(TARGETS OneMaxLibEA RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson5 COMPONENT examples) ###################################################################################### diff --git a/eo/tutorial/Lesson6/CMakeLists.txt b/eo/tutorial/Lesson6/CMakeLists.txt index b29e76fac..2df16a459 100644 --- a/eo/tutorial/Lesson6/CMakeLists.txt +++ b/eo/tutorial/Lesson6/CMakeLists.txt @@ -2,50 +2,50 @@ ### 1) Include the sources ###################################################################################### -INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src) +include_directories(${EO_SRC_DIR}/src) ###################################################################################### ### 2) Specify where CMake can find the libraries ###################################################################################### -IF(NOT WIN32 OR CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}/lib) -ENDIF(NOT WIN32 OR CYGWIN) +if(NOT WIN32 OR CYGWIN) + link_directories(${EO_BIN_DIR}/lib) +endif(NOT WIN32 OR CYGWIN) # especially for Visual Studio -IF(WIN32 AND NOT CYGWIN) - LINK_DIRECTORIES(${EO_BINARY_DIR}\\lib\\${CMAKE_BUILD_TYPE}) -ENDIF(WIN32 AND NOT CYGWIN) +if(WIN32 AND NOT CYGWIN) + link_directories(${EO_BIN_DIR}\\lib\\${CMAKE_BUILD_TYPE}) +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 ###################################################################################### -SET(BINARYPSO_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(BinaryPSO PROPERTIES VERSION "${BINARYPSO_VERSION}") +set(BINARYPSO_VERSION ${GLOBAL_VERSION}) +set_target_properties(BinaryPSO PROPERTIES VERSION "${BINARYPSO_VERSION}") -SET(REALPSO_VERSION ${GLOBAL_VERSION}) -SET_TARGET_PROPERTIES(RealPSO PROPERTIES VERSION "${REALPSO_VERSION}") +set(REALPSO_VERSION ${GLOBAL_VERSION}) +set_target_properties(RealPSO PROPERTIES VERSION "${REALPSO_VERSION}") ###################################################################################### ### 5) Link the librairies for the targets ###################################################################################### -TARGET_LINK_LIBRARIES(BinaryPSO eo eoutils) -TARGET_LINK_LIBRARIES(RealPSO eo eoutils) +target_link_libraries(BinaryPSO eo eoutils) +target_link_libraries(RealPSO eo eoutils) ###################################################################################### ### 6) Configure project installation paths ###################################################################################### -INSTALL(TARGETS BinaryPSO RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson6 COMPONENT examples) -INSTALL(TARGETS RealPSO RUNTIME DESTINATION share${INSTALL_SUB_DIR}/eo/examples/Lesson6 COMPONENT examples) +install(TARGETS BinaryPSO RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson6 COMPONENT examples) +install(TARGETS RealPSO RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/examples/Lesson6 COMPONENT examples) ###################################################################################### diff --git a/eo/tutorial/Parallelization/INSTALL b/eo/tutorial/Parallelization/INSTALL new file mode 100644 index 000000000..827216807 --- /dev/null +++ b/eo/tutorial/Parallelization/INSTALL @@ -0,0 +1,63 @@ +How to install EoMPI +==================== + +Install OpenMpi +--------------- + +1) Download OpenMPI on their website or with the following command: + + wget http://www.open-mpi.org/software/ompi/v1.6/downloads/openmpi-1.6.tar.bz2 + +2) Untar the downloaded archive in a directory and change working directory to there: + + tar -xvjf openmpi*.tar.bz2 + cd openmpi-X.Y + +3) Use configuration script to indicate in which directory OpenMPI should be installed, and other options: + +Simplest configuration: + ./configure --prefix=/home/`whoami`/openmpi/ + +Only static libraries: + ./configure --enable-static --disable-shared + +Only static libraries, with prefix, disable build for Fortran77 and Fortran90, add support for SGE: + ./configure --enable-static --disable-shared --prefix=/home/`whoami`/openmpi/ --disable-mpi-f77 --disable-mpi-f90 --with-sge + +Other options are available in the README file. + +4) Make it and install: + +In sequential: + make all install + +Or in parallel: + make -j 2 all + make install + +5) Try to compile and run the sample program: + + ~/openmpi/bin/mpicxx -o sample mpi.c + ~/openmpi/bin/mpirun -np 3 ./sample + +Configure EO to use MPI +----------------------- + +You only need to configure eo-conf.cmake so as to use MPI : + +1) Put the WITH_MPI boolean to true: + + SET(WITH_MPI TRUE CACHE BOOL "Use mpi ?" FORCE) + +2) Indicate in which directories you have installed openmpi: + + SET(MPI_DIR "/where/did/you/install/openmpi" CACHE PATH "OpenMPI directory" FORCE) + +3) Recompile eo: + + ./distclean + ./build_gcc_linux_release.sh + +4) If you meet any issue, don't hesitate to contact the EO mailing list: + + eodev-main@lists.sourceforge.net diff --git a/eo/tutorial/Parallelization/css/deck.core.css b/eo/tutorial/Parallelization/css/deck.core.css new file mode 100644 index 000000000..a188b28fd --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.core.css @@ -0,0 +1,405 @@ +html { + height: 100%; +} + +body.deck-container { + overflow-y: auto; + position: static; +} + +.deck-container { + position: relative; + min-height: 100%; + margin: 0 auto; + padding: 0 48px; + font-size: 16px; + line-height: 1.25; + overflow: hidden; + /* Resets and base styles from HTML5 Boilerplate */ + /* End HTML5 Boilerplate adaptations */ +} +.js .deck-container { + visibility: hidden; +} +.ready .deck-container { + visibility: visible; +} +.touch .deck-container { + -webkit-text-size-adjust: none; + -moz-text-size-adjust: none; +} +.deck-container div, .deck-container span, .deck-container object, .deck-container iframe, +.deck-container h1, .deck-container h2, .deck-container h3, .deck-container h4, .deck-container h5, .deck-container h6, .deck-container p, .deck-container blockquote, .deck-container pre, +.deck-container abbr, .deck-container address, .deck-container cite, .deck-container code, .deck-container del, .deck-container dfn, .deck-container em, .deck-container img, .deck-container ins, .deck-container kbd, .deck-container q, .deck-container samp, +.deck-container small, .deck-container strong, .deck-container sub, .deck-container sup, .deck-container var, .deck-container b, .deck-container i, .deck-container dl, .deck-container dt, .deck-container dd, .deck-container ol, .deck-container ul, .deck-container li, +.deck-container fieldset, .deck-container form, .deck-container label, .deck-container legend, +.deck-container table, .deck-container caption, .deck-container tbody, .deck-container tfoot, .deck-container thead, .deck-container tr, .deck-container th, .deck-container td, +.deck-container article, .deck-container aside, .deck-container canvas, .deck-container details, .deck-container figcaption, .deck-container figure, +.deck-container footer, .deck-container header, .deck-container hgroup, .deck-container menu, .deck-container nav, .deck-container section, .deck-container summary, +.deck-container time, .deck-container mark, .deck-container audio, .deck-container video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +.deck-container article, .deck-container aside, .deck-container details, .deck-container figcaption, .deck-container figure, +.deck-container footer, .deck-container header, .deck-container hgroup, .deck-container menu, .deck-container nav, .deck-container section { + display: block; +} +.deck-container blockquote, .deck-container q { + quotes: none; +} +.deck-container blockquote:before, .deck-container blockquote:after, .deck-container q:before, .deck-container q:after { + content: ""; + content: none; +} +.deck-container ins { + background-color: #ff9; + color: #000; + text-decoration: none; +} +.deck-container mark { + background-color: #ff9; + color: #000; + font-style: italic; + font-weight: bold; +} +.deck-container del { + text-decoration: line-through; +} +.deck-container abbr[title], .deck-container dfn[title] { + border-bottom: 1px dotted; + cursor: help; +} +.deck-container table { + border-collapse: collapse; + border-spacing: 0; +} +.deck-container hr { + display: block; + height: 1px; + border: 0; + border-top: 1px solid #ccc; + margin: 1em 0; + padding: 0; +} +.deck-container input, .deck-container select { + vertical-align: middle; +} +.deck-container select, .deck-container input, .deck-container textarea, .deck-container button { + font: 99% sans-serif; +} +.deck-container pre, .deck-container code, .deck-container kbd, .deck-container samp { + font-family: monospace, sans-serif; +} +.deck-container a { + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); +} +.deck-container a:hover, .deck-container a:active { + outline: none; +} +.deck-container ul, .deck-container ol { + margin-left: 2em; + vertical-align: top; +} +.deck-container ol { + list-style-type: decimal; +} +.deck-container nav ul, .deck-container nav li { + margin: 0; + list-style: none; + list-style-image: none; +} +.deck-container small { + font-size: 85%; +} +.deck-container strong, .deck-container th { + font-weight: bold; +} +.deck-container td { + vertical-align: top; +} +.deck-container sub, .deck-container sup { + font-size: 75%; + line-height: 0; + position: relative; +} +.deck-container sup { + top: -0.5em; +} +.deck-container sub { + bottom: -0.25em; +} +.deck-container textarea { + overflow: auto; +} +.ie6 .deck-container legend, .ie7 .deck-container legend { + margin-left: -7px; +} +.deck-container input[type="radio"] { + vertical-align: text-bottom; +} +.deck-container input[type="checkbox"] { + vertical-align: bottom; +} +.ie7 .deck-container input[type="checkbox"] { + vertical-align: baseline; +} +.ie6 .deck-container input { + vertical-align: text-bottom; +} +.deck-container label, .deck-container input[type="button"], .deck-container input[type="submit"], .deck-container input[type="image"], .deck-container button { + cursor: pointer; +} +.deck-container button, .deck-container input, .deck-container select, .deck-container textarea { + margin: 0; +} +.deck-container input:invalid, .deck-container textarea:invalid { + border-radius: 1px; + -moz-box-shadow: 0px 0px 5px red; + -webkit-box-shadow: 0px 0px 5px red; + box-shadow: 0px 0px 5px red; +} +.deck-container input:invalid .no-boxshadow, .deck-container textarea:invalid .no-boxshadow { + background-color: #f0dddd; +} +.deck-container button { + width: auto; + overflow: visible; +} +.ie7 .deck-container img { + -ms-interpolation-mode: bicubic; +} +.deck-container, .deck-container select, .deck-container input, .deck-container textarea { + color: #444; +} +.deck-container a { + color: #607890; +} +.deck-container a:hover, .deck-container a:focus { + color: #036; +} +.deck-container a:link { + -webkit-tap-highlight-color: #fff; +} +.deck-container.deck-loading { + display: none; +} + +.slide { + width: auto; + min-height: 100%; + position: relative; +} +.slide h1 { + font-size: 4.5em; +} +.slide h1, .slide .vcenter { + font-weight: bold; + text-align: center; + padding-top: 1em; + max-height: 100%; +} +.csstransforms .slide h1, .csstransforms .slide .vcenter { + padding: 0 48px; + position: absolute; + left: 0; + right: 0; + top: 50%; + -webkit-transform: translate(0, -50%); + -moz-transform: translate(0, -50%); + -ms-transform: translate(0, -50%); + -o-transform: translate(0, -50%); + transform: translate(0, -50%); +} +.slide .vcenter h1 { + position: relative; + top: auto; + padding: 0; + -webkit-transform: none; + -moz-transform: none; + -ms-transform: none; + -o-transform: none; + transform: none; +} +.slide h2 { + font-size: 2.25em; + font-weight: bold; + padding-top: .5em; + margin: 0 0 .66666em 0; + border-bottom: 3px solid #888; +} +.slide h3 { + font-size: 1.4375em; + font-weight: bold; + margin-bottom: .30435em; +} +.slide h4 { + font-size: 1.25em; + font-weight: bold; + margin-bottom: .25em; +} +.slide h5 { + font-size: 1.125em; + font-weight: bold; + margin-bottom: .2222em; +} +.slide h6 { + font-size: 1em; + font-weight: bold; +} +.slide img, .slide iframe, .slide video { + display: block; + max-width: 100%; +} +.slide video, .slide iframe, .slide img { + display: block; + margin: 0 auto; +} +.slide p, .slide blockquote, .slide iframe, .slide img, .slide ul, .slide ol, .slide pre, .slide video { + margin-bottom: 1em; +} +.slide pre { + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; + padding: 1em; + border: 1px solid #888; +} +.slide em { + font-style: italic; +} +.slide li { + padding: .25em 0; + vertical-align: middle; +} + +.deck-before, .deck-previous, .deck-next, .deck-after { + position: absolute; + left: -999em; + top: -999em; +} + +.deck-current { + z-index: 2; +} + +.slide .slide { + visibility: hidden; + position: static; + min-height: 0; +} + +.deck-child-current { + position: static; + z-index: 2; +} +.deck-child-current .slide { + visibility: hidden; +} +.deck-child-current .deck-previous, .deck-child-current .deck-before, .deck-child-current .deck-current { + visibility: visible; +} + +@media screen and (max-device-width: 480px) { + /* html { -webkit-text-size-adjust:none; -ms-text-size-adjust:none; } */ +} +@media print { + * { + background: transparent !important; + color: black !important; + text-shadow: none !important; + filter: none !important; + -ms-filter: none !important; + -webkit-box-reflect: none !important; + -moz-box-reflect: none !important; + -webkit-box-shadow: none !important; + -moz-box-shadow: none !important; + box-shadow: none !important; + } + * :before, * :after { + display: none !important; + } + + a, a:visited { + color: #444 !important; + text-decoration: underline; + } + + a[href]:after { + content: " (" attr(href) ")"; + } + + abbr[title]:after { + content: " (" attr(title) ")"; + } + + .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { + content: ""; + } + + pre, blockquote { + border: 1px solid #999; + page-break-inside: avoid; + } + + thead { + display: table-header-group; + } + + tr, img { + page-break-inside: avoid; + } + + @page { + margin: 0.5cm; +} + + p, h2, h3 { + orphans: 3; + widows: 3; + } + + h2, h3 { + page-break-after: avoid; + } + + .slide { + position: static !important; + visibility: visible !important; + display: block !important; + -webkit-transform: none !important; + -moz-transform: none !important; + -o-transform: none !important; + -ms-transform: none !important; + transform: none !important; + opacity: 1 !important; + } + + h1, .vcenter { + -webkit-transform: none !important; + -moz-transform: none !important; + -o-transform: none !important; + -ms-transform: none !important; + transform: none !important; + padding: 0 !important; + position: static !important; + } + + .deck-container > .slide { + page-break-after: always; + } + + .deck-container { + width: 100% !important; + height: auto !important; + padding: 0 !important; + display: block !important; + } + + script { + display: none; + } +} diff --git a/eo/tutorial/Parallelization/css/deck.goto.css b/eo/tutorial/Parallelization/css/deck.goto.css new file mode 100644 index 000000000..108e4f9c4 --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.goto.css @@ -0,0 +1,41 @@ +.deck-container .goto-form { + position: absolute; + z-index: 3; + bottom: 10px; + left: 50%; + height: 1.75em; + margin: 0 0 0 -9.125em; + line-height: 1.75em; + padding: 0.625em; + display: none; + background: #ccc; + overflow: hidden; +} +.borderradius .deck-container .goto-form { + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border-radius: 10px; +} +.deck-container .goto-form label { + font-weight: bold; +} +.deck-container .goto-form label, .deck-container .goto-form input { + display: inline-block; + font-family: inherit; +} + +.deck-goto .goto-form { + display: block; +} + +#goto-slide { + width: 8.375em; + margin: 0 0.625em; + height: 1.4375em; +} + +@media print { + .goto-form, #goto-slide { + display: none !important; + } +} diff --git a/eo/tutorial/Parallelization/css/deck.hash.css b/eo/tutorial/Parallelization/css/deck.hash.css new file mode 100644 index 000000000..28f07326b --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.hash.css @@ -0,0 +1,13 @@ +.deck-container .deck-permalink { + display: none; + position: absolute; + z-index: 4; + bottom: 30px; + right: 0; + width: 48px; + text-align: center; +} + +.no-history .deck-container:hover .deck-permalink { + display: block; +} diff --git a/eo/tutorial/Parallelization/css/deck.menu.css b/eo/tutorial/Parallelization/css/deck.menu.css new file mode 100644 index 000000000..c664a3f8e --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.menu.css @@ -0,0 +1,47 @@ +.deck-menu .slide { + background: #eee; + position: relative; + left: 0; + top: 0; + visibility: visible; + cursor: pointer; +} +.no-csstransforms .deck-menu > .slide { + float: left; + width: 22%; + height: 22%; + min-height: 0; + margin: 1%; + font-size: 0.22em; + overflow: hidden; + padding: 0 0.5%; +} +.csstransforms .deck-menu > .slide { + -webkit-transform: scale(0.22) !important; + -moz-transform: scale(0.22) !important; + -o-transform: scale(0.22) !important; + -ms-transform: scale(0.22) !important; + transform: scale(0.22) !important; + -webkit-transform-origin: 0 0; + -moz-transform-origin: 0 0; + -o-transform-origin: 0 0; + -ms-transform-origin: 0 0; + transform-origin: 0 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 100%; + height: 100%; + overflow: hidden; + padding: 0 48px; + margin: 12px; +} +.deck-menu iframe, .deck-menu img, .deck-menu video { + max-width: 100%; +} +.deck-menu .deck-current, .no-touch .deck-menu .slide:hover { + background: #ddf; +} +.deck-menu.deck-container:hover .deck-prev-link, .deck-menu.deck-container:hover .deck-next-link { + display: none; +} diff --git a/eo/tutorial/Parallelization/css/deck.navigation.css b/eo/tutorial/Parallelization/css/deck.navigation.css new file mode 100644 index 000000000..e1ebad8b8 --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.navigation.css @@ -0,0 +1,43 @@ +.deck-container .deck-prev-link, .deck-container .deck-next-link { + display: none; + position: absolute; + z-index: 3; + top: 50%; + width: 32px; + height: 32px; + margin-top: -16px; + font-size: 20px; + font-weight: bold; + line-height: 32px; + vertical-align: middle; + text-align: center; + text-decoration: none; + color: #fff; + background: #888; +} +.borderradius .deck-container .deck-prev-link, .borderradius .deck-container .deck-next-link { + -webkit-border-radius: 16px; + -moz-border-radius: 16px; + border-radius: 16px; +} +.deck-container .deck-prev-link:hover, .deck-container .deck-prev-link:focus, .deck-container .deck-prev-link:active, .deck-container .deck-prev-link:visited, .deck-container .deck-next-link:hover, .deck-container .deck-next-link:focus, .deck-container .deck-next-link:active, .deck-container .deck-next-link:visited { + color: #fff; +} +.deck-container .deck-prev-link { + left: 8px; +} +.deck-container .deck-next-link { + right: 8px; +} +.deck-container:hover .deck-prev-link, .deck-container:hover .deck-next-link { + display: block; +} +.deck-container:hover .deck-prev-link.deck-nav-disabled, .touch .deck-container:hover .deck-prev-link, .deck-container:hover .deck-next-link.deck-nav-disabled, .touch .deck-container:hover .deck-next-link { + display: none; +} + +@media print { + .deck-prev-link, .deck-next-link { + display: none !important; + } +} diff --git a/eo/tutorial/Parallelization/css/deck.scale.css b/eo/tutorial/Parallelization/css/deck.scale.css new file mode 100644 index 000000000..d6a4eb0be --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.scale.css @@ -0,0 +1,28 @@ +/* Remove this line if you are embedding deck.js in a page and +using the scale extension. */ +.csstransforms { + overflow: hidden; +} + +.csstransforms .deck-container.deck-scale:not(.deck-menu) > .slide { + -webkit-box-sizing: padding-box; + -moz-box-sizing: padding-box; + box-sizing: padding-box; + width: 100%; + padding-bottom: 20px; +} +.csstransforms .deck-container.deck-scale:not(.deck-menu) > .slide > .deck-slide-scaler { + -webkit-transform-origin: 50% 0; + -moz-transform-origin: 50% 0; + -o-transform-origin: 50% 0; + -ms-transform-origin: 50% 0; + transform-origin: 50% 0; +} + +.csstransforms .deck-container.deck-menu .deck-slide-scaler { + -webkit-transform: none !important; + -moz-transform: none !important; + -o-transform: none !important; + -ms-transform: none !important; + transform: none !important; +} diff --git a/eo/tutorial/Parallelization/css/deck.status.css b/eo/tutorial/Parallelization/css/deck.status.css new file mode 100644 index 000000000..17d55ad0d --- /dev/null +++ b/eo/tutorial/Parallelization/css/deck.status.css @@ -0,0 +1,18 @@ +.deck-container .deck-status { + position: absolute; + bottom: 10px; + right: 5px; + color: #888; + z-index: 3; + margin: 0; +} + +body.deck-container .deck-status { + position: fixed; +} + +@media print { + .deck-status { + display: none; + } +} diff --git a/eo/tutorial/Parallelization/css/eompi.css b/eo/tutorial/Parallelization/css/eompi.css new file mode 100644 index 000000000..d089362ce --- /dev/null +++ b/eo/tutorial/Parallelization/css/eompi.css @@ -0,0 +1,9 @@ +.changed +{ + color: green; +} + +.specific +{ + color: red; +} diff --git a/eo/tutorial/Parallelization/css/horizontal-slide.css b/eo/tutorial/Parallelization/css/horizontal-slide.css new file mode 100644 index 000000000..4a4c6adf6 --- /dev/null +++ b/eo/tutorial/Parallelization/css/horizontal-slide.css @@ -0,0 +1,76 @@ +.csstransitions.csstransforms { + overflow-x: hidden; +} +.csstransitions.csstransforms .deck-container > .slide { + -webkit-transition: -webkit-transform 500ms ease-in-out; + -moz-transition: -moz-transform 500ms ease-in-out; + -ms-transition: -ms-transform 500ms ease-in-out; + -o-transition: -o-transform 500ms ease-in-out; + transition: transform 500ms ease-in-out; +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide { + position: absolute; + top: 0; + left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 100%; + padding: 0 48px; +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .slide { + position: relative; + left: 0; + top: 0; + -webkit-transition: -webkit-transform 500ms ease-in-out, opacity 500ms ease-in-out; + -moz-transition: -moz-transform 500ms ease-in-out, opacity 500ms ease-in-out; + -ms-transition: -ms-transform 500ms ease-in-out, opacity 500ms ease-in-out; + -o-transition: -o-transform 500ms ease-in-out, opacity 500ms ease-in-out; + transition: -webkit-transform 500ms ease-in-out, opacity 500ms ease-in-out; +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .deck-next, .csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .deck-after { + visibility: visible; + -webkit-transform: translate3d(200%, 0, 0); + -moz-transform: translate(200%, 0); + -ms-transform: translate(200%, 0); + -o-transform: translate(200%, 0); + transform: translate3d(200%, 0, 0); +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-previous { + -webkit-transform: translate3d(-200%, 0, 0); + -moz-transform: translate(-200%, 0); + -ms-transform: translate(-200%, 0); + -o-transform: translate(-200%, 0); + transform: translate3d(-200%, 0, 0); +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-before { + -webkit-transform: translate3d(-400%, 0, 0); + -moz-transform: translate(-400%, 0); + -ms-transform: translate(-400%, 0); + -o-transform: translate(-400%, 0); + transform: translate3d(-400%, 0, 0); +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-next { + -webkit-transform: translate3d(200%, 0, 0); + -moz-transform: translate(200%, 0); + -ms-transform: translate(200%, 0); + -o-transform: translate(200%, 0); + transform: translate3d(200%, 0, 0); +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-after { + -webkit-transform: translate3d(400%, 0, 0); + -moz-transform: translate(400%, 0); + -ms-transform: translate(400%, 0); + -o-transform: translate(400%, 0); + transform: translate3d(400%, 0, 0); +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-before .slide, .csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-previous .slide { + visibility: visible; +} +.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-child-current { + -webkit-transform: none; + -moz-transform: none; + -ms-transform: none; + -o-transform: none; + transform: none; +} diff --git a/eo/tutorial/Parallelization/css/shjs.css b/eo/tutorial/Parallelization/css/shjs.css new file mode 100644 index 000000000..ec9d4088b --- /dev/null +++ b/eo/tutorial/Parallelization/css/shjs.css @@ -0,0 +1,67 @@ +pre.sh_sourceCode { + background-color: white; + color: black; + font-style: normal; + font-weight: normal; +} + +pre.sh_sourceCode .sh_keyword { color: blue; font-weight: bold; } /* language keywords */ +pre.sh_sourceCode .sh_type { color: darkgreen; } /* basic types */ +pre.sh_sourceCode .sh_usertype { color: teal; } /* user defined types */ +pre.sh_sourceCode .sh_string { color: red; font-family: monospace; } /* strings and chars */ +pre.sh_sourceCode .sh_regexp { color: orange; font-family: monospace; } /* regular expressions */ +pre.sh_sourceCode .sh_specialchar { color: pink; font-family: monospace; } /* e.g., \n, \t, \\ */ +pre.sh_sourceCode .sh_comment { color: brown; font-style: italic; } /* comments */ +pre.sh_sourceCode .sh_number { color: purple; } /* literal numbers */ +pre.sh_sourceCode .sh_preproc { color: darkblue; font-weight: bold; } /* e.g., #include, import */ +pre.sh_sourceCode .sh_symbol { color: darkred; } /* e.g., <, >, + */ +pre.sh_sourceCode .sh_function { color: black; font-weight: bold; } /* function calls and declarations */ +pre.sh_sourceCode .sh_cbracket { color: red; } /* block brackets (e.g., {, }) */ +pre.sh_sourceCode .sh_todo { font-weight: bold; background-color: cyan; } /* TODO and FIXME */ + +/* Predefined variables and functions (for instance glsl) */ +pre.sh_sourceCode .sh_predef_var { color: darkblue; } +pre.sh_sourceCode .sh_predef_func { color: darkblue; font-weight: bold; } + +/* for OOP */ +pre.sh_sourceCode .sh_classname { color: teal; } + +/* line numbers (not yet implemented) */ +pre.sh_sourceCode .sh_linenum { color: black; font-family: monospace; } + +/* Internet related */ +pre.sh_sourceCode .sh_url { color: blue; text-decoration: underline; font-family: monospace; } + +/* for ChangeLog and Log files */ +pre.sh_sourceCode .sh_date { color: blue; font-weight: bold; } +pre.sh_sourceCode .sh_time, pre.sh_sourceCode .sh_file { color: darkblue; font-weight: bold; } +pre.sh_sourceCode .sh_ip, pre.sh_sourceCode .sh_name { color: darkgreen; } + +/* for Prolog, Perl... */ +pre.sh_sourceCode .sh_variable { color: darkgreen; } + +/* for LaTeX */ +pre.sh_sourceCode .sh_italics { color: darkgreen; font-style: italic; } +pre.sh_sourceCode .sh_bold { color: darkgreen; font-weight: bold; } +pre.sh_sourceCode .sh_underline { color: darkgreen; text-decoration: underline; } +pre.sh_sourceCode .sh_fixed { color: green; font-family: monospace; } +pre.sh_sourceCode .sh_argument { color: darkgreen; } +pre.sh_sourceCode .sh_optionalargument { color: purple; } +pre.sh_sourceCode .sh_math { color: orange; } +pre.sh_sourceCode .sh_bibtex { color: blue; } + +/* for diffs */ +pre.sh_sourceCode .sh_oldfile { color: orange; } +pre.sh_sourceCode .sh_newfile { color: darkgreen; } +pre.sh_sourceCode .sh_difflines { color: blue; } + +/* for css */ +pre.sh_sourceCode .sh_selector { color: purple; } +pre.sh_sourceCode .sh_property { color: blue; } +pre.sh_sourceCode .sh_value { color: darkgreen; font-style: italic; } + +/* other */ +pre.sh_sourceCode .sh_section { color: black; font-weight: bold; } +pre.sh_sourceCode .sh_paren { color: red; } +pre.sh_sourceCode .sh_attribute { color: darkgreen; } + diff --git a/eo/tutorial/Parallelization/css/thales.css b/eo/tutorial/Parallelization/css/thales.css new file mode 100644 index 000000000..e30282966 --- /dev/null +++ b/eo/tutorial/Parallelization/css/thales.css @@ -0,0 +1,91 @@ +.deck-container em { + color:rgb(255,115,0); +} + +.deck-container s { + color:rgb(180,180,211); +} + +.deck-container { + font-family: "Helvetica Neue", sans-serif; + font-size: 1.75em; + color:RGB(50,50,101); + background:white url("./img/thales.jpg") no-repeat fixed bottom left; +} +.deck-container .slide { +} +.deck-container .slide h1 { + color:rgb(50,50,101); +} +.deck-container .slide h2 { + color:rgb(255,115,0); + border-bottom-color:lightgray; +} +.deck-container .slide h3 { + color:RGB(57,138,199); +} +.deck-container .slide pre { + border-color: #ccc; +} +.deck-container .slide blockquote { + font-size: 2em; + font-style: italic; + padding: 1em 2em; + color: #000; + border-left: 5px solid #ccc; + font-family:serif; +} +.deck-container .slide blockquote p { + margin: 0; +} +.deck-container .slide blockquote cite { + font-size: .5em; + font-style: normal; + font-weight: bold; + color: #888; +} +.deck-container .slide ::-moz-selection { + background: #c00; + color: #fff; +} +.deck-container .slide ::selection { + background: #c00; + color: #fff; +} +.deck-container .slide a, .deck-container .slide a:hover, .deck-container .slide a:focus, .deck-container .slide a:active, .deck-container .slide a:visited { + color:RGB(152,191,12); + text-decoration: none; +} +.deck-container .slide a:hover, .deck-container .slide a:focus { + text-decoration: underline; +} +.deck-container > .slide .deck-before, .deck-container > .slide .deck-previous { + opacity: 0.4; +} +.deck-container > .slide .deck-before:not(.deck-child-current) .deck-before, .deck-container > .slide .deck-before:not(.deck-child-current) .deck-previous, .deck-container > .slide .deck-previous:not(.deck-child-current) .deck-before, .deck-container > .slide .deck-previous:not(.deck-child-current) .deck-previous { + opacity: 1; +} +.deck-container > .slide .deck-child-current { + opacity: 1; +} +.deck-container .deck-prev-link, .deck-container .deck-next-link { + background: #ccc; + font-family: serif; +} +.deck-container .deck-prev-link, .deck-container .deck-prev-link:hover, .deck-container .deck-prev-link:focus, .deck-container .deck-prev-link:active, .deck-container .deck-prev-link:visited, .deck-container .deck-next-link, .deck-container .deck-next-link:hover, .deck-container .deck-next-link:focus, .deck-container .deck-next-link:active, .deck-container .deck-next-link:visited { + color: #fff; +} +.deck-container .deck-prev-link:hover, .deck-container .deck-prev-link:focus, .deck-container .deck-next-link:hover, .deck-container .deck-next-link:focus { + background: #c00; + text-decoration: none; +} +.deck-container .deck-status { + font-size: 0.6666em; +} +.deck-container.deck-menu .slide { + background: #eee; +} +.deck-container.deck-menu .deck-current, .no-touch .deck-container.deck-menu .slide:hover { + background: #ddf; +} + diff --git a/eo/tutorial/Parallelization/eompi.html b/eo/tutorial/Parallelization/eompi.html new file mode 100644 index 000000000..82533a796 --- /dev/null +++ b/eo/tutorial/Parallelization/eompi.html @@ -0,0 +1,903 @@ + + + + + + + + + + EO::MPI parallelization + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    EO's Parallelization with MPI

    +
    + +
    +

    What is parallelization?

    +
      +
    • Divide and Conquer paradigm

      +

      A difficult problem can be splitted into simpler sub problems.

      +

      Therefore the sub problems should be solved faster.

      +
    • +
    • Parallelize.

      +

      Process serveral tasks together (concurrent programming).

      +

      By different ways : +

        +
      • Shared memory : Multitask, OpenMP, etc.
      • +
      • Message Passing Interface : MPI.
      • +
      • Other ways, undetailed here: coroutines, multi-thread / LightWeightProcess, + Field Programmable Gate Array (FPGA), General Purpose GPU (GPGPU), etc.
      • +
      +

      +
    • +
    +
    + +
    +

    Shared memory (e.g : OpenMP)

    +
      +
    • Multicore : more than one core per processor. +
        +
      • Processes several instruction streams together, each one manipulating different datas.
      • +
      • Different from superscalar processors, which can process more than one instruction during a + single processor cycle.
      • +
      • A multicore processor can however be superscalar.
      • +
      • For instance : IBM's Cell microprocessor (PlayStation3)
      • +
      +
    • + +
    • Symmetric multiprocessing : More than one processor which communicate through + a specific bus. +
        +
      • Bus contention is the principal limitating factor.
      • +
      +
    • + +
    • The main drawback is explicitly contained in the name. +
        +
      • Memory is shared
      • +
      • Bus contention?
      • +
      • Low memory?
      • +
      • Use of virtual memory (swap) and page faults?
      • +
      • => Can slow the speedup compared with the number of processors.
      • +
      +
    • +
    +
    + +
    +

    Message Passing Interface (e.g : OpenMPI)

    +

    Memory isn't shared here, manipulated objects are sent on a network: there is communication between the machines + (called hosts)

    +
      +
    • Cluster +
        +
      • Several machines network connected (for instance, in an Ethernet network).
      • +
      • Can have different specifications, but this can affect load balancing.
      • +
      • Most of the supercomputers are clusters.
      • +
      • For exemple : Beowulf Cluster, Sun Grid Engine...
      • +
      +
    • + +
    • Massive parallel processing +
        +
      • This is not machines but processors which are directly connected by network.
      • +
      • Like a cluster, but the networks are specific, so as to wire more processors.
      • +
      +
    • + +
    • Grid (a.k.a Distributed Computing) +
        +
      • Networks with potentially high latence and low bandwith, like Internet.
      • +
      • Example of programs : BOINC, Seti@home...
      • +
      +
    • +
    +
    + +
    +

    Parallelization myths

    +
    + +
    +

    A myth about speed: the car's enigma

    +
      +
    • If a car has to travel 100 Km, but has yet traveled 60 Km in 1 hour (i.e it has an average + speed of 60 Km per hour), what is its maximal average speed on the whole traject + ?
    • + +

      +
    • Some hints: +
        +
      • The driver can use all the hilarious gas (N2O, nitrous oxyde, a.k.a nitro) he + needs.
      • +
      • Let's suppose even that the car can travel at speed of light, or teleport (despite general theory of + relativity).
      • +
      +
    • + +
    • The solution: 100 Km/h
    • +
    • The explanation: let's suppose that the car teleports after the first 60 Km. It would have + traveled 60 Km in 1 hour and 40 Km in 0 seconds, which is 100 Km in 1 hour: 100 Km/h.
    • +
    +
    + +
    +

    A myth about speed: "Il dit qu'il voit pas le rapport ?"

    +

    +
      +
    • Let P be the parallelizable proportion of the program (~ the remaining distance to travel), which can be + processed by N machines.
    • +
    • Then 1 - P is the sequential (non parallelizable) proportion of the program (~ the already traveled distance), which + can be processed by 1 machine.
    • +
    • A sequential version would take 1 - P + P = 1 unit (of time) to terminate.
    • +
    • A parallel version would take (1-P) + P / N units to terminate.
    • +
    • The speedup (gain of speed) would then be: + + which tends to 1-P as N tends to infinity.
    • +
    • The maximal theoritical speedup (~ maximal average speed) would then be 1 / (1-P)
    • +
    • This result is known as Amdahl's law

    • +
    +
    + +
    +

    A myth about data : the cat's enigma

    +
      +
    • +

      If 3 cats catch 3 mices in 3 minutes, how many cats are needed to catch 9 mices in 9 + minutes ? + +

      +
    • +
    • The solution: 3 too !
    • +
    • A better question to ask would be: how many mices can catch 9 cats in 3 minutes ?
    • +
    +
    + +
    +

    A myth about data

    +
      +
    • The idea is no more to make a processing faster (for a constant amount of data) but to process more data (in + the same time).
    • +
    • In this case, the most hosts we add, the most data we can process at a time.
    • +
    • This doesn't contradict Amdahl's Law, which makes the assumption that the amount of data to process stays + the same.
    • +
    • There is also another way to calculate speedup here: + + where P is the number of processes, alpha the non parallelizable part of the program. +
    • +
    • This result is known as the Gustafson's Law

    • +
    +
    + +
    +

    A metric: speedup

    +
      +
    • Speedup refers to how much a parallel algorithm is faster than a corresponding sequential algorithm
    • +
    • It's a quantitative mesure, relative to the sequential version : + + where T1 is the time taken by the sequential version and Tp the time taken by the parallel version with p + processes. +
    • +
    • A speedup equal to one indicates that the version is as performant as the sequential version.
    • +
    • Practically, speedup may not be linear in number of processes (Amdahl's Law)
    • +
    +
    + +
    +

    Parallelization in EO

    +
    + +
    +

    Objectives

    +
      +
    • Remember, tasks have to be independant from one to another.
    • +
    • Process data faster: what takes time in EO? +
        +
      • Evaluation!
      • +
      +
    • +
    • Process more data during the same time: where? +
        +
      • Multi-start!
      • +
      +
    • +
    • Other objectives : +
        +
      • Readily serialize EO objects.
      • +
      • Be able to easily implement other parallel algorithms.
      • +
      +
    • +
    +
    + +
    +

    Evaluation: Long story short

    +
    
    +    int main( int argc, char **argv )
    +    {
    +        eo::mpi::Node::init( argc, argv );
    +        // PUT EO STUFF HERE
    +        // Let's make the assumption that pop is a eoPop<EOT>
    +        // and evalFunc is an evaluation functor
    +        eo::mpi::DynamicAssignmentAlgorithm assign;
    +        eoParallelPopLoopEval<EOT> popEval( assign, eo::mpi::DEFAULT_MASTER, evalFunc );
    +        popEval( pop, pop );
    +    }
    +    
    +
    + +
    +

    Serializing EO objects

    +
      +
    • Serializing is writing a message from a binary source into a message transmissible data.
    • +
    • Several formats can be used +
        +
      • Binary directly - but all the hosts have to be the same!
      • +
      • Text based formats: XML, YAML, JSON,...
      • +
      +
    • +
    • So why use text? +
        +
      • It's human readable, more or less easily parsable.
      • +
      • It's independant from the data type representations on the machines (e.g: an int on a 32 bits and on + a 64 bits machines are not the same).
      • +
      • Main drawbacks: it takes more space and it needs a processing for encoding and decoding.
      • +
      +
    • +
    +
    + +
    +

    eoserial : principle

    + +
      +
    • JSON serialization +
        +
      • Lighter than XML.
      • +
      • Easily parsable, the grammar is trivial.
      • +
      • Allows to represent tables, objects and texts: it's sufficient!
      • +
      +
    • +
    • What happens in your life when you're serializable? +
    • +
    • Implement interface eoserial::Persistent and your object can be saved and loaded, in JSON format.
    • +
    • No need to serialize the whole object, you choose what you need to save and load.
    • +
    • Everything can be serialized!
        +
      • Atomic types are directly serialized into eoserial::String (thanks to std::stringstream)
      • +
      • Arrays are serializable (into eoserial::Array), if what they contain is too.
      • +
      • Object can be serializable (into eoserial::Object), if what they contain is too.
      • +
    • +
    +
    + +
    +

    eoserial : interface eoserial::Persistent

    +
    +    
    +    # include <serial/eoSerial.h>
    +
    +    class MyObject : public eoserial::Persistent {
    +        public:
    +
    +        // A persistent class needs a default empty ctor.
    +        MyObject() {}
    +
    +        int id;
    +
    +        // Implementation of eoserial::Persistent::pack
    +        // What to save when making a serialized object?
    +        eoserial::Object* pack() const
    +        {
    +            eoserial::Object* obj = new eoserial::Object;
    +            // eoserial::make creates a eoserial::String from a basic type
    +            eoserial::String* idAsString = eoserial::make( id );
    +            // the key "saved_id" will be associated to the JSON object idAsString
    +            obj->add( "saved_id", idAsString );
    +            // could have be done with
    +            // (*obj)["saved_id"] = idAsString;
    +            // as obj is a std::map pointer
    +            return obj;
    +        }
    +
    +        // Implementation of eoserial::Persistent::unpack
    +        // What data to retrieve from a JSON object and where to put it?
    +        void unpack(const eoserial::Object* json)
    +        {
    +            // retrieves the value from key "saved_id" in "*json" object and put it into member "id"
    +            eoserial::unpack( *json, "saved_id" , id );
    +        }
    +    };
    +    
    +    
    +
    + +
    +

    eoserial : use it

    +
    +    
    +# include <eoSerial.h>
    +# include <fstream>
    +# include <cassert>
    +
    +    int main(void)
    +    {
    +        MyObject instance;
    +        instance.id = 42;
    +
    +        // Writes
    +        eoserial::Object* obj = instance.pack();
    +        std::ofstream ofile("filename");
    +        obj->print( ofile );
    +        ofile.close();
    +        delete obj;
    +
    +        // Reads
    +        std::ifstream ifile("filename");
    +        std::stringstream ss;
    +        while( ifile )
    +        {
    +            std::string s;
    +            ifile >> s;
    +            ss << s;
    +        }
    +        eoserial::Object* objCopy = eoserial::Parser::parse( ss.str() );
    +        MyObject instanceCopy;
    +        instanceCopy.unpack( objCopy );
    +
    +        assert( instanceCopy.id == instance.id );
    +
    +        return 0;
    +    }
    +    
    +    
    +
    + +
    +

    eoserial : more complex uses

    +
    
    +    struct ComplexObject
    +    {
    +        bool someBooleanValue; // will be serialized into a string
    +        MyObject obj; // Objects can contain other objects too
    +        std::vector<int>; // and tables too!
    +    };
    +
    +    int main(void)
    +    {
    +        ComplexObject co;
    +        // let's imagine we've set values of co.
    +        eoserial::Object* json = new eoserial::Object;
    +        // serialize basic type
    +        (*json)["some_boolean_value"] = eoserial::make( co.someBooleanValue );
    +        // MyObject is Persistent, so eoserial knows how to serialize it
    +        json->add( "my_object", &co.obj );
    +        // Instead of having a "for" loop, let's automatically serialize the content of the array
    +        json->add( "int_array",
    +            eoserial::makeArray< std::vector<int>, eoserial::MakeAlgorithm >( co.array ) );
    +        // Print everything on the standard output
    +        json->print( std::cout );
    +        delete json;
    +        return 0;
    +    }
    +    
    +
    + +
    +

    MPI

    +
      +
    • We know how to serialize our objects. Now, we need to transmit them over the network.
    • +
    • Message Passing Interface (MPI) is a norm.
    • +
    • OpenMPI implements it, in C, in the SPMD (Single Program Multiple Data) fashion. It is an active community + and the library is very well documented.
    • +
    • Boost::mpi gives it a C++ flavour (and tests each status code returned by MPI calls, throwing up exceptions + instead).
    • +
    • MPI helps by: +
        +
      • Managing the administration of roles: each MPI process has a rank and knows the whole + size of the cluster.
      • +
      • Regrouping outputs of different processes into one single output.
      • +
      • Managing the routing of messages and connections between the processes.
      • +
      • Launch a given number of processes via SSH, or a cluster engine (like SGE).
      • +
      +
    • +
    • MPI doesn't deal with: +
        +
      • Debugging: if one of your program segfaults, buy a parallel debugger or... Good luck!
      • +
      • More generally, knowing what happens: even the standard output becomes a shared resource without any + protection!
      • +
      +
    • +
    +
    + +
    +

    Design of parallel algorithms

    +
    + +
    +

    Some vocabulary

    +
      +
    • In the most of cases, we want the results to be retrieved in one place. Besides, communication in MPI is + synchronous (it's a design choice making things are simpler).
    • +
    • One process will have particular responsabilities, like aggregating results: it's the master.
    • +
    • Other processes will be used to do the processing (it's the goal, after all?) : they're the + workers. Or slaves, but it may be patronizing and the master is rarely called + the patron.
    • +
    • As there is one master, the algorithm is said to be centralized. Some well-known parallel algorithms + use this paradigm: Google's MapReduce, Apache's Hadoop(free implementation of Google's one :-)),...
    • +
    • A job is the parallel algorithm seen in its globality (i.e., as a function).
    • +
    • A job is a set of tasks, which are the atomic, decomposed part which can be serialized and + processed by a worker, at a time.
    • +
    +
    + +
    +

    Evaluation (1/2)

    +

    + Let's see how we could implement our parallelized evaluation
    + It's feasible as evaluating an individual is independant from evaluating another one.
    +

    
    +        // On master side
    +        function parallel_evaluate( population p )
    +            foreach individual i in p,
    +                send i to a worker
    +                if there is no available worker,
    +                    wait for any response (return)
    +                    and retry
    +                endif
    +            endforeach
    +            inform all the available workers that they are done (yes, it's a centralized algorithm)
    +            wait for all remaining responses
    +        endfunction
    +
    +        when receiving a response:
    +            replace the evaluated individual in the population
    +
    +        // On worker side
    +        function parallel_evaluate( evaluation function f )
    +            wait for a individual i
    +            apply f on it
    +            send i to the master
    +        endfunction
    +        
    +

    +
    + +
    +

    Evaluation (2/2)

    +

    But a parallelization algorithm is interesting only if the process time is higher than the + communication time. If process time is too short relatively to the communication time, we can do the following: +

    
    +        // On master side
    +        function parallel_evaluate( population p, number of elements to send each time packet_size )
    +            index = 0
    +            while index < size
    +                sentSize := how many individuals (<= packet_size) can we send to a worker?
    +                find a worker. If there is no one, wait for any response (return) and retry
    +                send the sentSize to the worker
    +                send the individuals to the worker
    +                index += sentSize
    +            endwhile
    +            inform all the available workers that they're done
    +            wait for all remaining responses
    +        endfunction
    +
    +        when receiving a response:
    +            replace the evaluated individuals in the population
    +
    +        // On worker side
    +        function parallel_evaluate( evaluation function f )
    +        size := wait for a sentSize as described above
    +            individuals := wait for size individuals
    +            apply f on each of them
    +            send back the individuals
    +        endfunction
    +        
    +
    + +
    +

    Multi start

    +

    The idea behing multi-start is to run many times the same algorithm (for instance, eoEasyEA), but with different + seeds: the workers launch the algorithm and send their solutions as they come to the master, which saves the + ultimate best solution.

    +
    +        // On master side
    +        variable best_score (initialized at the worst value ever) // score can be fitness, for instance
    +
    +        function parallel_multistart( integer runs )
    +            seeds = table of generated seeds, or fixed seeds, whose size is at least "runs"
    +            for i := 0; i < runs; ++i
    +                find a worker. If there is no one, wait for any response (return) and retry
    +                send to the worker a different seed
    +            endfor
    +            inform all the available workers that they're done
    +            wait for all remaining responses
    +        endfunction
    +
    +        when receiving a response:
    +            received_score := receive score from the worker.
    +            If the received_score > best_score
    +                send worker a message indicating that master is interested by the solution
    +                receive the solution
    +                updates the best_score
    +            else
    +                send worker a message indicating that master isn't interested by the solution
    +            endif
    +
    +        // On worker side
    +        function parallel_multistart( algorithm eoAlgo )
    +            seed := wait for a seed
    +            solution := eoAlgo( seed )
    +            send solution score to master
    +            master_is_interested := wait for the response
    +            if master_is_interested
    +                send solution to master
    +            endif
    +        endfunction
    +    
    +
    + +
    +

    Common parts vs specific parts

    +
      +
    • These two algorithms have common parts and specific parts.
    • +
    • Identifying them allows to design generic parallel algorithms.
    • +
    • In the following code sample, specific parts are in red. Everything else is hence generic.
    • +
    + +
    
    +        // On master side
    +        function parallel_evaluate(population p, number of elements to send each time packet_size )
    +            index = 0
    +            while index < size
    +                find a worker. If there is no one, wait for any response (return) and retry
    +                sentSize := how many individuals (<= packet_size) can we send to a worker?
    +                send the sentSize to the worker
    +                send the individuals to the worker
    +                index += sentSize
    +            endwhile
    +            inform all the available workers that they're done
    +            wait for all remaining responses
    +        endfunction
    +
    +        when receiving a response:
    +            replace the evaluated individuals in the population
    +
    +        // On worker side
    +        function parallel_evaluate( evaluation function f )
    +        size := wait for a sentSize as described above
    +            individuals := wait for size individuals
    +            apply f on each of them
    +            send back the individuals
    +        endfunction
    +        
    + +
    + +
    +

    Common parts

    +
      +
    • Master runs a loop.
    • +
    • Master has to manage workers (find them, wait for them, etc...)
    • +
    • Workers need to be informed if they have something to do or not (stop condition in master part)
    • +
    • Master needs to wait to get all the responses.
    • +
    +
    + +
    +

    Specific parts

    +
      +
    • Loop condition in the master's part.
    • +
    • What has to be sent to a worker by master?
    • +
    • What has to be done by a worker when it receives an order?
    • +
    • What has to be done when the master receives a response?
    • +
    +
    + +
    +

    Generic parallel algorithm

    +

    The calls to specific parts are in red.

    +
    
    +    // Master side
    +    function parallel_algorithm()
    +        while ! isFinished()
    +            worker := none
    +            while worker is none
    +                wait for a response and affect worker the origin of the response
    +                handleResponse( worker )
    +                worker = retrieve worker
    +            endwhile
    +            send worker a work order
    +            sendTask( worker )
    +        endwhile
    +
    +        foreach available worker
    +            indicate worker it's done (send them a termination order)
    +        endforeach
    +
    +        while all responses haven't be received
    +            worker := none
    +            wait for a response and affect worker the origin of the response
    +            handleResponse( worker )
    +            send worker a termination order
    +        endwhile
    +    endfunction
    +
    +    // Worker side
    +    function parallel_algorithm()
    +        order := receive order
    +        while order is not termination order
    +            processTask( )
    +            order = receive order
    +        endwhile
    +    endfunction
    +    
    +
    + +
    +

    TLDR;

    + +
    + +
    +

    Functors

    +
      +
    • Using functors allows them to wrap and be wrapped (decorator pattern).
    • +
    • IsFinished : implements bool operator()(), indicating that the job is over.
    • +
    • SendTask : implements void operator()( int worker_rank ), indicating what to send to the + worker.
    • +
    • ProcessTask : implements void operator()(), indicating what the worker has to do when it receives a + task.
    • +
    • HandleResponse : implements void operator()( int worker_rank ), indicating what to do when + receiving a worker response.
    • +
    • Implementing these 4 functors is sufficient for a parallel algorithm!
    • +
    • You can also wrap the existing one to add functionalities.
    • +
    +
    + +
    +

    Stores

    +
      +
    • These 4 functors can use about the same data.
    • +
    • This data needs to be shared : all the functors are templated on a JobData structure.
    • +
    • A job needs data and functors to be launched.
    • +
    • Several jobs can use the same data and functors.
    • +
    • => Data and functors are saved into a store, which can be reused between different jobs.
    • +
    +
    + +
    +

    Scheduling tasks between workers

    +
      +
    • Until here, we don't know how to schedule tasks between workers.
    • +
    • Naive, simple solution: as soon as a worker has finished a task, give it a new task. Workers are put in a + queue, this is the dynamic assignment (scheduling).
    • +
    • If the worker's number of call is well-known, initially give to each worker a fixed amount of tasks. When a + worker has finished a task, give it another task only if it the amount of remaining tasks is positive ; else, + wait for another worker. Workers are managed with a fixed table, this is the static + assignment.
    • +
    +
    + +
    +

    Let's go back to evaluation in EO

    +
      +
    • The idea behind applying a functor to each element of a table is very generic. Google, Python and Javascript + call it map, we call it ParallelApply, according to existing + apply function, in apply.h.
    • +
    • There is also a ParallelApplyJob, a ParallelApplyStore which contains a + ParallelApplyData, a IsFinishedParallelApply, etc...
    • +
    • This is what is used when calling parallel evaluation.
    • +
    +
    + +
    +

    Customizing evaluation: reminder

    +
    
    +    int main( int argc, char **argv )
    +    {
    +        eo::mpi::Node::init( argc, argv );
    +        // PUT EO STUFF HERE
    +        // Let's make the assumption that pop is a eoPop<EOT>
    +        // and evalFunc is an evaluation functor
    +        eo::mpi::DynamicAssignmentAlgorithm assign;
    +        eoParallelPopLoopEval<EOT> popEval( assign, eo::mpi::DEFAULT_MASTER, evalFunc );
    +        // The store is hidden behind this call, but it can be given at eoParallelPopLoopEval constructor!
    +        popEval( pop, pop );
    +    }
    +    
    +
    + +
    +

    Customizing evaluation: the idea

    +
      +
    • We would like to retrieve best individuals, as soon as they're processed, and print their fitness in the + standard output, for instance.
    • +
    • We can wrap one of the 4 functors.
    • +
    • Master side or worker side? +
        +
      • Master side: we want to retrieve the global best individual, not the best individual in + population slices.
      • +
      • We have 3 choices: IsFinished, HandleResponse, SendTask.
      • +
      • So which one? +
          +
        • The functor HandleResponse should be reimplemented: in a sequential version, it would be done just + after the evaluation of an individual. The HandleResponse is the nearest functor called after having + received the result.
        • +
        +
      • +
      +
    • +
    • How to do it? +
        +
      1. Retrieve which slice has been processed by the worker.
      2. +
      3. Call the embedded HandleResponse.
      4. +
      5. Compare the fitnesses of individuals in the slice to the global best individual.
      6. +
      +
    • +
    +
    + +
    +

    Customizing evaluation: implementation!

    +
    
    +    // Our objective is to minimize fitness, for instance
    +    struct CatBestAnswers : public eo::mpi::HandleResponseParallelApply<EOT>
    +    {
    +        CatBestAnswers()
    +        {
    +            best.fitness( 1000000000. );
    +        }
    +
    +        void operator()(int wrkRank)
    +        {
    +            // Retrieve informations about the slice processed by the worker
    +            int index = _data->assignedTasks[wrkRank].index;
    +            int size = _data->assignedTasks[wrkRank].size;
    +            // call to the wrapped function HERE
    +            (*_wrapped)( wrkRank );
    +            // Compare fitnesses of evaluated individuals with the best saved
    +            for(int i = index; i < index+size; ++i)
    +            {
    +                if( best.fitness() < _data->table()[ i ].fitness() )
    +                {
    +                    eo::log << eo::quiet << "Better solution found:" << _data->table()[i].fitness() << std::endl;
    +                    best = _data->table()[ i ];
    +                }
    +            }
    +        }
    +
    +        protected:
    +
    +        EOT best;
    +    };
    +    
    +
    + +
    +

    Using customized handler

    +
    
    +        int main( int argc, char **argv )
    +        {
    +            eo::mpi::Node::init( argc, argv );
    +            // PUT EO STUFF HERE
    +            // Let's make the assumption that pop is a eoPop<EOT>
    +            // and evalFunc is an evaluation functor
    +            eo::mpi::DynamicAssignmentAlgorithm assign;
    +            // What was used before
    +            // eoParallelPopLoopEval<EOT> popEval( assign, eo::mpi::DEFAULT_MASTER, evalFunc );
    +            // What's new
    +            eo::mpi::ParallelApplyStore< EOT > store( evalFunc, eo::mpi::DEFAULT_MASTER );
    +            CatBestAnswer catBestAnswers;
    +            store.wrapHandleResponse( &catBestAnswers );
    +
    +            eoParallelPopLoopEval< EOT > popEval( assign, eo::mpi::DEFAULT_MASTER, &store );
    +            // What doesn't change
    +            popEval( pop, pop );
    +        }
    +    
    +
    + +
    +

    Thank you for your attention

    +
    + +
    +

    Remarks

    +
      +
    • This presentation is made of HTML5, CSS3, JavaScript, thanks to frameworks + Deck.js (slides) and SHJS (syntax + highlighting). +
    • If you have any complaint to make, please refer to Johann Dreo.
    • +
    • If you have any question or compliment, please refer to me + (Benjamin Bouvier).
    • +
    +
    + + + + + + +

    + + / + +

    + + +
    + + + + +
    + + +# + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eo/tutorial/Parallelization/img/generic_parallel.dia b/eo/tutorial/Parallelization/img/generic_parallel.dia new file mode 100644 index 000000000..693475c5b Binary files /dev/null and b/eo/tutorial/Parallelization/img/generic_parallel.dia differ diff --git a/eo/tutorial/Parallelization/img/generic_parallel.png b/eo/tutorial/Parallelization/img/generic_parallel.png new file mode 100644 index 000000000..90bbcf170 Binary files /dev/null and b/eo/tutorial/Parallelization/img/generic_parallel.png differ diff --git a/eo/tutorial/Parallelization/img/serialisation.dia b/eo/tutorial/Parallelization/img/serialisation.dia new file mode 100644 index 000000000..2a9333506 Binary files /dev/null and b/eo/tutorial/Parallelization/img/serialisation.dia differ diff --git a/eo/tutorial/Parallelization/img/serialisation.png b/eo/tutorial/Parallelization/img/serialisation.png new file mode 100644 index 000000000..76ac0a9c0 Binary files /dev/null and b/eo/tutorial/Parallelization/img/serialisation.png differ diff --git a/eo/tutorial/Parallelization/js/deck.core.js b/eo/tutorial/Parallelization/js/deck.core.js new file mode 100644 index 000000000..6fbeb5ce0 --- /dev/null +++ b/eo/tutorial/Parallelization/js/deck.core.js @@ -0,0 +1,498 @@ +/*! +Deck JS - deck.core +Copyright (c) 2011 Caleb Troughton +Dual licensed under the MIT license and GPL license. +https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt +https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt +*/ + +/* +The deck.core module provides all the basic functionality for creating and +moving through a deck. It does so by applying classes to indicate the state of +the deck and its slides, allowing CSS to take care of the visual representation +of each state. It also provides methods for navigating the deck and inspecting +its state, as well as basic key bindings for going to the next and previous +slides. More functionality is provided by wholly separate extension modules +that use the API provided by core. +*/ +(function($, deck, document, undefined) { + var slides, // Array of all the uh, slides... + current, // Array index of the current slide + $container, // Keeping this cached + + events = { + /* + This event fires whenever the current slide changes, whether by way of + next, prev, or go. The callback function is passed two parameters, from + and to, equal to the indices of the old slide and the new slide + respectively. If preventDefault is called on the event within this handler + the slide change does not occur. + + $(document).bind('deck.change', function(event, from, to) { + alert('Moving from slide ' + from + ' to ' + to); + }); + */ + change: 'deck.change', + + /* + This event fires at the beginning of deck initialization, after the options + are set but before the slides array is created. This event makes a good hook + for preprocessing extensions looking to modify the deck. + */ + beforeInitialize: 'deck.beforeInit', + + /* + This event fires at the end of deck initialization. Extensions should + implement any code that relies on user extensible options (key bindings, + element selectors, classes) within a handler for this event. Native + events associated with Deck JS should be scoped under a .deck event + namespace, as with the example below: + + var $d = $(document); + $.deck.defaults.keys.myExtensionKeycode = 70; // 'h' + $d.bind('deck.init', function() { + $d.bind('keydown.deck', function(event) { + if (event.which === $.deck.getOptions().keys.myExtensionKeycode) { + // Rock out + } + }); + }); + */ + initialize: 'deck.init' + }, + + options = {}, + $d = $(document), + + /* + Internal function. Updates slide and container classes based on which + slide is the current slide. + */ + updateStates = function() { + var oc = options.classes, + osc = options.selectors.container, + old = $container.data('onSlide'), + $all = $(); + + // Container state + $container.removeClass(oc.onPrefix + old) + .addClass(oc.onPrefix + current) + .data('onSlide', current); + + // Remove and re-add child-current classes for nesting + $('.' + oc.current).parentsUntil(osc).removeClass(oc.childCurrent); + slides[current].parentsUntil(osc).addClass(oc.childCurrent); + + // Remove previous states + $.each(slides, function(i, el) { + $all = $all.add(el); + }); + $all.removeClass([ + oc.before, + oc.previous, + oc.current, + oc.next, + oc.after + ].join(" ")); + + // Add new states back in + slides[current].addClass(oc.current); + if (current > 0) { + slides[current-1].addClass(oc.previous); + } + if (current + 1 < slides.length) { + slides[current+1].addClass(oc.next); + } + if (current > 1) { + $.each(slides.slice(0, current - 1), function(i, el) { + el.addClass(oc.before); + }); + } + if (current + 2 < slides.length) { + $.each(slides.slice(current+2), function(i, el) { + el.addClass(oc.after); + }); + } + }, + + /* Methods exposed in the jQuery.deck namespace */ + methods = { + + /* + jQuery.deck(selector, options) + + selector: string | jQuery | array + options: object, optional + + Initializes the deck, using each element matched by selector as a slide. + May also be passed an array of string selectors or jQuery objects, in + which case each selector in the array is considered a slide. The second + parameter is an optional options object which will extend the default + values. + + $.deck('.slide'); + + or + + $.deck([ + '#first-slide', + '#second-slide', + '#etc' + ]); + */ + init: function(elements, opts) { + var startTouch, + tolerance, + esp = function(e) { + e.stopPropagation(); + }; + + options = $.extend(true, {}, $[deck].defaults, opts); + slides = []; + current = 0; + $container = $(options.selectors.container); + tolerance = options.touch.swipeTolerance; + + // Pre init event for preprocessing hooks + $d.trigger(events.beforeInitialize); + + // Hide the deck while states are being applied to kill transitions + $container.addClass(options.classes.loading); + + // Fill slides array depending on parameter type + if ($.isArray(elements)) { + $.each(elements, function(i, e) { + slides.push($(e)); + }); + } + else { + $(elements).each(function(i, e) { + slides.push($(e)); + }); + } + + /* Remove any previous bindings, and rebind key events */ + $d.unbind('keydown.deck').bind('keydown.deck', function(e) { + if (e.which === options.keys.next || $.inArray(e.which, options.keys.next) > -1) { + methods.next(); + e.preventDefault(); + } + else if (e.which === options.keys.previous || $.inArray(e.which, options.keys.previous) > -1) { + methods.prev(); + e.preventDefault(); + } + }); + + /* Bind touch events for swiping between slides on touch devices */ + $container.unbind('touchstart.deck').bind('touchstart.deck', function(e) { + if (!startTouch) { + startTouch = $.extend({}, e.originalEvent.targetTouches[0]); + } + }) + .unbind('touchmove.deck').bind('touchmove.deck', function(e) { + $.each(e.originalEvent.changedTouches, function(i, t) { + if (startTouch && t.identifier === startTouch.identifier) { + if (t.screenX - startTouch.screenX > tolerance || t.screenY - startTouch.screenY > tolerance) { + $[deck]('prev'); + startTouch = undefined; + } + else if (t.screenX - startTouch.screenX < -1 * tolerance || t.screenY - startTouch.screenY < -1 * tolerance) { + $[deck]('next'); + startTouch = undefined; + } + return false; + } + }); + e.preventDefault(); + }) + .unbind('touchend.deck').bind('touchend.deck', function(t) { + $.each(t.originalEvent.changedTouches, function(i, t) { + if (startTouch && t.identifier === startTouch.identifier) { + startTouch = undefined; + } + }); + }) + .scrollLeft(0).scrollTop(0) + /* Stop propagation of key events within editable elements of slides */ + .undelegate('input, textarea, select, button, meter, progress, [contentEditable]', 'keydown', esp) + .delegate('input, textarea, select, button, meter, progress, [contentEditable]', 'keydown', esp); + + /* + Kick iframe videos, which dont like to redraw w/ transforms. + Remove this if Webkit ever fixes it. + */ + $.each(slides, function(i, $el) { + $el.unbind('webkitTransitionEnd.deck').bind('webkitTransitionEnd.deck', + function(event) { + if ($el.hasClass($[deck]('getOptions').classes.current)) { + var embeds = $(this).find('iframe').css('opacity', 0); + window.setTimeout(function() { + embeds.css('opacity', 1); + }, 100); + } + }); + }); + + if (slides.length) { + updateStates(); + } + + // Show deck again now that slides are in place + $container.removeClass(options.classes.loading); + $d.trigger(events.initialize); + }, + + /* + jQuery.deck('go', index) + + index: integer | string + + Moves to the slide at the specified index if index is a number. Index is + 0-based, so $.deck('go', 0); will move to the first slide. If index is a + string this will move to the slide with the specified id. If index is out + of bounds or doesn't match a slide id the call is ignored. + */ + go: function(index) { + var e = $.Event(events.change), + ndx; + + /* Number index, easy. */ + if (typeof index === 'number' && index >= 0 && index < slides.length) { + ndx = index; + } + /* Id string index, search for it and set integer index */ + else if (typeof index === 'string') { + $.each(slides, function(i, $slide) { + if ($slide.attr('id') === index) { + ndx = i; + return false; + } + }); + }; + + /* Out of bounds, id doesn't exist, illegal input, eject */ + if (typeof ndx === 'undefined') return; + + $d.trigger(e, [current, ndx]); + if (e.isDefaultPrevented()) { + /* Trigger the event again and undo the damage done by extensions. */ + $d.trigger(events.change, [ndx, current]); + } + else { + current = ndx; + updateStates(); + } + }, + + /* + jQuery.deck('next') + + Moves to the next slide. If the last slide is already active, the call + is ignored. + */ + next: function() { + methods.go(current+1); + }, + + /* + jQuery.deck('prev') + + Moves to the previous slide. If the first slide is already active, the + call is ignored. + */ + prev: function() { + methods.go(current-1); + }, + + /* + jQuery.deck('getSlide', index) + + index: integer, optional + + Returns a jQuery object containing the slide at index. If index is not + specified, the current slide is returned. + */ + getSlide: function(index) { + var i = typeof index !== 'undefined' ? index : current; + if (typeof i != 'number' || i < 0 || i >= slides.length) return null; + return slides[i]; + }, + + /* + jQuery.deck('getSlides') + + Returns all slides as an array of jQuery objects. + */ + getSlides: function() { + return slides; + }, + + /* + jQuery.deck('getContainer') + + Returns a jQuery object containing the deck container as defined by the + container option. + */ + getContainer: function() { + return $container; + }, + + /* + jQuery.deck('getOptions') + + Returns the options object for the deck, including any overrides that + were defined at initialization. + */ + getOptions: function() { + return options; + }, + + /* + jQuery.deck('extend', name, method) + + name: string + method: function + + Adds method to the deck namespace with the key of name. This doesn’t + give access to any private member data — public methods must still be + used within method — but lets extension authors piggyback on the deck + namespace rather than pollute jQuery. + + $.deck('extend', 'alert', function(msg) { + alert(msg); + }); + + // Alerts 'boom' + $.deck('alert', 'boom'); + */ + extend: function(name, method) { + methods[name] = method; + } + }; + + /* jQuery extension */ + $[deck] = function(method, arg) { + if (methods[method]) { + return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); + } + else { + return methods.init(method, arg); + } + }; + + /* + The default settings object for a deck. All deck extensions should extend + this object to add defaults for any of their options. + + options.classes.after + This class is added to all slides that appear after the 'next' slide. + + options.classes.before + This class is added to all slides that appear before the 'previous' + slide. + + options.classes.childCurrent + This class is added to all elements in the DOM tree between the + 'current' slide and the deck container. For standard slides, this is + mostly seen and used for nested slides. + + options.classes.current + This class is added to the current slide. + + options.classes.loading + This class is applied to the deck container during loading phases and is + primarily used as a way to short circuit transitions between states + where such transitions are distracting or unwanted. For example, this + class is applied during deck initialization and then removed to prevent + all the slides from appearing stacked and transitioning into place + on load. + + options.classes.next + This class is added to the slide immediately following the 'current' + slide. + + options.classes.onPrefix + This prefix, concatenated with the current slide index, is added to the + deck container as you change slides. + + options.classes.previous + This class is added to the slide immediately preceding the 'current' + slide. + + options.selectors.container + Elements matched by this CSS selector will be considered the deck + container. The deck container is used to scope certain states of the + deck, as with the onPrefix option, or with extensions such as deck.goto + and deck.menu. + + options.keys.next + The numeric keycode used to go to the next slide. + + options.keys.previous + The numeric keycode used to go to the previous slide. + + options.touch.swipeTolerance + The number of pixels the users finger must travel to produce a swipe + gesture. + */ + $[deck].defaults = { + classes: { + after: 'deck-after', + before: 'deck-before', + childCurrent: 'deck-child-current', + current: 'deck-current', + loading: 'deck-loading', + next: 'deck-next', + onPrefix: 'on-slide-', + previous: 'deck-previous' + }, + + selectors: { + container: '.deck-container' + }, + + keys: { + // enter, space, page down, right arrow, down arrow, + next: [13, 32, 34, 39, 40], + // backspace, page up, left arrow, up arrow + previous: [8, 33, 37, 38] + }, + + touch: { + swipeTolerance: 60 + } + }; + + $d.ready(function() { + $('html').addClass('ready'); + }); + + /* + FF + Transforms + Flash video don't get along... + Firefox will reload and start playing certain videos after a + transform. Blanking the src when a previously shown slide goes out + of view prevents this. + */ + $d.bind('deck.change', function(e, from, to) { + var oldFrames = $[deck]('getSlide', from).find('iframe'), + newFrames = $[deck]('getSlide', to).find('iframe'); + + oldFrames.each(function() { + var $this = $(this), + curSrc = $this.attr('src'); + + if(curSrc) { + $this.data('deck-src', curSrc).attr('src', ''); + } + }); + + newFrames.each(function() { + var $this = $(this), + originalSrc = $this.data('deck-src'); + + if (originalSrc) { + $this.attr('src', originalSrc); + } + }); + }); +})(jQuery, 'deck', document); diff --git a/eo/tutorial/Parallelization/js/deck.goto.js b/eo/tutorial/Parallelization/js/deck.goto.js new file mode 100644 index 000000000..eedba10b1 --- /dev/null +++ b/eo/tutorial/Parallelization/js/deck.goto.js @@ -0,0 +1,170 @@ +/*! +Deck JS - deck.goto +Copyright (c) 2011 Caleb Troughton +Dual licensed under the MIT license and GPL license. +https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt +https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt +*/ + +/* +This module adds the necessary methods and key bindings to show and hide a form +for jumping to any slide number/id in the deck (and processes that form +accordingly). The form-showing state is indicated by the presence of a class on +the deck container. +*/ +(function($, deck, undefined) { + var $d = $(document); + + /* + Extends defaults/options. + + options.classes.goto + This class is added to the deck container when showing the Go To Slide + form. + + options.selectors.gotoDatalist + The element that matches this selector is the datalist element that will + be populated with options for each of the slide ids. In browsers that + support the datalist element, this provides a drop list of slide ids to + aid the user in selecting a slide. + + options.selectors.gotoForm + The element that matches this selector is the form that is submitted + when a user hits enter after typing a slide number/id in the gotoInput + element. + + options.selectors.gotoInput + The element that matches this selector is the text input field for + entering a slide number/id in the Go To Slide form. + + options.keys.goto + The numeric keycode used to show the Go To Slide form. + + options.countNested + If false, only top level slides will be counted when entering a + slide number. + */ + $.extend(true, $[deck].defaults, { + classes: { + goto: 'deck-goto' + }, + + selectors: { + gotoDatalist: '#goto-datalist', + gotoForm: '.goto-form', + gotoInput: '#goto-slide' + }, + + keys: { + goto: 71 // g + }, + + countNested: true + }); + + /* + jQuery.deck('showGoTo') + + Shows the Go To Slide form by adding the class specified by the goto class + option to the deck container. + */ + $[deck]('extend', 'showGoTo', function() { + $[deck]('getContainer').addClass($[deck]('getOptions').classes.goto); + $($[deck]('getOptions').selectors.gotoInput).focus(); + }); + + /* + jQuery.deck('hideGoTo') + + Hides the Go To Slide form by removing the class specified by the goto class + option from the deck container. + */ + $[deck]('extend', 'hideGoTo', function() { + $($[deck]('getOptions').selectors.gotoInput).blur(); + $[deck]('getContainer').removeClass($[deck]('getOptions').classes.goto); + }); + + /* + jQuery.deck('toggleGoTo') + + Toggles between showing and hiding the Go To Slide form. + */ + $[deck]('extend', 'toggleGoTo', function() { + $[deck]($[deck]('getContainer').hasClass($[deck]('getOptions').classes.goto) ? 'hideGoTo' : 'showGoTo'); + }); + + $d.bind('deck.init', function() { + var opts = $[deck]('getOptions'), + $datalist = $(opts.selectors.gotoDatalist), + slideTest = $.map([ + opts.classes.before, + opts.classes.previous, + opts.classes.current, + opts.classes.next, + opts.classes.after + ], function(el, i) { + return '.' + el; + }).join(', '), + rootCounter = 1; + + // Bind key events + $d.unbind('keydown.deckgoto').bind('keydown.deckgoto', function(e) { + var key = $[deck]('getOptions').keys.goto; + + if (e.which === key || $.inArray(e.which, key) > -1) { + e.preventDefault(); + $[deck]('toggleGoTo'); + } + }); + + /* Populate datalist and work out countNested*/ + $.each($[deck]('getSlides'), function(i, $slide) { + var id = $slide.attr('id'), + $parentSlides = $slide.parentsUntil(opts.selectors.container, slideTest); + + if (id) { + $datalist.append('