* New tree configuration of the project:
.../
... + -- EO
| |
| |
+-- src ----- + -- EDO
| |
| |
+-- test + -- MO
| |
| |
+-- tutorial + -- MOEO
| |
| |
+-- doc + -- SMP
| |
| |
... + -- EOMPI
|
|
+ -- EOSERIAL
Question for current maintainers: ./README: new release?
Also:
* Moving out eompi & eoserial modules (issue #2).
* Correction of the errors when executing "make doc" command.
* Adding a solution for the conflicting headers problem (see the two CMake Cache
Values: PROJECT_TAG & PROJECT_HRS_INSTALL_SUBPATH) (issue #1)
* Header inclusions:
** src: changing absolute paths into relative paths ('#include <...>' -> '#include "..."')
** test, tutorial: changing relative paths into absolute paths ('#include "..."' -> '#include <...>')
* Moving out some scripts from EDO -> to the root
* Add a new script for compilation and installation (see build_gcc_linux_install)
* Compilation with uBLAS library or EDO module: now ok
* Minor modifications on README & INSTALL files
* Comment eompi failed tests with no end
*** TODO: CPack (debian (DEB) & RedHat (RPM) packages) (issues #6 & #7) ***
This commit is contained in:
parent
515bd5943d
commit
490e837f7a
2359 changed files with 7688 additions and 16329 deletions
53
test/CMakeLists.txt
Executable file
53
test/CMakeLists.txt
Executable file
|
|
@ -0,0 +1,53 @@
|
|||
## EO Module
|
||||
add_subdirectory(${EO_TEST_DIR})
|
||||
|
||||
if(NOT EO_ONLY)
|
||||
|
||||
## MO Module
|
||||
if(MO)
|
||||
add_subdirectory(${MO_TEST_DIR})
|
||||
endif(MO)
|
||||
|
||||
## EDO Module
|
||||
if(EDO)
|
||||
if(EDO_USE_LIB STREQUAL "Eigen3")
|
||||
find_package(Eigen3)
|
||||
if(EIGEN3_FOUND) # see edoNormalAdaptive
|
||||
add_subdirectory(${EDO_TEST_DIR})
|
||||
else(EIGEN3_FOUND)
|
||||
message(FATAL_ERROR "\n\nERROR: You asked for Eigen3 but it has not been found.\n" )
|
||||
endif(EIGEN3_FOUND)
|
||||
elseif(EDO_USE_LIB STREQUAL "uBLAS")
|
||||
find_package(Boost)
|
||||
if(Boost_FOUND)
|
||||
message("Warning: EDO_USE_LIB MATCHES ${EDO_USE_LIB} but Eigen3 recommended for tests")
|
||||
add_subdirectory(${EDO_TEST_DIR})
|
||||
else(Boost_FOUND)
|
||||
message(FATAL_ERROR "\n\nERROR: You asked for Boost::uBLAS but it has not been found.\n" )
|
||||
endif(Boost_FOUND)
|
||||
else()
|
||||
message(FATAL_ERROR "\n\nYou must set EDO_USE_LIB to either 'uBLAS' or 'Eigen3'.\n" )
|
||||
endif()
|
||||
endif(EDO)
|
||||
|
||||
## MOEO Module
|
||||
if(MOEO)
|
||||
add_subdirectory(${MOEO_TEST_DIR})
|
||||
endif(MOEO)
|
||||
|
||||
## SMP Module
|
||||
if(SMP)
|
||||
add_subdirectory(${SMP_TEST_DIR})
|
||||
endif(SMP)
|
||||
|
||||
## EOMPI Module
|
||||
if(EOMPI)
|
||||
add_subdirectory(${EOMPI_TEST_DIR})
|
||||
endif(EOMPI)
|
||||
|
||||
## EOSERIAL Module
|
||||
#if(EOSERIAL)
|
||||
# add_subdirectory(${EOSERIAL_TEST_DIR})
|
||||
#endif(EOSERIAL)
|
||||
|
||||
endif()
|
||||
59
test/edo/CMakeLists.txt
Executable file
59
test/edo/CMakeLists.txt
Executable file
|
|
@ -0,0 +1,59 @@
|
|||
###############################################################################
|
||||
##
|
||||
## CMakeLists file for unit test
|
||||
##
|
||||
###############################################################################
|
||||
|
||||
|
||||
######################################################################################
|
||||
### 1) Include the sources
|
||||
######################################################################################
|
||||
|
||||
#include_directories(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
#include_directories(${CMAKE_SOURCE_DIR}/application/common)
|
||||
include_directories(${EDO_TUTORIAL_DIR}/common)
|
||||
#include_directories(${EO_SRC_DIR}/src)
|
||||
#include_directories(${EDO_SRC_DIR}/src)
|
||||
|
||||
######################################################################################
|
||||
### 2) Specify where CMake can find the libraries
|
||||
######################################################################################
|
||||
|
||||
if(EDO_USE_LIB STREQUAL "Eigen3")
|
||||
find_package(Eigen3)
|
||||
include_directories( ${EIGEN3_INCLUDE_DIR} )
|
||||
add_definitions( -DWITH_EIGEN )
|
||||
elseif(EDO_USE_LIB STREQUAL "uBLAS")
|
||||
find_package(Boost)
|
||||
include_directories( ${Boost_INCLUDE_DIRS} )
|
||||
add_definitions( -DWITH_BOOST )
|
||||
else()
|
||||
message(FATAL_ERROR "\n\nYou must set EDO_USE_LIB to either 'uBLAS' or 'Eigen3'.\n" )
|
||||
endif()
|
||||
|
||||
######################################################################################
|
||||
### 3) Define your targets and link the librairies
|
||||
######################################################################################
|
||||
|
||||
set(SOURCES
|
||||
#t-cholesky
|
||||
t-variance
|
||||
t-edoEstimatorNormalMulti
|
||||
t-mean-distance
|
||||
t-bounderno
|
||||
t-uniform
|
||||
t-continue
|
||||
# t-dispatcher-round
|
||||
t-repairer-modulo
|
||||
t-binomial
|
||||
t-binomialmulti
|
||||
)
|
||||
|
||||
foreach(current ${SOURCES})
|
||||
add_executable(${current} ${current}.cpp)
|
||||
add_test(${current} ${current})
|
||||
target_link_libraries(${current} eo eoutils edoutils)
|
||||
install(TARGETS ${current} RUNTIME DESTINATION share/edo/test COMPONENT test)
|
||||
endforeach()
|
||||
|
||||
######################################################################################
|
||||
502
test/edo/COPYING
Executable file
502
test/edo/COPYING
Executable file
|
|
@ -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.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it 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.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
19
test/edo/boxplot.py
Executable file
19
test/edo/boxplot.py
Executable file
|
|
@ -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()
|
||||
104
test/edo/t-binomial.cpp
Executable file
104
test/edo/t-binomial.cpp
Executable file
|
|
@ -0,0 +1,104 @@
|
|||
/*
|
||||
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) 2013 Thales group
|
||||
*/
|
||||
/*
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
#include <paradiseo/eo/ga.h> // for Bools
|
||||
|
||||
template<class T>
|
||||
void print( T v, std::string sep=" " )
|
||||
{
|
||||
for( typename T::iterator it=v.begin(); it!=v.end(); ++it ) {
|
||||
std::cout << *it << sep;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
int main(int ac, char** av)
|
||||
{
|
||||
typedef eoBit<double> Bools;
|
||||
|
||||
eoParser parser(ac, av);
|
||||
|
||||
std::string section("Algorithm parameters");
|
||||
unsigned int popsize = parser.createParam((unsigned int)100000, "popSize", "Population Size", 'P', section).value(); // P
|
||||
unsigned int dim = parser.createParam((unsigned int)20, "dim", "Dimension size", 'd', section).value(); // d
|
||||
double proba = parser.createParam((double)0.5, "proba", "Probability to estimate", 'b', section).value(); // b
|
||||
|
||||
if( parser.userNeedsHelp() ) {
|
||||
parser.printHelp(std::cout);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
make_help(parser);
|
||||
|
||||
|
||||
// This generate a random boolean when called...
|
||||
eoBooleanGenerator flip( proba );
|
||||
|
||||
// ... by this initializator...
|
||||
eoInitFixedLength<Bools> init( dim, flip );
|
||||
|
||||
// ... when building this pop.
|
||||
std::cout << "Init a pop of eoBit of size " << popsize << " at random with p(x=1)=" << proba << std::endl;
|
||||
eoPop<Bools> pop( popsize, init );
|
||||
// print( pop, "\n" );
|
||||
|
||||
// EDO triplet
|
||||
edoBinomial<Bools> distrib(dim,0.0);
|
||||
edoEstimatorBinomial<Bools> estimate;
|
||||
edoSamplerBinomial<Bools> sample;
|
||||
|
||||
std::cout << "Estimate a distribution from the init pop" << std::endl;
|
||||
distrib = estimate(pop);
|
||||
print( distrib );
|
||||
// std::cout << std::endl;
|
||||
|
||||
std::cout << "Sample a new pop from the init distrib" << std::endl;
|
||||
pop.clear();
|
||||
for( unsigned int i=0; i<popsize; ++i ) {
|
||||
pop.push_back( sample( distrib ) );
|
||||
}
|
||||
// print( pop, "\n" );
|
||||
|
||||
std::cout << "Estimate a distribution from the sampled pop" << std::endl;
|
||||
distrib = estimate(pop);
|
||||
print( distrib );
|
||||
// std::cout << std::endl;
|
||||
|
||||
double sum=0;
|
||||
for( unsigned int i=0; i<distrib.size(); ++i ) {
|
||||
sum += distrib[i];
|
||||
}
|
||||
double e = sum / dim;
|
||||
|
||||
std::cout << "Estimated initial proba = " << e << std::endl;
|
||||
}
|
||||
95
test/edo/t-binomialmulti.cpp
Executable file
95
test/edo/t-binomialmulti.cpp
Executable file
|
|
@ -0,0 +1,95 @@
|
|||
/*
|
||||
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) 2013 Thales group
|
||||
*/
|
||||
/*
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
#include <paradiseo/eo/ga.h> // for Bools
|
||||
|
||||
|
||||
#ifdef WITH_EIGEN
|
||||
#include <Eigen/Dense>
|
||||
#endif // WITH_EIGEN
|
||||
|
||||
#ifdef WITH_EIGEN
|
||||
// NOTE: a typedef on eoVector does not work, because of readFrom on a vector AtomType
|
||||
// typedef eoVector<eoMinimizingFitness, std::vector<bool> > Bools;
|
||||
class Bools : public std::vector<std::vector<bool> >, public EO<double>
|
||||
{
|
||||
public:
|
||||
typedef std::vector<bool> AtomType;
|
||||
};
|
||||
#endif
|
||||
|
||||
int main(int ac, char** av)
|
||||
{
|
||||
|
||||
#ifdef WITH_EIGEN
|
||||
eoParser parser(ac, av);
|
||||
|
||||
std::string section("Algorithm parameters");
|
||||
unsigned int popsize = parser.createParam((unsigned int)100000, "popSize", "Population Size", 'P', section).value(); // P
|
||||
unsigned int rows = parser.createParam((unsigned int)2, "lines", "Lines number", 'l', section).value(); // l
|
||||
unsigned int cols = parser.createParam((unsigned int)3, "columns", "Columns number", 'c', section).value(); // c
|
||||
double proba = parser.createParam((double)0.5, "proba", "Probability to estimate", 'b', section).value(); // b
|
||||
|
||||
if( parser.userNeedsHelp() ) {
|
||||
parser.printHelp(std::cout);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
make_help(parser);
|
||||
|
||||
std::cout << "Init distrib" << std::endl;
|
||||
Eigen::MatrixXd initd = Eigen::MatrixXd::Constant(rows,cols,proba);
|
||||
edoBinomialMulti<Bools> distrib( initd );
|
||||
std::cout << distrib << std::endl;
|
||||
|
||||
edoEstimatorBinomialMulti<Bools> estimate;
|
||||
edoSamplerBinomialMulti<Bools> sample;
|
||||
|
||||
std::cout << "Sample a pop from the init distrib" << std::endl;
|
||||
eoPop<Bools> pop; pop.reserve(popsize);
|
||||
for( unsigned int i=0; i < popsize; ++i ) {
|
||||
pop.push_back( sample( distrib ) );
|
||||
}
|
||||
|
||||
std::cout << "Estimate a distribution from the sampled pop" << std::endl;
|
||||
distrib = estimate( pop );
|
||||
std::cout << distrib << std::endl;
|
||||
|
||||
std::cout << "Estimated initial proba = " << distrib.mean() << std::endl;
|
||||
#else
|
||||
#ifdef WITH_BOOST
|
||||
#pragma message "WARNING: there is no Boost::uBLAS implementation of t-binomialmulti, build WITH_EIGEN if you need it."
|
||||
#endif
|
||||
#endif // WITH_EIGEN
|
||||
return 0;
|
||||
}
|
||||
40
test/edo/t-bounderno.cpp
Executable file
40
test/edo/t-bounderno.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
|
||||
#include "Rosenbrock.h"
|
||||
|
||||
typedef eoReal< eoMinimizingFitness > EOT;
|
||||
|
||||
int main(void)
|
||||
{
|
||||
edoBounderNo< EOT > bounder;
|
||||
|
||||
return 0;
|
||||
}
|
||||
250
test/edo/t-cholesky.cpp
Executable file
250
test/edo/t-cholesky.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
//#include <vector>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <limits>
|
||||
#include <iomanip>
|
||||
#include <ctime>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
|
||||
typedef eoReal< eoMinimizingFitness > EOT;
|
||||
typedef edoNormalMulti<EOT> EOD;
|
||||
|
||||
|
||||
void setformat( std::ostream& out )
|
||||
{
|
||||
out << std::right;
|
||||
out << std::setfill(' ');
|
||||
out << std::setw( 5 + std::numeric_limits<double>::digits10);
|
||||
out << std::setprecision(std::numeric_limits<double>::digits10);
|
||||
out << std::setiosflags(std::ios_base::showpoint);
|
||||
}
|
||||
|
||||
|
||||
template<typename MT>
|
||||
std::string format(const MT& mat )
|
||||
{
|
||||
std::ostringstream out;
|
||||
setformat(out);
|
||||
|
||||
for( unsigned int i=0; i<mat.size1(); ++i) {
|
||||
for( unsigned int j=0; j<mat.size2(); ++j) {
|
||||
out << mat(i,j) << "\t";
|
||||
} // columns
|
||||
out << std::endl;
|
||||
} // rows
|
||||
|
||||
return out.str();
|
||||
}
|
||||
|
||||
|
||||
template< typename T >
|
||||
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<typename MT>
|
||||
bool equal( const MT& M1, const MT& M2, double prec /* = 1/std::numeric_limits<double>::digits10 ???*/ )
|
||||
{
|
||||
if( M1.size1() != M2.size1() || M1.size2() != M2.size2() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for( unsigned int i=0; i<M1.size1(); ++i ) {
|
||||
for( unsigned int j=0; j<M1.size2(); ++j ) {
|
||||
if( round(M1(i,j),prec) != round(M2(i,j),prec) ) {
|
||||
std::cout << "round(M(" << i << "," << j << "," << prec << ") == "
|
||||
<< round(M1(i,j),prec) << " != " << round(M2(i,j),prec) << std::endl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
template<typename MT >
|
||||
MT error( const MT& M1, const MT& M2 )
|
||||
{
|
||||
assert( M1.size1() == M2.size1() && M1.size1() == M2.size2() );
|
||||
|
||||
MT Err = ublas::zero_matrix<double>(M1.size1(),M1.size2());
|
||||
|
||||
for( unsigned int i=0; i<M1.size1(); ++i ) {
|
||||
for( unsigned int j=0; j<M1.size2(); ++j ) {
|
||||
Err(i,j) = M1(i,j) - M2(i,j);
|
||||
}
|
||||
}
|
||||
|
||||
return Err;
|
||||
}
|
||||
|
||||
|
||||
template<typename MT >
|
||||
double trigsum( const MT& M )
|
||||
{
|
||||
double sum;
|
||||
for( unsigned int i=0; i<M.size1(); ++i ) {
|
||||
for( unsigned int j=i; j<M.size2(); ++j ) { // triangular browsing
|
||||
sum += fabs( M(i,j) ); // absolute deviation
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
double sum( const T& c )
|
||||
{
|
||||
return std::accumulate(c.begin(), c.end(), 0);
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
srand(time(0));
|
||||
|
||||
unsigned int N = 4; // size of matrix
|
||||
unsigned int R = 1000; // nb of repetitions
|
||||
|
||||
if( argc >= 2 ) {
|
||||
N = std::atoi(argv[1]);
|
||||
}
|
||||
if( argc >= 3 ) {
|
||||
R = std::atoi(argv[2]);
|
||||
}
|
||||
|
||||
std::cout << "Usage: t-cholesky [matrix size] [repetitions]" << std::endl;
|
||||
std::cout << "matrix size = " << N << std::endl;
|
||||
std::cout << "repetitions = " << R << std::endl;
|
||||
|
||||
typedef edoSamplerNormalMulti<EOT,EOD>::Cholesky::CovarMat CovarMat;
|
||||
typedef edoSamplerNormalMulti<EOT,EOD>::Cholesky::FactorMat FactorMat;
|
||||
|
||||
edoSamplerNormalMulti<EOT,EOD>::Cholesky LLT( edoSamplerNormalMulti<EOT,EOD>::Cholesky::standard );
|
||||
edoSamplerNormalMulti<EOT,EOD>::Cholesky LLTa( edoSamplerNormalMulti<EOT,EOD>::Cholesky::absolute );
|
||||
edoSamplerNormalMulti<EOT,EOD>::Cholesky LLTz( edoSamplerNormalMulti<EOT,EOD>::Cholesky::zeroing );
|
||||
edoSamplerNormalMulti<EOT,EOD>::Cholesky LDLT( edoSamplerNormalMulti<EOT,EOD>::Cholesky::robust );
|
||||
|
||||
std::vector<double> s0,s1,s2,s3;
|
||||
for( unsigned int n=0; n<R; ++n ) {
|
||||
|
||||
// a variance-covariance matrix of size N*N
|
||||
CovarMat V(N,N);
|
||||
|
||||
// random covariance matrix
|
||||
for( unsigned int i=0; i<N; ++i) {
|
||||
V(i,i) = std::pow(rand(),2); // variance should be >= 0
|
||||
for( unsigned int j=i+1; j<N; ++j) {
|
||||
V(i,j) = rand();
|
||||
}
|
||||
}
|
||||
|
||||
FactorMat L0 = LLT(V);
|
||||
CovarMat V0 = ublas::prod( L0, ublas::trans(L0) );
|
||||
s0.push_back( trigsum(error(V,V0)) );
|
||||
|
||||
FactorMat L1 = LLTa(V);
|
||||
CovarMat V1 = ublas::prod( L1, ublas::trans(L1) );
|
||||
s1.push_back( trigsum(error(V,V1)) );
|
||||
|
||||
FactorMat L2 = LLTz(V);
|
||||
CovarMat V2 = ublas::prod( L2, ublas::trans(L2) );
|
||||
s2.push_back( trigsum(error(V,V2)) );
|
||||
|
||||
FactorMat L3 = LDLT(V);
|
||||
CovarMat V3 = ublas::prod( L3, ublas::trans(L3) );
|
||||
s3.push_back( trigsum(error(V,V3)) );
|
||||
}
|
||||
|
||||
std::cout << "Average error:" << std::endl;
|
||||
std::cout << "\tLLT: " << sum(s0)/R << std::endl;
|
||||
std::cout << "\tLLTa: " << sum(s1)/R << std::endl;
|
||||
std::cout << "\tLLTz: " << sum(s2)/R << std::endl;
|
||||
std::cout << "\tLDLT: " << sum(s3)/R << std::endl;
|
||||
|
||||
// double precision = 1e-15;
|
||||
// if( argc >= 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<EOT,EOD>::Cholesky LLT( edoSamplerNormalMulti<EOT,EOD>::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<EOT,EOD>::Cholesky LLTa( edoSamplerNormalMulti<EOT,EOD>::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<EOT,EOD>::Cholesky LDLT( edoSamplerNormalMulti<EOT,EOD>::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;
|
||||
|
||||
}
|
||||
44
test/edo/t-continue.cpp
Executable file
44
test/edo/t-continue.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
|
||||
#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;
|
||||
}
|
||||
81
test/edo/t-dispatcher-round.cpp
Executable file
81
test/edo/t-dispatcher-round.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
Pierre Savéant <pierre.saveant@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
|
||||
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<EOT>* rep1 = new edoRepairerFloor<EOT>();
|
||||
edoRepairer<EOT>* rep2 = new edoRepairerCeil<EOT>();
|
||||
edoRepairer<EOT>* rep3 = new edoRepairerRound<EOT>();
|
||||
edoRepairer<EOT>* rep4 = new edoRepairerRoundDecimals<EOT>( 10 );
|
||||
|
||||
std::vector<unsigned int> indexes1;
|
||||
indexes1.push_back(0);
|
||||
indexes1.push_back(2);
|
||||
|
||||
std::vector<unsigned int> indexes2;
|
||||
indexes2.push_back(1);
|
||||
indexes2.push_back(3);
|
||||
|
||||
std::vector<unsigned int> indexes3;
|
||||
indexes3.push_back(4);
|
||||
indexes3.push_back(5);
|
||||
|
||||
std::vector<unsigned int> indexes4;
|
||||
indexes4.push_back(6);
|
||||
indexes4.push_back(7);
|
||||
indexes4.push_back(8);
|
||||
|
||||
edoRepairerDispatcher<EOT> repare( indexes1, rep1 );
|
||||
repare.add( indexes2, rep2 );
|
||||
repare.add( indexes3, rep3 );
|
||||
repare.add( indexes4, rep4 );
|
||||
|
||||
repare(sol);
|
||||
|
||||
std::cout << sol << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
198
test/edo/t-edoEstimatorNormalMulti.cpp
Executable file
198
test/edo/t-edoEstimatorNormalMulti.cpp
Executable file
|
|
@ -0,0 +1,198 @@
|
|||
/*
|
||||
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 <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
//#include <paradiseo/mo.h>
|
||||
|
||||
#include "Rosenbrock.h"
|
||||
#include "Sphere.h"
|
||||
|
||||
typedef eoReal< eoMinimizingFitness > EOT;
|
||||
typedef edoNormalMulti< EOT > Distrib;
|
||||
typedef EOT::AtomType AtomType;
|
||||
|
||||
#ifdef WITH_BOOST
|
||||
#include <boost/numeric/ublas/vector.hpp>
|
||||
#include <boost/numeric/ublas/symmetric.hpp>
|
||||
typedef ublas::vector< AtomType > Vector;
|
||||
typedef ublas::symmetric_matrix< AtomType, ublas::lower > Matrix;
|
||||
#else
|
||||
#ifdef WITH_EIGEN
|
||||
#include <Eigen/Dense>
|
||||
typedef edoNormalMulti<EOT>::Vector Vector;
|
||||
typedef edoNormalMulti<EOT>::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<EOT>;
|
||||
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;
|
||||
}
|
||||
243
test/edo/t-mean-distance.cpp
Executable file
243
test/edo/t-mean-distance.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <fstream>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
//#include <paradiseo/mo.h>
|
||||
|
||||
#include <paradiseo/edo.h>
|
||||
|
||||
|
||||
#include "Rosenbrock.h"
|
||||
#include "Sphere.h"
|
||||
|
||||
typedef eoReal< eoMinimizingFitness > EOT;
|
||||
typedef edoNormalMulti< EOT > Distrib;
|
||||
typedef EOT::AtomType AtomType;
|
||||
|
||||
#ifdef WITH_BOOST
|
||||
#include <boost/numeric/ublas/vector.hpp>
|
||||
#include <boost/numeric/ublas/symmetric.hpp>
|
||||
typedef ublas::vector< AtomType > Vector;
|
||||
typedef ublas::symmetric_matrix< AtomType, ublas::lower > Matrix;
|
||||
#else
|
||||
#ifdef WITH_EIGEN
|
||||
#include <Eigen/Dense>
|
||||
typedef edoNormalMulti<EOT>::Vector Vector;
|
||||
typedef edoNormalMulti<EOT>::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;
|
||||
}
|
||||
55
test/edo/t-repairer-modulo.cpp
Executable file
55
test/edo/t-repairer-modulo.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#define _USE_MATH_DEFINES
|
||||
#include <math.h>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
|
||||
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<EOT>* repare = new edoRepairerModulo<EOT>( 2 * M_PI ); // modulo 2pi
|
||||
|
||||
(*repare)(sol);
|
||||
|
||||
std::cout << sol << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
43
test/edo/t-uniform.cpp
Executable file
43
test/edo/t-uniform.cpp
Executable file
|
|
@ -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 <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
|
||||
#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;
|
||||
}
|
||||
83
test/edo/t-variance.cpp
Executable file
83
test/edo/t-variance.cpp
Executable file
|
|
@ -0,0 +1,83 @@
|
|||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/edo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
|
||||
typedef eoReal<eoMinimizingFitness> 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<ex_mean.size(); ++i ) {
|
||||
assert( es_mean[i] == ex_mean[i] );
|
||||
assert( es_var[i] == ex_var[i] );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
std::clog << "Variance computation on a simple vector" << std::endl;
|
||||
eoPop<Vec> 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<Vec> estimator;
|
||||
|
||||
edoNormalMono<Vec> 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 );
|
||||
}
|
||||
|
||||
18
test/edo/test_cov_parameters.py
Executable file
18
test/edo/test_cov_parameters.py
Executable file
|
|
@ -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 )
|
||||
116
test/eo/CMakeLists.txt
Executable file
116
test/eo/CMakeLists.txt
Executable file
|
|
@ -0,0 +1,116 @@
|
|||
###############################################################################
|
||||
##
|
||||
## CMakeLists file for eo/test
|
||||
##
|
||||
###############################################################################
|
||||
|
||||
|
||||
######################################################################################
|
||||
### 1) Include the sources
|
||||
######################################################################################
|
||||
|
||||
#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_BIN_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 share/${PROJECT_TAG}/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)
|
||||
|
||||
######################################################################################
|
||||
7
test/eo/CTestConfig.cmake
Executable file
7
test/eo/CTestConfig.cmake
Executable file
|
|
@ -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)
|
||||
36
test/eo/ChangeLog
Executable file
36
test/eo/ChangeLog
Executable file
|
|
@ -0,0 +1,36 @@
|
|||
2006-12-04 Jochen Kpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* Makefile.am: Add t-eoRNG
|
||||
|
||||
* t-eoRNG.cpp: Start test for random number generator.
|
||||
|
||||
2006-12-02 Jochen Kpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* 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 <thomas.legrand@inria.fr>
|
||||
|
||||
* test/t-eoEasyPSO.cpp: added PSO test
|
||||
|
||||
* test/Makefile.am: added PSO test
|
||||
|
||||
|
||||
2006-02-27 Thomas Legrand <thomas.legrand@inria.fr>
|
||||
|
||||
* 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:
|
||||
502
test/eo/LICENSE
Executable file
502
test/eo/LICENSE
Executable file
|
|
@ -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.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
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.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
62
test/eo/RoyalRoad.h
Executable file
62
test/eo/RoyalRoad.h
Executable file
|
|
@ -0,0 +1,62 @@
|
|||
/*
|
||||
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
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
template<class EOT>
|
||||
class RoyalRoad: public eoEvalFunc<EOT> {
|
||||
|
||||
public:
|
||||
|
||||
typedef typename EOT::Fitness FitT;
|
||||
|
||||
/// Ctor: takes a length, and divides that length in equal parts
|
||||
RoyalRoad( unsigned _div ): eoEvalFunc<EOT >(), 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
|
||||
16
test/eo/binary_value.h
Executable file
16
test/eo/binary_value.h
Executable file
|
|
@ -0,0 +1,16 @@
|
|||
#include <algorithm>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** Just the simple function that takes binary value of a chromosome and sets
|
||||
the fitnes.
|
||||
@param _chrom A binary chromosome
|
||||
*/
|
||||
|
||||
template <class Chrom> double binary_value(const Chrom& _chrom)
|
||||
{
|
||||
double sum = 0.0;
|
||||
for (unsigned i=0; i<_chrom.size(); i++)
|
||||
sum += _chrom[i];
|
||||
return sum;
|
||||
}
|
||||
15
test/eo/boxplot.py
Executable file
15
test/eo/boxplot.py
Executable file
|
|
@ -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()
|
||||
15
test/eo/boxplot_to_pdf.py
Executable file
15
test/eo/boxplot_to_pdf.py
Executable file
|
|
@ -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 )
|
||||
15
test/eo/boxplot_to_png.py
Executable file
15
test/eo/boxplot_to_png.py
Executable file
|
|
@ -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' )
|
||||
431
test/eo/fitness_traits.cpp
Executable file
431
test/eo/fitness_traits.cpp
Executable file
|
|
@ -0,0 +1,431 @@
|
|||
#include <map> // for pair
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <math.h> // for exp
|
||||
|
||||
using namespace std;
|
||||
|
||||
/* fitness_traits.h */
|
||||
|
||||
// default traits: defaults to a double that needs to be maximized
|
||||
template <class T = double>
|
||||
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 <class EOT>
|
||||
static worth_type get_fitness(const EOT& _eo) { return _eo.performance(); }
|
||||
|
||||
// compare the two individuals
|
||||
template <class EOT>
|
||||
static bool is_better(const EOT& _eo1, const EOT& _eo2)
|
||||
{
|
||||
return _eo1.performance() > _eo2.performance();
|
||||
}
|
||||
};
|
||||
|
||||
struct minimization {};
|
||||
struct maximization {};
|
||||
|
||||
struct fitness_traits<minimization> : public fitness_traits<double>
|
||||
{
|
||||
// for minimization, invert the is_better
|
||||
template <class EOT>
|
||||
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<maximization> : public fitness_traits<double> {};
|
||||
|
||||
// forward declaration
|
||||
//template <class EOT> class eoPop;
|
||||
//template <class Fitness, class Traits> 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 <class Performance, class Worth>
|
||||
struct fitness_traits< pair<Performance, Worth> >
|
||||
{
|
||||
typedef pair<Performance, Worth> 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 <class EOT>
|
||||
static worth_type get_fitness(const EOT& _eo) { return _eo.worth(); }
|
||||
|
||||
template <class EOT>
|
||||
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 Fitness, class Traits = fitness_traits<Fitness> >
|
||||
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<Fitness, Traits>& other) const
|
||||
{
|
||||
return !Traits::is_better(other, *this);
|
||||
}
|
||||
|
||||
bool operator>(const EO<Fitness, Traits>& 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 EOT> class eoPop;
|
||||
|
||||
template <class EOT>
|
||||
void exponential_scaling(eoPop<EOT>& _pop)
|
||||
{
|
||||
for (unsigned i = 0; i < _pop.size(); ++i)
|
||||
{ // change minimimization into maximization
|
||||
_pop[i].worth(exp(-_pop[i].performance()));
|
||||
}
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
class eoPerf2Worth /* : public eoUF<eoPop<EOT>&, void> */
|
||||
{
|
||||
public :
|
||||
virtual void operator()(eoPop<EOT>& _pop)
|
||||
{
|
||||
return exponential_scaling(_pop);
|
||||
}
|
||||
};
|
||||
|
||||
/* end eoPerf2Worth.h */
|
||||
|
||||
|
||||
/* eoPop.h */
|
||||
|
||||
template <class EOT>
|
||||
class eoPop : public vector<EOT>
|
||||
{
|
||||
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<EOT>());
|
||||
}
|
||||
|
||||
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<EOT>& _p2w)
|
||||
{
|
||||
p2w = &_p2w;
|
||||
}
|
||||
|
||||
void setPerf2Worth(eoPerf2Worth<EOT>* _p2w)
|
||||
{
|
||||
p2w = _p2w;
|
||||
}
|
||||
|
||||
eoPerf2Worth<EOT>* getPerf2Worth() { return p2w; }
|
||||
|
||||
void swap(eoPop<EOT>& other)
|
||||
{
|
||||
vector<EOT>::swap(other);
|
||||
eoPerf2Worth<EOT>* tmp = p2w;
|
||||
p2w = other.p2w;
|
||||
other.p2w = tmp;
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
// a pointer as it can be emtpy
|
||||
eoPerf2Worth<EOT>* p2w;
|
||||
};
|
||||
|
||||
// need this one to be able to swap the members as well...
|
||||
template <class EOT>
|
||||
void swap(eoPop<EOT>& _p1, eoPop<EOT>& _p2)
|
||||
{
|
||||
_p1.swap(_p2);
|
||||
}
|
||||
|
||||
/* end eoPop.h */
|
||||
|
||||
/* main and test */
|
||||
|
||||
template <class EOT>
|
||||
void algo(eoPop<EOT>& _pop)
|
||||
{
|
||||
eoPop<EOT> 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<minimization> 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<double> simple_eo;
|
||||
typedef EO<pair<double, double> > 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<simple_eo> 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<scaled_eo> perf2worth;
|
||||
eoPop<scaled_eo> 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;
|
||||
}
|
||||
}
|
||||
16
test/eo/real_value.h
Executable file
16
test/eo/real_value.h
Executable file
|
|
@ -0,0 +1,16 @@
|
|||
#include <vector>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/** Just a simple function that takes an eoEsBase<double> and sets the fitnes
|
||||
to sphere
|
||||
@param _ind vector<double>
|
||||
*/
|
||||
|
||||
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/_ind.size();
|
||||
}
|
||||
9
test/eo/run_tests
Executable file
9
test/eo/run_tests
Executable file
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/sh
|
||||
|
||||
echo "Testing -h"
|
||||
./t-eoCheckpointing -h
|
||||
|
||||
echo "Finished"
|
||||
|
||||
#TODO test if an error occured
|
||||
echo "Ok"
|
||||
104
test/eo/t-MGE-control.cpp
Executable file
104
test/eo/t-MGE-control.cpp
Executable file
|
|
@ -0,0 +1,104 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoMGE.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#ifndef __GNUG__
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif // __GNUG__
|
||||
|
||||
#include <paradiseo/eo/ga/eoBitOp.h>
|
||||
|
||||
#include "RoyalRoad.h"
|
||||
|
||||
// Viri
|
||||
#include "VirusOp.h"
|
||||
#include "eoVirus.h"
|
||||
#include "eoInitVirus.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoVirus<float> Chrom;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int main()
|
||||
{
|
||||
const unsigned POP_SIZE = 10, CHROM_SIZE = 12;
|
||||
unsigned i;
|
||||
eoBooleanGenerator gen;
|
||||
|
||||
// the populations:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
RoyalRoad<Chrom> rr( 8 );
|
||||
eoEvalFuncCounter<Chrom> eval( rr );
|
||||
|
||||
eoInitVirus<float> 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<Chrom> lottery(0.9 );
|
||||
|
||||
// breeder
|
||||
eoOneBitFlip<Chrom> vm;
|
||||
eoUBitXover<Chrom> xover;
|
||||
eoProportionalOp<Chrom> propSel;
|
||||
eoGeneralBreeder<Chrom> breeder( lottery, propSel );
|
||||
propSel.add(vm, 0.2);
|
||||
propSel.add(xover, 0.8);
|
||||
|
||||
// Replace a single one
|
||||
eoCommaReplacement<Chrom> replace;
|
||||
|
||||
// Terminators
|
||||
eoGenContinue<Chrom> continuator1(10);
|
||||
eoFitContinue<Chrom> continuator2(CHROM_SIZE);
|
||||
eoCombinedContinue<Chrom> continuator(continuator1);
|
||||
continuator.add( continuator2 );
|
||||
eoCheckPoint<Chrom> checkpoint(continuator);
|
||||
eoStdoutMonitor monitor;
|
||||
checkpoint.add(monitor);
|
||||
eoSecondMomentStats<Chrom> stats;
|
||||
eoPopStat<Chrom> dumper( 10 );
|
||||
monitor.add(stats);
|
||||
checkpoint.add(dumper);
|
||||
checkpoint.add(stats);
|
||||
|
||||
// GA generation
|
||||
eoEasyEA<Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
109
test/eo/t-MGE.cpp
Executable file
109
test/eo/t-MGE.cpp
Executable file
|
|
@ -0,0 +1,109 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoMGE.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#ifndef __GNUG__
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif // __GNUG__
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/ga/eoBitOp.h>
|
||||
|
||||
#include "RoyalRoad.h"
|
||||
|
||||
// Viri
|
||||
#include "VirusOp.h"
|
||||
#include "eoVirus.h"
|
||||
#include "eoInitVirus.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoVirus<float> Chrom;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int main()
|
||||
{
|
||||
const unsigned POP_SIZE = 10, CHROM_SIZE = 12;
|
||||
unsigned i;
|
||||
eoBooleanGenerator gen;
|
||||
|
||||
// the populations:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
RoyalRoad<Chrom> rr( 8 );
|
||||
eoEvalFuncCounter<Chrom> eval( rr );
|
||||
|
||||
eoInitVirus<float> 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<Chrom> lottery(0.9 );
|
||||
|
||||
// breeder
|
||||
VirusMutation<float> vm;
|
||||
VirusTransmission<float> vt;
|
||||
VirusBitFlip<float> vf;
|
||||
eoUBitXover<Chrom> xover;
|
||||
eoProportionalOp<Chrom> propSel;
|
||||
eoGeneralBreeder<Chrom> 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<Chrom> replace;
|
||||
|
||||
// Terminators
|
||||
eoGenContinue<Chrom> continuator1(10);
|
||||
eoFitContinue<Chrom> continuator2(CHROM_SIZE);
|
||||
eoCombinedContinue<Chrom> continuator(continuator1);
|
||||
continuator.add( continuator2);
|
||||
eoCheckPoint<Chrom> checkpoint(continuator);
|
||||
eoStdoutMonitor monitor;
|
||||
checkpoint.add(monitor);
|
||||
eoSecondMomentStats<Chrom> stats;
|
||||
eoPopStat<Chrom> dumper( 10 );
|
||||
monitor.add(stats);
|
||||
checkpoint.add(dumper);
|
||||
checkpoint.add(stats);
|
||||
|
||||
// GA generation
|
||||
eoEasyEA<Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
112
test/eo/t-MGE1bit.cpp
Executable file
112
test/eo/t-MGE1bit.cpp
Executable file
|
|
@ -0,0 +1,112 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoMGE.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#ifndef __GNUG__
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif // __GNUG__
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
//#include "ga/eoBitOp.h"
|
||||
#include "RoyalRoad.h"
|
||||
|
||||
// Viri
|
||||
#include "VirusOp.h"
|
||||
#include "eoVirus.h"
|
||||
#include "eoInitVirus.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoVirus<double> Chrom;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int main()
|
||||
{
|
||||
const unsigned POP_SIZE = 10, CHROM_SIZE = 12;
|
||||
unsigned i;
|
||||
eoBooleanGenerator gen;
|
||||
|
||||
// the populations:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
RoyalRoad<Chrom> rr( 8 );
|
||||
eoEvalFuncCounter<Chrom> eval( rr );
|
||||
|
||||
eoInitVirus1bit<double> 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<Chrom> lottery(0.9 );
|
||||
|
||||
// breeder
|
||||
VirusShiftMutation<double> vm;
|
||||
VirusTransmission<double> vt;
|
||||
VirusBitFlip<double> vf;
|
||||
eoUBitXover<Chrom> xover;
|
||||
eoProportionalOp<Chrom> propSel;
|
||||
eoGeneralBreeder<Chrom> 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<Chrom> replace;
|
||||
|
||||
// Terminators
|
||||
eoGenContinue<Chrom> continuator1(10);
|
||||
eoFitContinue<Chrom> continuator2(CHROM_SIZE);
|
||||
eoCombinedContinue<Chrom> continuator(continuator1);
|
||||
continuator.add(continuator2);
|
||||
eoCheckPoint<Chrom> checkpoint(continuator);
|
||||
eoStdoutMonitor monitor;
|
||||
checkpoint.add(monitor);
|
||||
eoSecondMomentStats<Chrom> stats;
|
||||
eoPopStat<Chrom> dumper( 10 );
|
||||
monitor.add(stats);
|
||||
checkpoint.add(dumper);
|
||||
checkpoint.add(stats);
|
||||
|
||||
// GA generation
|
||||
eoEasyEA<Chrom> 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:
|
||||
14
test/eo/t-eo.cpp
Executable file
14
test/eo/t-eo.cpp
Executable file
|
|
@ -0,0 +1,14 @@
|
|||
#include <paradiseo/eo.h>
|
||||
|
||||
typedef EO<float> 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;
|
||||
}
|
||||
220
test/eo/t-eo2dVector.cc
Executable file
220
test/eo/t-eo2dVector.cc
Executable file
|
|
@ -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 <stdexcept>
|
||||
#include <paradiseo/eo/eo2dVector.h> // eo2dVector
|
||||
#include <paradiseo/eo/eoUniform.h> // Random generator
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef unsigned T;
|
||||
typedef double fitnessT;
|
||||
typedef eo2dVector<T,fitnessT> C;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
main()
|
||||
{
|
||||
{
|
||||
C c1;
|
||||
cout << "Default constructor: " << endl
|
||||
<< c1 << endl;
|
||||
}
|
||||
{
|
||||
C c1( 5,6,1 );
|
||||
cout << "Default constructor with values: " << endl
|
||||
<< c1 << endl;
|
||||
|
||||
}
|
||||
{
|
||||
eoUniform<T> 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<T> 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<T> 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<T> 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<T> 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<T> 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<T> 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<T> 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
127
test/eo/t-eoCMAES.cpp
Executable file
127
test/eo/t-eoCMAES.cpp
Executable file
|
|
@ -0,0 +1,127 @@
|
|||
#include <iostream>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
/*
|
||||
#include <paradiseo/eo/eoScalarFitness.h>
|
||||
#include <paradiseo/eo/eoVector.h>
|
||||
#include <paradiseo/eo/eoPop.h>
|
||||
#include <paradiseo/eo/utils/eoParser.h>
|
||||
#include <paradiseo/eo/utils/eoCheckPoint.h>
|
||||
#include <paradiseo/eo/eoEvalFuncPtr.h>
|
||||
|
||||
#include <paradiseo/eo/eoGenContinue.h>
|
||||
#include <paradiseo/eo/eoFitContinue.h>
|
||||
#include <paradiseo/eo/utils/eoStdoutMonitor.h>
|
||||
#include <paradiseo/eo/utils/eoStat.h>
|
||||
#include <paradiseo/eo/utils/eoTimedMonitor.h>
|
||||
|
||||
#include <paradiseo/eo/eoMergeReduce.h>
|
||||
#include <paradiseo/eo/eoEasyEA.h>
|
||||
|
||||
#include <paradiseo/eo/es/CMAState.h>
|
||||
#include <paradiseo/eo/es/CMAParams.h>
|
||||
#include <paradiseo/eo/es/eoCMAInit.h>
|
||||
#include <paradiseo/eo/es/eoCMABreed.h>
|
||||
*/
|
||||
|
||||
using namespace eo;
|
||||
using namespace std;
|
||||
|
||||
typedef eoMinimizingFitness FitT;
|
||||
typedef eoVector<FitT, double> EoType;
|
||||
|
||||
double sqr(double x) { return x*x; }
|
||||
|
||||
eoValueParam<int> evals(0,"Function Evals","Number of Evaluations");
|
||||
|
||||
double f_sphere(const vector<double>& 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<double>& 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<double> initial_point(params.n, 0.0);
|
||||
|
||||
CMAState state(params, initial_point);
|
||||
|
||||
if (parser.userNeedsHelp())
|
||||
{
|
||||
parser.printHelp(std::cout);
|
||||
return 1;
|
||||
}
|
||||
|
||||
eoCMAInit<FitT> init(state);
|
||||
|
||||
eoPop<EoType> pop(params.mu, init);
|
||||
|
||||
eoEvalFuncPtr<EoType, double, const vector<double>&> eval( f_rosen );
|
||||
|
||||
eoCMABreed<FitT> breed(state, params.lambda);
|
||||
|
||||
for (unsigned i = 0; i < pop.size(); ++i) {
|
||||
eval(pop[i]);
|
||||
}
|
||||
|
||||
eoCommaReplacement<EoType> comma;
|
||||
|
||||
eoGenContinue<EoType> gen(params.maxgen);
|
||||
eoFitContinue<EoType> fit(1e-10);
|
||||
|
||||
eoCheckPoint<EoType> checkpoint(gen);
|
||||
checkpoint.add(fit);
|
||||
|
||||
eoBestFitnessStat<EoType> 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<EoType> 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;
|
||||
}
|
||||
177
test/eo/t-eoCheckpointing.cpp
Executable file
177
test/eo/t-eoCheckpointing.cpp
Executable file
|
|
@ -0,0 +1,177 @@
|
|||
// to avoid long name warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <stdexcept> // runtime_error
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
// general
|
||||
/*
|
||||
#include <paradiseo/eo/utils/eoRNG.h> // Random number generators
|
||||
#include <paradiseo/eo/ga.h>
|
||||
#include <paradiseo/eo/utils/eoParser.h>
|
||||
#include <paradiseo/eo/utils/eoState.h>
|
||||
#include <paradiseo/eo/eoGenContinue.h>
|
||||
|
||||
// include package checkpointing
|
||||
#include <paradiseo/eo/utils/checkpointing>
|
||||
*/
|
||||
|
||||
struct Dummy : public EO<double>
|
||||
{
|
||||
typedef double Type;
|
||||
};
|
||||
|
||||
|
||||
struct eoDummyPop : public eoPop<Dummy>
|
||||
{
|
||||
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<float> Chrom;
|
||||
|
||||
eoParser parser(argc, argv);
|
||||
|
||||
// Define Parameters
|
||||
eoValueParam<double> rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit");
|
||||
eoValueParam<double> factor(0.99, "mutationFactor", "Decrease factor for mutation rate");
|
||||
eoValueParam<uint32_t> seed(time(0), "seed", "Random number seed");
|
||||
eoValueParam<std::string> load_name("", "Load","Load",'L');
|
||||
eoValueParam<std::string> 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<EoType> genTerm(5); // run for 5 generations
|
||||
|
||||
eoCheckPoint<EoType> checkpoint(genTerm);
|
||||
// The algorithm will now quit after five generations
|
||||
|
||||
// Create a counter parameter
|
||||
eoValueParam<unsigned> 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<unsigned> 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<EoType> 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;
|
||||
}
|
||||
|
||||
}
|
||||
88
test/eo/t-eoDualFitness.cpp
Executable file
88
test/eo/t-eoDualFitness.cpp
Executable file
|
|
@ -0,0 +1,88 @@
|
|||
#include <utility>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
#include <paradiseo/eo/utils/eoStat.h>
|
||||
|
||||
typedef eoVector<eoDualFitness<double,eoMinimizingFitness>,double> DualVector;
|
||||
|
||||
template<class EOT>
|
||||
class DualSphere : public eoEvalFunc<EOT>
|
||||
{
|
||||
public:
|
||||
virtual void operator()( EOT & x )
|
||||
{
|
||||
if( x.invalid() ) { return; }
|
||||
|
||||
double sum = 0;
|
||||
int sign = 1;
|
||||
for( unsigned int i=0, s=x.size(); i<s; ++i ) {
|
||||
sum += x[i] * x[i];
|
||||
sign *= x[i]<0 ? -1 : 1;
|
||||
}
|
||||
|
||||
x.fitness( std::make_pair( sum, sign>0 ? true : false ) );
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
double test( eoPop<DualVector>& pop, double target_value )
|
||||
{
|
||||
DualSphere<DualVector> eval;
|
||||
|
||||
eoPopLoopEval<DualVector> pop_eval(eval);
|
||||
|
||||
pop_eval(pop,pop);
|
||||
|
||||
eoInterquartileRangeStat<DualVector> 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<DualVector> 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<double> normal(1,rng);
|
||||
eoInitFixedLength<DualVector> init_N(2, normal);
|
||||
pop = eoPop<DualVector>( 1000000, init_N );
|
||||
double iqr = test(pop, 1.09);
|
||||
if( iqr < 1.08 || iqr > 1.11 ) {
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
150
test/eo/t-eoESAll.cpp
Executable file
150
test/eo/t-eoESAll.cpp
Executable file
|
|
@ -0,0 +1,150 @@
|
|||
// Program to test several EO-ES features
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
#include <ctime>
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <crtdbg.h>
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
// representation specific
|
||||
//#include <paradiseo/eo/es/make_es.h>
|
||||
|
||||
#include "real_value.h" // the sphere fitness
|
||||
|
||||
// Now the main
|
||||
///////////////
|
||||
typedef eoMinimizingFitness FitT;
|
||||
|
||||
template <class EOT>
|
||||
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<bool>& simpleParam = parser.getORcreateParam(true, "Isotropic",
|
||||
"Isotropic self-adaptive mutation",
|
||||
'i', "ES mutation");
|
||||
eoValueParam<bool>& stdevsParam = parser.getORcreateParam(false, "Stdev",
|
||||
"One self-adaptive stDev per variable",
|
||||
's', "ES mutation");
|
||||
eoValueParam<bool>& 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<FitT>(), parser, state);
|
||||
}
|
||||
else if (stdevsParam.value() == false)
|
||||
{
|
||||
std::cout << "Using eoEsSimple" << std::endl;
|
||||
runAlgorithm(eoEsSimple<FitT>(), parser, state);
|
||||
}
|
||||
else if (corrParam.value() == false)
|
||||
{
|
||||
std::cout << "Using eoEsStdev" << std::endl;
|
||||
runAlgorithm(eoEsStdev<FitT>(), parser, state);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Using eoEsFull" << std::endl;
|
||||
runAlgorithm(eoEsFull<FitT>(), 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 <class EOT>
|
||||
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<EOT, double, const std::vector<double>&> mainEval( real_value );
|
||||
eoEvalFuncCounter<EOT> eval(mainEval);
|
||||
|
||||
// the genotype - through a genotype initializer
|
||||
eoRealInitBounded<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);
|
||||
apply<EOT>(eval, pop);
|
||||
|
||||
// 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
|
||||
///////
|
||||
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;
|
||||
}
|
||||
180
test/eo/t-eoESFull.cpp
Executable file
180
test/eo/t-eoESFull.cpp
Executable file
|
|
@ -0,0 +1,180 @@
|
|||
// Program to test several EO-ES features
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
#include <time.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
// representation specific
|
||||
#include <paradiseo/eo/es.h>
|
||||
|
||||
#include "real_value.h" // the sphere fitness
|
||||
|
||||
// Now the main
|
||||
///////////////
|
||||
typedef eoMinimizingFitness FitT;
|
||||
|
||||
template <class EOT>
|
||||
void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam<string> _load_name);
|
||||
|
||||
int main_function(int argc, char *argv[])
|
||||
{
|
||||
// Create the command-line parser
|
||||
eoParser parser( argc, argv, "Basic EA for vector<float> with adaptive mutations");
|
||||
|
||||
// Define Parameters and load them
|
||||
eoValueParam<uint32_t>& seed = parser.createParam(static_cast<uint32_t>(time(0)),
|
||||
"seed", "Random number seed");
|
||||
eoValueParam<string>& load_name = parser.createParam(string(), "Load","Load a state file",'L');
|
||||
eoValueParam<string>& save_name = parser.createParam(string(), "Save","Saves a state file",'S');
|
||||
eoValueParam<bool>& stdevs = parser.createParam(false, "Stdev", "Use adaptive mutation rates", 's');
|
||||
eoValueParam<bool>& corr = parser.createParam(false, "Correl", "Use correlated mutations", 'c');
|
||||
eoValueParam<unsigned>& chromSize = parser.createParam(unsigned(50), "ChromSize", "Number of chromosomes", 'n');
|
||||
eoValueParam<double>& minimum = parser.createParam(-1.0, "Min", "Minimum for Objective Variables", 'l');
|
||||
eoValueParam<double>& 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<FitT>() ,parser, state, bounds, load_name);
|
||||
}
|
||||
else if (corr.value() == true)
|
||||
{
|
||||
runAlgorithm(eoEsFull<FitT>(),parser, state, bounds, load_name);
|
||||
}
|
||||
else
|
||||
{
|
||||
runAlgorithm(eoEsStdev<FitT>(), 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 <class EOT>
|
||||
void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam<string> _load_name)
|
||||
{
|
||||
// evaluation
|
||||
eoEvalFuncPtr<EOT, double, const vector<double>&> eval( real_value );
|
||||
|
||||
// population parameters, unfortunately these can not be altered in the state file
|
||||
eoValueParam<unsigned> mu = _parser.createParam(unsigned(7), "mu","Size of the population");
|
||||
eoValueParam<double>lambda_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<EOT> init(_bounds);
|
||||
|
||||
// State takes ownership of pop because it needs to save it in caller
|
||||
eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>(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<EOT>(eval, pop);
|
||||
}
|
||||
|
||||
// Ok, time to set up the algorithm
|
||||
// Proxy for the mutation parameters
|
||||
eoEsMutationInit mutateInit(_parser);
|
||||
|
||||
eoEsMutate<EOT> mutate(mutateInit, _bounds);
|
||||
|
||||
// monitoring, statistics etc.
|
||||
eoAverageStat<EOT> average;
|
||||
eoStdoutMonitor monitor;
|
||||
|
||||
monitor.add(average);
|
||||
|
||||
eoGenContinue<EOT> cnt(100);
|
||||
eoCheckPoint<EOT> checkpoint(cnt);
|
||||
checkpoint.add(monitor);
|
||||
checkpoint.add(average);
|
||||
|
||||
// only mutation (== with rate 1.0)
|
||||
eoMonGenOp<EOT> op(mutate);
|
||||
|
||||
// the selection: sequential selection
|
||||
eoSequentialSelect<EOT> select;
|
||||
// the general breeder (lambda is a rate -> true)
|
||||
eoGeneralBreeder<EOT> breed(select, op, lambda_rate.value(), true);
|
||||
|
||||
// the replacement - hard-coded Comma replacement
|
||||
eoCommaReplacement<EOT> replace;
|
||||
|
||||
// now the eoEasyEA
|
||||
eoEasyEA<EOT> es(checkpoint, eval, breed, replace);
|
||||
|
||||
es(pop);
|
||||
|
||||
pop.sort();
|
||||
std::cout << "Final population\n" << pop << std::endl;
|
||||
|
||||
}
|
||||
74
test/eo/t-eoEasyEA.cpp
Executable file
74
test/eo/t-eoEasyEA.cpp
Executable file
|
|
@ -0,0 +1,74 @@
|
|||
#ifndef __GNUG__
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif // __GNUG__
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
#include "binary_value.h"
|
||||
|
||||
typedef eoBin<float> Chrom;
|
||||
|
||||
main()
|
||||
{
|
||||
const unsigned POP_SIZE = 8, CHROM_SIZE = 16;
|
||||
unsigned i;
|
||||
|
||||
// a chromosome randomizer
|
||||
eoBinRandom<Chrom> random;
|
||||
// the populations:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Chrom> 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<Chrom> lottery;
|
||||
|
||||
// breeder
|
||||
eoBinBitFlip<Chrom> bitflip;
|
||||
eoBinCrossover<Chrom> xover;
|
||||
eoProportionalOpSel<Chrom> propSel;
|
||||
eoBreeder<Chrom> breeder( propSel );
|
||||
propSel.addOp(bitflip, 0.25);
|
||||
propSel.addOp(xover, 0.75);
|
||||
|
||||
// replacement
|
||||
eoInclusion<Chrom> inclusion;
|
||||
|
||||
// Terminators
|
||||
eoFitTerm<Chrom> term( pow(2.0, CHROM_SIZE), 1 );
|
||||
|
||||
// GA generation
|
||||
eoEasyEA<Chrom> 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;
|
||||
}
|
||||
102
test/eo/t-eoEasyPSO.cpp
Executable file
102
test/eo/t-eoEasyPSO.cpp
Executable file
|
|
@ -0,0 +1,102 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoEasyPSO.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef __GNUG__
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif // __GNUG__
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
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<Particle> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Particle, double, const Particle& > 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<Particle> topology(NEIGHBORHOOD_SIZE);
|
||||
|
||||
// the full initializer
|
||||
eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop);
|
||||
init();
|
||||
|
||||
|
||||
// bounds
|
||||
eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5);
|
||||
|
||||
// velocity
|
||||
eoStandardVelocity <Particle> velocity (topology,1,1.6,2,bnds);
|
||||
|
||||
// flight
|
||||
eoStandardFlight <Particle> flight;
|
||||
|
||||
// Terminators
|
||||
eoGenContinue <Particle> genCont1 (50);
|
||||
eoGenContinue <Particle> genCont2 (50);
|
||||
|
||||
// PS flight
|
||||
eoEasyPSO<Particle> pso1(genCont1, eval, velocity, flight);
|
||||
|
||||
eoEasyPSO<Particle> 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;
|
||||
}
|
||||
78
test/eo/t-eoEvalKeepBest.cpp
Executable file
78
test/eo/t-eoEvalKeepBest.cpp
Executable file
|
|
@ -0,0 +1,78 @@
|
|||
#include <iostream>
|
||||
|
||||
#include <paradiseo/eo/es/make_real.h>
|
||||
#include <paradiseo/eo/apply.h>
|
||||
#include <paradiseo/eo/eoEvalKeepBest.h>
|
||||
#include "real_value.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
typedef eoReal<eoMinimizingFitness> 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<EOT, double, const std::vector<double>&>
|
||||
main_eval( real_value ); // use a function defined in real_value.h
|
||||
|
||||
// wrap the evaluation function in a call counter
|
||||
eoEvalFuncCounter<EOT> eval_counter(main_eval);
|
||||
|
||||
// the genotype - through a genotype initializer
|
||||
eoRealInitBounded<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_counter);
|
||||
|
||||
// things that are called at each generation
|
||||
eoCheckPoint<EOT> & checkpoint = make_checkpoint(parser, state, eval_counter, term);
|
||||
|
||||
// wrap the evaluator in another one that will keep the best individual
|
||||
// evaluated so far
|
||||
eoEvalKeepBest<EOT> eval_keep( eval_counter );
|
||||
|
||||
// algorithm
|
||||
eoAlgo<EOT>& 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<EOT>(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;
|
||||
}
|
||||
76
test/eo/t-eoExtendedVelocity.cpp
Executable file
76
test/eo/t-eoExtendedVelocity.cpp
Executable file
|
|
@ -0,0 +1,76 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoExtendedVelocity.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
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<Particle> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Particle, double, const Particle& > 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<Particle> topology(NEIGHBORHOOD_SIZE);
|
||||
eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop);
|
||||
init();
|
||||
|
||||
// velocity
|
||||
eoExtendedVelocity <Particle> 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;
|
||||
}
|
||||
135
test/eo/t-eoExternalEO.cpp
Executable file
135
test/eo/t-eoExternalEO.cpp
Executable file
|
|
@ -0,0 +1,135 @@
|
|||
// to avoid long name warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <stdexcept> // runtime_error
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
/*
|
||||
#include <paradiseo/eo/eoEvalFuncPtr.h>
|
||||
#include <paradiseo/eo/other/external_eo>
|
||||
#include <paradiseo/eo/utils/eoRNG.h>
|
||||
*/
|
||||
|
||||
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<int>(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<UserDefStruct::Enum>(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<float, External> EoType;
|
||||
|
||||
eoExternalInit<FitnessType, External> init(RandomStruct);
|
||||
eoExternalMonOp<FitnessType, External> mutate(UserDefMutate);
|
||||
eoExternalBinOp<FitnessType, External> cross1(UserDefBinCrossover);
|
||||
eoExternalQuadOp<FitnessType, External> cross2(UserDefQuadCrossover);
|
||||
|
||||
// eoExternalEvalFunc<FitnessType, External> 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);
|
||||
|
||||
}
|
||||
105
test/eo/t-eoFitnessAssembled.cpp
Executable file
105
test/eo/t-eoFitnessAssembled.cpp
Executable file
|
|
@ -0,0 +1,105 @@
|
|||
// -*- 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 <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
//#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 << "A<B: " << (A<B) << std::endl;
|
||||
std::cout << "A>B: " << (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;
|
||||
|
||||
}
|
||||
175
test/eo/t-eoFitnessAssembledEA.cpp
Executable file
175
test/eo/t-eoFitnessAssembledEA.cpp
Executable file
|
|
@ -0,0 +1,175 @@
|
|||
// -*- 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 <config.h>
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
|
||||
// General eo includes
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
#include <paradiseo/eo/utils/eoRealVectorBounds.h> // The real bounds (not yet in general eo include)
|
||||
|
||||
// Representation dependent includes and typedefs
|
||||
#include <paradiseo/eo/es/eoReal.h> // Definition of representation
|
||||
#include <paradiseo/eo/es/eoRealInitBounded.h> // Uniformly initializes real vector in bounds
|
||||
#include <paradiseo/eo/es/make_genotype_real.h> // Initialization of a genotype
|
||||
#include <paradiseo/eo/eoEvalFunc.h> // Base class for fitness evaluation
|
||||
#include <paradiseo/eo/es/make_op_real.h> // Variation operators using standard Real operators
|
||||
#include <paradiseo/eo/eoScalarFitnessAssembled.h> // The fitness class
|
||||
typedef eoReal<eoAssembledMinimizingFitness> Indi;
|
||||
|
||||
// Representation independent modules
|
||||
#include <paradiseo/eo/do/make_pop.h> // Initialization of population
|
||||
#include <paradiseo/eo/do/make_continue.h> // The stopping criterion
|
||||
#include <paradiseo/eo/do/make_checkpoint_assembled.h> // Outputs (stats, population dumps, ...)
|
||||
#include <paradiseo/eo/do/make_algo_scalar.h> // Evolution engine (selection and replacement)
|
||||
#include <paradiseo/eo/do/make_run.h> // simple call to the algo.stays there for consistency reasons
|
||||
|
||||
// Define a fitness class
|
||||
template <class EOT>
|
||||
class eoAssembledEvalFunc : public eoEvalFunc<EOT>{
|
||||
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<Indi> plainEval;
|
||||
// turn that object into an evaluation counter
|
||||
eoEvalFuncCounter<Indi> eval(plainEval);
|
||||
|
||||
// The genotype
|
||||
eoRealInitBounded<Indi>& init = do_make_genotype(parser, state, Indi() );
|
||||
|
||||
// The variation operators
|
||||
eoGenOp<Indi>& 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<Indi>& pop = do_make_pop(parser, state, init);
|
||||
|
||||
// stopping criteria
|
||||
eoContinue<Indi> & term = do_make_continue(parser, state, eval);
|
||||
// output
|
||||
eoCheckPoint<Indi> & checkpoint = do_make_checkpoint_assembled(parser, state, eval, term);
|
||||
// algorithm (need the operator!)
|
||||
eoAlgo<Indi>& 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<Indi>(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;
|
||||
|
||||
}
|
||||
48
test/eo/t-eoFunctor.cpp
Executable file
48
test/eo/t-eoFunctor.cpp
Executable file
|
|
@ -0,0 +1,48 @@
|
|||
#include <paradiseo/eo/eoInit.h>
|
||||
#include <paradiseo/eo/eoCounter.h>
|
||||
|
||||
void f(eoInit<int>& func)
|
||||
{
|
||||
int i;
|
||||
func(i);
|
||||
}
|
||||
|
||||
class Tester : public eoInit<int>
|
||||
{
|
||||
public :
|
||||
void operator()(int& i)
|
||||
{
|
||||
i=1;
|
||||
}
|
||||
};
|
||||
|
||||
#include <iostream>
|
||||
#include <paradiseo/eo/eoFixedLength.h>
|
||||
#include <paradiseo/eo/eoVariableLength.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(void)
|
||||
{
|
||||
Tester test;
|
||||
|
||||
eoFunctorStore store;
|
||||
|
||||
/// make a counter and store it in 'store'
|
||||
eoInit<int>& cntr = make_counter(functor_category(test), test, store);
|
||||
|
||||
eoUnaryFunctorCounter<eoInit<int> > cntr2(test);
|
||||
|
||||
f(cntr);
|
||||
f(cntr2);
|
||||
f(cntr2);
|
||||
f(test);
|
||||
|
||||
typedef eoVariableLength<double, int> EoType;
|
||||
EoType eo;
|
||||
|
||||
eo.push_back(1);
|
||||
eo.push_back(2);
|
||||
|
||||
return 1;
|
||||
}
|
||||
72
test/eo/t-eoGA.cpp
Executable file
72
test/eo/t-eoGA.cpp
Executable file
|
|
@ -0,0 +1,72 @@
|
|||
#include <iostream>
|
||||
|
||||
#include <paradiseo/eo/ga/make_ga.h>
|
||||
#include <paradiseo/eo/eoEvalFuncPtr.h>
|
||||
#include "binary_value.h"
|
||||
#include <paradiseo/eo/apply.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
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, double> 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<EOT>(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;
|
||||
}
|
||||
}
|
||||
427
test/eo/t-eoGenOp.cpp
Executable file
427
test/eo/t-eoGenOp.cpp
Executable file
|
|
@ -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 <sstream>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/eoPopulator.h>
|
||||
#include <paradiseo/eo/eoOpContainer.h>
|
||||
|
||||
struct Dummy : public EO<double>
|
||||
{
|
||||
Dummy(std::string _s="") : s(_s) {}
|
||||
|
||||
void printOn(std::ostream & _os) const
|
||||
{
|
||||
EO<double>::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<EOT>
|
||||
{
|
||||
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<EOT>
|
||||
{
|
||||
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<EOT>
|
||||
{
|
||||
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<EOT>
|
||||
{
|
||||
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<EOT> // :-)
|
||||
{
|
||||
public:
|
||||
unsigned max_production(void) { return 3; }
|
||||
|
||||
void apply(eoPopulator<EOT>& _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<EOT> // :-)
|
||||
{
|
||||
public:
|
||||
unsigned max_production(void) { return 1; }
|
||||
|
||||
void apply(eoPopulator<EOT>& _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<EOT> // :-)
|
||||
{
|
||||
public:
|
||||
unsigned max_production(void) { return 3; }
|
||||
|
||||
void apply(eoPopulator<EOT>& _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<Dummy> & _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<unsigned int> parentSizeParam(
|
||||
parser.createParam(unsigned(10), "parentSize", "Parent size",'P'));
|
||||
pSize = parentSizeParam.value(); // global variable
|
||||
|
||||
eoValueParam<uint32_t> 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<EOT> select;
|
||||
// and a recognizable selector for testing the inbedded selector mechanism
|
||||
eoBestSelect<EOT> selectBest;
|
||||
|
||||
// proportional selection between quad and bin
|
||||
// so we either do a quad or a bin
|
||||
eoProportionalOp<EOT> pOp;
|
||||
pOp.add(quad, 0.1);
|
||||
pOp.add(bin, 0.1);
|
||||
|
||||
// sequential selection between pOp and mon
|
||||
eoSequentialOp<EOT> sOp;
|
||||
sOp.add(pOp, 0.9);
|
||||
sOp.add(mon, 0.1);
|
||||
|
||||
// with one2three op
|
||||
eoSequentialOp<EOT> sOp2;
|
||||
sOp2.add(o2t, 1);
|
||||
// sOp2.add(quad, 1);
|
||||
|
||||
// with three2three op
|
||||
eoSequentialOp<EOT> sOp3;
|
||||
sOp3.add(t2t, 1);
|
||||
|
||||
// eoSequentialOp<EOT> 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<EOT> sOpQuadPlusMon;
|
||||
sOpQuadPlusMon.add(quad, 1);
|
||||
sOpQuadPlusMon.add(mon, 1);
|
||||
|
||||
// this corresponds
|
||||
eoProportionalOp<EOT> pOpSAGLike;
|
||||
pOpSAGLike.add(sOpQuadPlusMon, 0.24);
|
||||
pOpSAGLike.add(quad, 0.56);
|
||||
pOpSAGLike.add(mon, 0.06);
|
||||
pOpSAGLike.add(clone, 0.14);
|
||||
|
||||
// init
|
||||
eoPop<EOT> pop;
|
||||
eoPop<EOT> 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<EOT> pSGAOp;
|
||||
pSGAOp.add(quad, 0.8);
|
||||
pSGAOp.add(quadclone, 0.2);
|
||||
// sequential selection between pSGAOp and mon
|
||||
eoSequentialOp<EOT> virtualSGA;
|
||||
virtualSGA.add(pSGAOp, 1.0);
|
||||
virtualSGA.add(mon, 0.3);
|
||||
|
||||
eoSeqPopulator<EOT> 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<EOT>::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<EOT> seqSelect;
|
||||
// select.init(); should be sorted out: is it the setup method???
|
||||
eoSelectivePopulator<EOT> 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<EOT> 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<EOT> 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<EOT> 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?
|
||||
|
||||
*/
|
||||
67
test/eo/t-eoIQRStat.cpp
Executable file
67
test/eo/t-eoIQRStat.cpp
Executable file
|
|
@ -0,0 +1,67 @@
|
|||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
#include <paradiseo/eo/utils/eoStat.h>
|
||||
|
||||
#include "real_value.h"
|
||||
|
||||
typedef eoReal<eoMinimizingFitness> realVec;
|
||||
|
||||
double test( eoPop<realVec>& pop, double target_value )
|
||||
{
|
||||
eoEvalFuncPtr<realVec, double, const std::vector<double>&> eval( real_value );
|
||||
|
||||
eoPopLoopEval<realVec> pop_eval(eval);
|
||||
|
||||
pop_eval(pop,pop);
|
||||
|
||||
eoInterquartileRangeStat<realVec> 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<realVec> 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<double> normal(1,rng);
|
||||
eoInitFixedLength<realVec> init_N(2, normal);
|
||||
pop = eoPop<realVec>( 1000000, init_N );
|
||||
double iqr = test(pop, 1.09);
|
||||
if( iqr < 1.08 || iqr > 1.11 ) {
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
68
test/eo/t-eoInitPermutation.cpp
Executable file
68
test/eo/t-eoInitPermutation.cpp
Executable file
|
|
@ -0,0 +1,68 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoInitPermutation.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
#include <paradiseo/eo/eoInt.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoInt<double> 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 <Chrom> random(CHROM_SIZE);
|
||||
|
||||
// the population:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
98
test/eo/t-eoInitVariableLength.cpp
Executable file
98
test/eo/t-eoInitVariableLength.cpp
Executable file
|
|
@ -0,0 +1,98 @@
|
|||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
// An adhoc atom type of our own
|
||||
class Quad : public std::vector<int>
|
||||
{
|
||||
public:
|
||||
// Just four times zero
|
||||
Quad() : std::vector<int>(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<n; ++i) {
|
||||
// use default int stream input
|
||||
is >> 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<n; ++i) {
|
||||
os << " " << q[i];
|
||||
}
|
||||
os << " ";
|
||||
return os;
|
||||
}
|
||||
|
||||
// An init for the atoms
|
||||
// Note that this mask the template passed to the eoInit
|
||||
class QuadInit : public eoInit<Quad>
|
||||
{
|
||||
public:
|
||||
// this is the API: an init modify the solution
|
||||
void operator()( Quad& q ) {
|
||||
for( unsigned int i=0, n=4; i<n; ++i) {
|
||||
// rng is the random number generator of EO
|
||||
q[i] = rng.random(10);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// The solution/individual type.
|
||||
// Just a proxy to an eoVector of atoms,
|
||||
// with a fitness as double.
|
||||
class QuadVec : public eoVector<double,Quad>
|
||||
{};
|
||||
|
||||
|
||||
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<QuadVec> 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<QuadVec> 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
|
||||
*/
|
||||
}
|
||||
24
test/eo/t-eoInt.cpp
Executable file
24
test/eo/t-eoInt.cpp
Executable file
|
|
@ -0,0 +1,24 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoInt.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/eoInt.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoInt<double> Chrom;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int main()
|
||||
{
|
||||
Chrom chrom1, chrom2;
|
||||
|
||||
std::cout << "chrom1 = " << chrom1 << std::endl
|
||||
<< "chrom2 = " << chrom2 << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
50
test/eo/t-eoLogger.cpp
Executable file
50
test/eo/t-eoLogger.cpp
Executable file
|
|
@ -0,0 +1,50 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoLogger.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
72
test/eo/t-eoOrderXover.cpp
Executable file
72
test/eo/t-eoOrderXover.cpp
Executable file
|
|
@ -0,0 +1,72 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoOrderXover.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <set>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/eoInt.h>
|
||||
#include <paradiseo/eo/eoOrderXover.h>
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoInt<int> Chrom;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Return true if the given chromosome corresponds to a permutation
|
||||
bool check_permutation(const Chrom& _chrom){
|
||||
unsigned size= _chrom.size();
|
||||
std::set<unsigned> 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 <Chrom> random(CHROM_SIZE);
|
||||
|
||||
// the population:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
//eoEvalFuncPtr<Chrom> 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<Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
148
test/eo/t-eoPBIL.cpp
Executable file
148
test/eo/t-eoPBIL.cpp
Executable file
|
|
@ -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 <config.h>
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/ga/make_ga.h>
|
||||
#include "binary_value.h"
|
||||
#include <paradiseo/eo/apply.h>
|
||||
#include <paradiseo/eo/ga/eoPBILDistrib.h>
|
||||
#include <paradiseo/eo/ga/eoPBILOrg.h>
|
||||
#include <paradiseo/eo/ga/eoPBILAdditive.h>
|
||||
#include <paradiseo/eo/eoSimpleEDA.h>
|
||||
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef eoBit<double> Indi;
|
||||
|
||||
// instanciating the outside subroutine that creates the distribution
|
||||
#include <paradiseo/eo/ga/make_PBILdistrib.h>
|
||||
eoPBILDistrib<Indi> & 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 <paradiseo/eo/ga/make_PBILupdate.h>
|
||||
eoDistribUpdater<Indi> & 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<Indi, double> mainEval( binary_value<Indi>);
|
||||
eoEvalFuncCounter<Indi> eval(mainEval);
|
||||
|
||||
// Construction of the distribution
|
||||
eoPBILDistrib<Indi> & distrib = make_PBILdistrib(parser, state, Indi());
|
||||
// and the update rule
|
||||
eoDistribUpdater<Indi> & update = make_PBILupdate(parser, state, Indi());
|
||||
|
||||
//// Now the representation-independent things
|
||||
//////////////////////////////////////////////
|
||||
|
||||
// stopping criteria
|
||||
eoContinue<Indi> & term = make_continue(parser, state, eval);
|
||||
// output
|
||||
eoCheckPoint<Indi> & 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<string>* ptDirNameParam = dynamic_cast<eoValueParam<string>*>(ptParam);
|
||||
if (!ptDirNameParam) // not found
|
||||
throw runtime_error("Parameter resDir not found where it was supposed to be");
|
||||
|
||||
// now create the snapshot monitor
|
||||
eoValueParam<bool>& 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<vector<double> >)
|
||||
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<Indi> 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;
|
||||
}
|
||||
}
|
||||
61
test/eo/t-eoParallel.cpp
Executable file
61
test/eo/t-eoParallel.cpp
Executable file
|
|
@ -0,0 +1,61 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoParallel.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <omp.h>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/es/make_real.h>
|
||||
//#include <paradiseo/eo/apply.h>
|
||||
#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;
|
||||
|
||||
#ifdef ENABLE_OPENMP
|
||||
|
||||
#pragma omp parallel
|
||||
{
|
||||
if ( 0 == omp_get_thread_num() ) //Warning: omp_get_thread_num doestn't work with pragma and required openMP
|
||||
{
|
||||
eo::log << "num of threads: " << omp_get_num_threads() << std::endl; //Warning: omp_get_num_threads doestn't work with pragma and required openMP
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
31
test/eo/t-eoParser.cpp
Executable file
31
test/eo/t-eoParser.cpp
Executable file
|
|
@ -0,0 +1,31 @@
|
|||
#include <iostream>
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
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;
|
||||
}
|
||||
53
test/eo/t-eoRNG.cpp
Executable file
53
test/eo/t-eoRNG.cpp
Executable file
|
|
@ -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 <config.h>
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/utils/eoRNG.h>
|
||||
|
||||
|
||||
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<num; ++i)
|
||||
sum += abs(rng.normal(sigma));
|
||||
sum /= double(num);
|
||||
if(sum > 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<num; ++i)
|
||||
sum += abs(rng.normal(mean, sigma) - mean);
|
||||
sum /= double(num);
|
||||
if(sum > 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:
|
||||
66
test/eo/t-eoRandom.cpp
Executable file
66
test/eo/t-eoRandom.cpp
Executable file
|
|
@ -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 <iostream> // cout
|
||||
#include <fstream> // ostrstream, istrstream
|
||||
#include <paradiseo/eo/utils/eoRndGenerators.h> // eoBin
|
||||
//#include <paradiseo/eo/eoNormal.h>
|
||||
//#include <paradiseo/eo/eoNegExp.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int main() {
|
||||
eoUniformGenerator<float> u1(-2.5,3.5);
|
||||
eoUniformGenerator<double> u2(0.003, 0.05 );
|
||||
eoUniformGenerator<unsigned long> u3( 10000U, 10000000U);
|
||||
|
||||
try
|
||||
{ // throws an error
|
||||
eoUniformGenerator<unsigned long> 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
|
||||
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
72
test/eo/t-eoReal.cpp
Executable file
72
test/eo/t-eoReal.cpp
Executable file
|
|
@ -0,0 +1,72 @@
|
|||
#include <iostream>
|
||||
|
||||
#include <paradiseo/eo/es/make_real.h>
|
||||
#include "real_value.h"
|
||||
#include <paradiseo/eo/apply.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
typedef eoReal<eoMinimizingFitness> 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, double, const std::vector<double>&>
|
||||
mainEval( real_value );
|
||||
eoEvalFuncCounter<EOT> eval(mainEval);
|
||||
|
||||
// the genotype - through a genotype initializer
|
||||
eoRealInitBounded<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>& 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<EOT>(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;
|
||||
}
|
||||
}
|
||||
223
test/eo/t-eoReplacement.cpp
Executable file
223
test/eo/t-eoReplacement.cpp
Executable file
|
|
@ -0,0 +1,223 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
|
||||
// to avoid long name warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <stdexcept> // runtime_error
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// tt.cpp:
|
||||
//
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
// general
|
||||
#include <paradiseo/eo.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
struct Dummy : public EO<double>
|
||||
{
|
||||
typedef double Type;
|
||||
void printOn(std::ostream & _os) const
|
||||
{
|
||||
_os << " - ";
|
||||
EO<double>::printOn(_os);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct eoDummyPop : public eoPop<Dummy>
|
||||
{
|
||||
public :
|
||||
eoDummyPop(int s=0) { resize(s); }
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int the_main(int argc, char **argv)
|
||||
{
|
||||
eoParser parser(argc, argv);
|
||||
eoValueParam<unsigned int> parentSizeParam(10, "parentSize", "Parent size",'P');
|
||||
parser.processParam( parentSizeParam );
|
||||
unsigned int pSize = parentSizeParam.value();
|
||||
|
||||
eoValueParam<unsigned int> offsrpringSizeParam(10, "offsrpringSize", "Offsrpring size",'O');
|
||||
parser.processParam( offsrpringSizeParam );
|
||||
unsigned int oSize = offsrpringSizeParam.value();
|
||||
|
||||
eoValueParam<unsigned int> tournamentSizeParam(2, "tournamentSize", "Deterministic tournament size",'T');
|
||||
parser.processParam( tournamentSizeParam );
|
||||
unsigned int tSize = tournamentSizeParam.value();
|
||||
|
||||
eoValueParam<double> tournamentRateParam(0.75, "tournamentRate", "Stochastic tournament rate",'R');
|
||||
parser.processParam( tournamentRateParam );
|
||||
double tRate = tournamentRateParam.value();
|
||||
|
||||
eoValueParam<double> sParentsElitismRateParam(0.1, "sParentsElitismRateParam", "Strong elitism rate for parents",'E');
|
||||
parser.processParam( sParentsElitismRateParam );
|
||||
double sParentsElitismRate = sParentsElitismRateParam.value();
|
||||
|
||||
eoValueParam<double> sParentsEugenismRateParam(0, "sParentsEugenismRateParam", "Strong Eugenism rate",'e');
|
||||
parser.processParam( sParentsEugenismRateParam );
|
||||
double sParentsEugenismRate = sParentsEugenismRateParam.value();
|
||||
|
||||
eoValueParam<double> sOffspringElitismRateParam(0, "sOffspringElitismRateParam", "Strong elitism rate for parents",'E');
|
||||
parser.processParam( sOffspringElitismRateParam );
|
||||
double sOffspringElitismRate = sOffspringElitismRateParam.value();
|
||||
|
||||
eoValueParam<double> 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<pSize; i++)
|
||||
orgParents[i].fitness(2*i+1);
|
||||
for (i=0; i<oSize; i++)
|
||||
orgOffspring[i].fitness(2*i);
|
||||
|
||||
std::cout << "Initial parents (odd)\n" << orgParents << "\n And initial offsprings (even)\n" << orgOffspring << std::endl;
|
||||
|
||||
// now the ones we're going to play with
|
||||
eoDummyPop parents(0);
|
||||
eoDummyPop offspring(0);
|
||||
|
||||
// the replacement procedures under test
|
||||
eoGenerationalReplacement<Dummy> genReplace;
|
||||
eoPlusReplacement<Dummy> plusReplace;
|
||||
eoEPReplacement<Dummy> epReplace(tSize);
|
||||
eoCommaReplacement<Dummy> commaReplace;
|
||||
eoWeakElitistReplacement<Dummy> weakElitistReplace(commaReplace);
|
||||
// the SSGA replacements
|
||||
eoSSGAWorseReplacement<Dummy> ssgaWorseReplace;
|
||||
eoSSGADetTournamentReplacement<Dummy> ssgaDTReplace(tSize);
|
||||
eoSSGAStochTournamentReplacement<Dummy> 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<Dummy> 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;
|
||||
}
|
||||
|
||||
}
|
||||
67
test/eo/t-eoRingTopology.cpp
Executable file
67
test/eo/t-eoRingTopology.cpp
Executable file
|
|
@ -0,0 +1,67 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoRingTopology.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
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<Indi, double, const Indi& > 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<Indi> topology(NEIGHBORHOOD_SIZE);
|
||||
topology.setup(pop);
|
||||
std::cout<<"\n\n\nPopulation :\n\n"<<pop;
|
||||
std::cout<<"\n\nNeighborhood :\n\n";
|
||||
topology.printOn();
|
||||
int k = NEIGHBORHOOD_SIZE/2;
|
||||
for(unsigned i=0;i<pop.size();i++)
|
||||
{
|
||||
std::cout<<"\nBetween : ";
|
||||
for(unsigned j=0;j<NEIGHBORHOOD_SIZE;j++)
|
||||
std::cout<<"\n"<<pop[((pop.size()+i-k+j)%pop.size())];
|
||||
std::cout<<"\nThe best is : \n"<<topology.best(i)<<"\n";
|
||||
}
|
||||
std::cout<<"\n\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
try
|
||||
{
|
||||
main_function(argc, argv);
|
||||
}
|
||||
catch(std::exception& e)
|
||||
{
|
||||
std::cout << "Exception: " << e.what() << " in t-eoRingTopology" << std::endl;
|
||||
}
|
||||
|
||||
}
|
||||
66
test/eo/t-eoRoulette.cpp
Executable file
66
test/eo/t-eoRoulette.cpp
Executable file
|
|
@ -0,0 +1,66 @@
|
|||
#include <paradiseo/eo/eoPop.h>
|
||||
#include <paradiseo/eo/EO.h>
|
||||
#include <paradiseo/eo/eoProportionalSelect.h>
|
||||
#include <paradiseo/eo/eoStochasticUniversalSelect.h>
|
||||
|
||||
class TestEO : public EO<double> { public: unsigned index; };
|
||||
|
||||
using namespace std;
|
||||
|
||||
template <class Select>
|
||||
int test_select()
|
||||
{
|
||||
vector<double> probs(4);
|
||||
probs[0] = 0.1;
|
||||
probs[1] = 0.4;
|
||||
probs[2] = 0.2;
|
||||
probs[3] = 0.3;
|
||||
|
||||
vector<double> counts(4,0.0);
|
||||
|
||||
// setup population
|
||||
eoPop<TestEO> 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<eoProportionalSelect<TestEO> >()) return 1;
|
||||
|
||||
return test_select<eoStochasticUniversalSelect<TestEO> >();
|
||||
}
|
||||
117
test/eo/t-eoSSGA.cpp
Executable file
117
test/eo/t-eoSSGA.cpp
Executable file
|
|
@ -0,0 +1,117 @@
|
|||
#include <paradiseo/eo.h>
|
||||
|
||||
// tests a Steady State GA
|
||||
|
||||
// Needed to define this breeder, maybe make it a breeder
|
||||
template <class EOT>
|
||||
class eoBreedOne : public eoBreed<EOT>
|
||||
{
|
||||
public :
|
||||
eoBreedOne(eoSelectOne<EOT>& _select, eoGenOp<EOT>& _op) : select(_select), op(_op) {}
|
||||
|
||||
void operator()(const eoPop<EOT>& _src, eoPop<EOT>& _dest)
|
||||
{
|
||||
_dest.clear();
|
||||
eoSelectivePopulator<EOT> pop(_src, _dest, select);
|
||||
op(pop);
|
||||
}
|
||||
|
||||
private :
|
||||
eoSelectOne<EOT>& select;
|
||||
eoGenOp<EOT>& op;
|
||||
};
|
||||
|
||||
typedef eoMinimizingFitness FitnessType;
|
||||
typedef eoVector<FitnessType, unsigned> EoType;
|
||||
|
||||
template <class EOT>
|
||||
class eoMyEval : public eoEvalFunc<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
void operator()(EOT& _eo)
|
||||
{
|
||||
_eo.fitness(*std::max_element(_eo.begin(), _eo.end()));
|
||||
}
|
||||
};
|
||||
|
||||
template <class EOT>
|
||||
class Xover : public eoBinOp<EOT>
|
||||
{
|
||||
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 EOT>
|
||||
class Mutate : public eoMonOp<EOT>
|
||||
{
|
||||
bool operator()(EOT& _eo)
|
||||
{
|
||||
unsigned point = rng.random(_eo.size());
|
||||
_eo[point] = rng.random(1024);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
int pop_size = 10;
|
||||
|
||||
eoGenContinue<EoType> cnt(10);
|
||||
eoCheckPoint<EoType> cp(cnt);
|
||||
|
||||
|
||||
Xover<EoType> xover;
|
||||
Mutate<EoType> mutate;
|
||||
|
||||
eoProportionalOp<EoType> opsel;
|
||||
|
||||
opsel.add(xover, 0.8);
|
||||
opsel.add(mutate, 0.2);
|
||||
|
||||
|
||||
eoDetTournamentSelect<EoType> selector(3);
|
||||
eoBreedOne<EoType> breed(selector, opsel);
|
||||
|
||||
// Replace a single one
|
||||
eoSSGAWorseReplacement<EoType> replace;
|
||||
|
||||
|
||||
// eoRandomSelect<EoType> selector;
|
||||
// eoGeneralBreeder<EoType> breed(selector, opsel);
|
||||
// eoPlusReplacement<EoType> replace;
|
||||
|
||||
|
||||
eoMyEval<EoType> eval;
|
||||
|
||||
eoEasyEA<EoType> algo(cp, eval, breed, replace);
|
||||
|
||||
eoUniformGenerator<unsigned> unif(0,1024);
|
||||
eoInitFixedLength<EoType> init(20, unif);
|
||||
|
||||
eoPop<EoType> pop(pop_size, init);
|
||||
|
||||
// evaluate
|
||||
apply<EoType>(eval, pop);
|
||||
|
||||
eoBestFitnessStat<EoType> best("Best_Fitness");
|
||||
eoAverageStat<EoType> avg("Avg_Fitness");
|
||||
eoStdoutMonitor mon;
|
||||
|
||||
cp.add(best);
|
||||
cp.add(avg);
|
||||
|
||||
// cp.add(mon);
|
||||
|
||||
mon.add(best);
|
||||
mon.add(avg);
|
||||
|
||||
// and run
|
||||
algo(pop);
|
||||
|
||||
}
|
||||
30
test/eo/t-eoSecondsElapsedContinue.cpp
Executable file
30
test/eo/t-eoSecondsElapsedContinue.cpp
Executable file
|
|
@ -0,0 +1,30 @@
|
|||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <time.h>
|
||||
#include <paradiseo/eo/eoSecondsElapsedContinue.h>
|
||||
#include <paradiseo/eo/eoPop.h>
|
||||
#include <paradiseo/eo/EO.h>
|
||||
|
||||
class Dummy : public EO<double> {};
|
||||
|
||||
int main() {
|
||||
|
||||
eoPop<Dummy> pop;
|
||||
|
||||
eoSecondsElapsedContinue<Dummy> 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;
|
||||
|
||||
}
|
||||
222
test/eo/t-eoSelect.cpp
Executable file
222
test/eo/t-eoSelect.cpp
Executable file
|
|
@ -0,0 +1,222 @@
|
|||
// to avoid long name warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
struct Dummy : public EO<double>
|
||||
{
|
||||
typedef double Type;
|
||||
void printOn(std::ostream & _os) const
|
||||
{
|
||||
_os << " - ";
|
||||
EO<double>::printOn(_os);
|
||||
}
|
||||
};
|
||||
|
||||
bool operator==(const Dummy & _d1, const Dummy & _d2)
|
||||
{
|
||||
return _d1.fitness() == _d2.fitness();
|
||||
}
|
||||
|
||||
struct eoDummyPop : public eoPop<Dummy>
|
||||
{
|
||||
public :
|
||||
eoDummyPop(int s=0) { resize(s); }
|
||||
};
|
||||
|
||||
// helper - DOES NOT WORK if different individuals have same fitness!!!
|
||||
template <class EOT>
|
||||
unsigned isInPop(EOT & _indi, eoPop<EOT> & _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 <class EOT>
|
||||
void testSelectMany(eoSelect<EOT> & _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<unsigned> nb(parents.size(), 0);
|
||||
for (i=0; i<offspring.size(); i++)
|
||||
{
|
||||
unsigned trouve = isInPop<Dummy>(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<parents.size(); i++)
|
||||
{
|
||||
std::cout << i << " -> " << ( (double)nb[i])/offspring.size() << std::endl;
|
||||
os << i << " " << ( (double)nb[i])/offspring.size() << std::endl;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
void testSelectOne(eoSelectOne<EOT> & _select, eoHowMany & _offspringRate,
|
||||
eoHowMany & _fertileRate, std::string _name)
|
||||
{
|
||||
eoTruncatedSelectOne<EOT> truncSelect(_select, _fertileRate);
|
||||
eoSelectMany<EOT> percSelect(truncSelect, _offspringRate);
|
||||
testSelectMany<EOT>(percSelect, _name);
|
||||
}
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int the_main(int argc, char **argv)
|
||||
{
|
||||
eoParser parser(argc, argv);
|
||||
eoValueParam<unsigned> parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P');
|
||||
pSize = parentSizeParam.value(); // global variable
|
||||
|
||||
// eoValueParam<double> offsrpringRateParam = parser.createParam<double>(1.0, "offsrpringRate", "Offsrpring rate",'O');
|
||||
// double oRate = offsrpringRateParam.value();
|
||||
eoValueParam<eoHowMany> offsrpringRateParam = parser.createParam(eoHowMany(1.0), "offsrpringRate", "Offsrpring rate (% or absolute)",'O');
|
||||
eoHowMany oRate = offsrpringRateParam.value();
|
||||
|
||||
eoValueParam<eoHowMany> fertileRateParam = parser.createParam(eoHowMany(1.0), "fertileRate", "Fertility rate (% or absolute)",'F');
|
||||
eoHowMany fRate = fertileRateParam.value();
|
||||
|
||||
eoValueParam<unsigned> tournamentSizeParam = parser.createParam(unsigned(2), "tournamentSize", "Deterministic tournament size",'T');
|
||||
unsigned int tSize = tournamentSizeParam.value();
|
||||
|
||||
eoValueParam<double> tournamentRateParam = parser.createParam(1.0, "tournamentRate", "Stochastic tournament rate",'t');
|
||||
double tRate = tournamentRateParam.value();
|
||||
|
||||
eoValueParam<double> rankingPressureParam = parser.createParam(2.0, "rankingPressure", "Selective pressure for the ranking selection",'p');
|
||||
double rankingPressure = rankingPressureParam.value();
|
||||
|
||||
eoValueParam<double> rankingExponentParam = parser.createParam(1.0, "rankingExponent", "Exponent for the ranking selection",'e');
|
||||
double rankingExponent = rankingExponentParam.value();
|
||||
|
||||
eoValueParam<std::string> 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<pSize; i++)
|
||||
parentsOrg[i].fitness(i);
|
||||
else if (fitnessType == std::string("exp"))
|
||||
for (unsigned i=0; i<pSize; i++)
|
||||
parentsOrg[i].fitness(exp((double)i));
|
||||
else if (fitnessType == std::string("log"))
|
||||
for (unsigned i=0; i<pSize; i++)
|
||||
parentsOrg[i].fitness(log(i+1.));
|
||||
else if (fitnessType == std::string("super"))
|
||||
{
|
||||
for (unsigned i=0; i<pSize-1; i++)
|
||||
parentsOrg[i].fitness(i);
|
||||
parentsOrg[pSize-1].fitness(10*pSize);
|
||||
}
|
||||
else
|
||||
throw std::runtime_error("Invalid fitness Type"+fitnessType);
|
||||
|
||||
std::cout << "Initial parents (odd)\n" << parentsOrg << std::endl;
|
||||
|
||||
// random seed
|
||||
eoValueParam<uint32_t>& 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<Dummy> detSelect(oRate);
|
||||
// testSelectMany(detSelect, "detSelect");
|
||||
|
||||
// Roulette
|
||||
eoProportionalSelect<Dummy> propSelect;
|
||||
testSelectOne<Dummy>(propSelect, oRate, fRate, "PropSelect");
|
||||
|
||||
// Linear ranking using the perf2Worth construct
|
||||
eoRankingSelect<Dummy> newRankingSelect(rankingPressure);
|
||||
sprintf(fileName,"LinRank_%g",rankingPressure);
|
||||
testSelectOne<Dummy>(newRankingSelect, oRate, fRate, fileName);
|
||||
|
||||
// Exponential ranking using the perf2Worth construct
|
||||
std::cout << "rankingExponent " << rankingExponent << std::endl;
|
||||
eoRankingSelect<Dummy> expRankingSelect(rankingPressure,rankingExponent);
|
||||
sprintf(fileName,"ExpRank_%g_%g",rankingPressure, rankingExponent);
|
||||
testSelectOne<Dummy>(expRankingSelect, oRate, fRate, fileName);
|
||||
|
||||
// Det tournament
|
||||
eoDetTournamentSelect<Dummy> detTourSelect(tSize);
|
||||
sprintf(fileName,"DetTour_%d",tSize);
|
||||
testSelectOne<Dummy>(detTourSelect, oRate, fRate, fileName);
|
||||
|
||||
// Stoch tournament
|
||||
eoStochTournamentSelect<Dummy> stochTourSelect(tRate);
|
||||
sprintf(fileName,"StochTour_%g",tRate);
|
||||
testSelectOne<Dummy>(stochTourSelect, oRate, fRate, fileName);
|
||||
|
||||
// Fitness scaling
|
||||
eoFitnessScalingSelect<Dummy> newFitScaleSelect(rankingPressure);
|
||||
sprintf(fileName,"LinFitScale_%g",rankingPressure);
|
||||
testSelectOne<Dummy>(newFitScaleSelect, oRate, fRate, fileName);
|
||||
|
||||
// Sequential selections
|
||||
eoSequentialSelect<Dummy> seqSel(false);
|
||||
strcpy(fileName,"Sequential");
|
||||
testSelectOne<Dummy>(seqSel, oRate, fRate, fileName);
|
||||
|
||||
eoEliteSequentialSelect<Dummy> eliteSeqSel;
|
||||
strcpy(fileName,"EliteSequential");
|
||||
testSelectOne<Dummy>(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;
|
||||
}
|
||||
}
|
||||
240
test/eo/t-eoSharing.cpp
Executable file
240
test/eo/t-eoSharing.cpp
Executable file
|
|
@ -0,0 +1,240 @@
|
|||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
// to avoid long name warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
// general
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/utils/eoDistance.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
struct Dummy : public EO<double>
|
||||
{
|
||||
typedef double Type;
|
||||
void printOn(std::ostream & _os) const
|
||||
{
|
||||
EO<double>::printOn(_os);
|
||||
std::cout << " " << xdist ;
|
||||
}
|
||||
double xdist;
|
||||
};
|
||||
|
||||
class
|
||||
eoDummyDistance : public eoDistance<Dummy>
|
||||
{
|
||||
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<Dummy>
|
||||
{
|
||||
public :
|
||||
eoDummyPop(int s=0) { resize(s); }
|
||||
};
|
||||
|
||||
// helper - DOES NOT WORK if different individuals have same fitness!!!
|
||||
template <class EOT>
|
||||
unsigned isInPop(EOT & _indi, eoPop<EOT> & _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 <class EOT>
|
||||
void testSelectMany(eoSelect<EOT> & _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<unsigned> nb(parents.size(), 0);
|
||||
for (i=0; i<offspring.size(); i++)
|
||||
{
|
||||
unsigned trouve = isInPop<Dummy>(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<parents.size(); i++)
|
||||
{
|
||||
std::cout << i << " -> " << ( (double)nb[i])/offspring.size() << std::endl;
|
||||
os << i << " " << ( (double)nb[i])/offspring.size() << std::endl;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
void testSelectOne(eoSelectOne<EOT> & _select, eoHowMany & _offspringRate,
|
||||
eoHowMany & _fertileRate, std::string _name)
|
||||
{
|
||||
eoTruncatedSelectOne<EOT> truncSelect(_select, _fertileRate);
|
||||
eoSelectMany<EOT> percSelect(truncSelect, _offspringRate);
|
||||
testSelectMany<EOT>(percSelect, _name);
|
||||
}
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int the_main(int argc, char **argv)
|
||||
{
|
||||
eoParser parser(argc, argv);
|
||||
|
||||
// random seed
|
||||
eoValueParam<uint32_t>& 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<unsigned> 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<unsigned> nbIndiPerPeak(peakNumber);
|
||||
unsigned i, sum=0;
|
||||
|
||||
// the second item is a vector<string> 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<peakNumber; i++)
|
||||
nbIndiPerPeak[i] = pSize/peakNumber;
|
||||
}
|
||||
else // parameters passed by user
|
||||
if (peakParam.second.size() != peakNumber)
|
||||
{
|
||||
std::cerr << "ERROR, not enough nb of indis per peaks" << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
else // now we have in peakParam.second all numbers
|
||||
{
|
||||
for (i=0; i<peakNumber; i++)
|
||||
sum += ( nbIndiPerPeak[i] = atoi(peakParam.second[i].c_str()) );
|
||||
// now normalize
|
||||
for (i=0; i<peakNumber; i++)
|
||||
nbIndiPerPeak[i] = nbIndiPerPeak[i] * pSize / sum;
|
||||
}
|
||||
|
||||
// compute exact total
|
||||
sum = 0;
|
||||
for (i=0; i<peakNumber; i++)
|
||||
sum += nbIndiPerPeak[i];
|
||||
if (sum != pSize)
|
||||
{
|
||||
pSize = pSizeParam.value() = sum;
|
||||
std::cerr << "WARNING, adjusting pSize to " << pSize << std::endl;
|
||||
}
|
||||
|
||||
make_help(parser);
|
||||
|
||||
// hard-coded directory name ...
|
||||
std::cout << "Testing the Sharing\n";
|
||||
std::cout << " There will be " << peakNumber << " peaks";
|
||||
std::cout << " with respective pops ";
|
||||
for (i=0; i<peakNumber; i++)
|
||||
std::cout << nbIndiPerPeak[i] << ", ";
|
||||
std::cout << "\n Peaks are at distance 1 from one-another (dim 1),\n";
|
||||
std::cout << " fitness of each peak is nb of peak, and\n";
|
||||
std::cout << " fitness of individuals = uniform[fitness of peak +- 0.01]\n\n";
|
||||
|
||||
std::cout << "The resulting file (in dir ResSelect), contains \n";
|
||||
std::cout << " the empirical proba. for each indi to be selected." << std::endl;
|
||||
system("mkdir ResSelect");
|
||||
|
||||
// initialize parent population
|
||||
parentsOrg.resize(pSize);
|
||||
|
||||
// all peaks of equal size in fitness, with different nn of individuals
|
||||
unsigned index=0;
|
||||
for (unsigned nbP=0; nbP<peakNumber; nbP++)
|
||||
for (i=0; i<nbIndiPerPeak[nbP]; i++)
|
||||
{
|
||||
parentsOrg[index].fitness(nbP+1 + 0.02*eo::rng.uniform() - 0.01);
|
||||
parentsOrg[index].xdist = nbP+1 + 0.02*eo::rng.uniform() - 0.01;
|
||||
index++;
|
||||
}
|
||||
|
||||
std::cout << "Initial population\n" << parentsOrg << std::endl;
|
||||
|
||||
char fileName[1024];
|
||||
|
||||
// the selection procedures under test
|
||||
// eoDetSelect<Dummy> detSelect(oRate);
|
||||
// testSelectMany(detSelect, "detSelect");
|
||||
|
||||
// Sharing using the perf2Worth construct
|
||||
// need a distance for that
|
||||
eoDummyDistance dist;
|
||||
eoSharingSelect<Dummy> newSharingSelect(nicheSize, dist);
|
||||
sprintf(fileName,"Niche_%g",nicheSize);
|
||||
testSelectOne<Dummy>(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;
|
||||
}
|
||||
}
|
||||
79
test/eo/t-eoShiftMutation.cpp
Executable file
79
test/eo/t-eoShiftMutation.cpp
Executable file
|
|
@ -0,0 +1,79 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoShiftMutation.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
#include <paradiseo/eo/eoInt.h>
|
||||
#include <paradiseo/eo/eoShiftMutation.h>
|
||||
#include <set>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoInt<double> 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<unsigned> 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 <Chrom> random(CHROM_SIZE);
|
||||
|
||||
// the population:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Chrom> 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 <Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
139
test/eo/t-eoStateAndParser.cpp
Executable file
139
test/eo/t-eoStateAndParser.cpp
Executable file
|
|
@ -0,0 +1,139 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
|
||||
// to avoid long name warnings
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <stdexcept> // runtime_error
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// tt.cpp:
|
||||
//
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
// general
|
||||
#include <paradiseo/eo/utils/eoRNG.h> // Random number generators
|
||||
#include <paradiseo/eo/ga.h>
|
||||
#include <paradiseo/eo/utils/eoParser.h>
|
||||
#include <paradiseo/eo/utils/eoState.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
// include package checkpointing
|
||||
#include <paradiseo/eo/utils/checkpointing>
|
||||
// and provisions for Bounds reading
|
||||
#include <paradiseo/eo/utils/eoRealVectorBounds.h>
|
||||
|
||||
struct Dummy : public EO<double>
|
||||
{
|
||||
typedef double Type;
|
||||
};
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
int the_main(int argc, char **argv)
|
||||
{ // ok, we have a command line parser and a state
|
||||
|
||||
typedef eoBit<float> Chrom;
|
||||
|
||||
eoParser parser(argc, argv);
|
||||
|
||||
// Define Parameters
|
||||
eoValueParam<unsigned int> dimParam((unsigned int)(5), "dimension", "dimension");
|
||||
eoValueParam<double> rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit");
|
||||
eoValueParam<double> factor(0.99, "mutationFactor", "Decrease factor for mutation rate");
|
||||
eoValueParam<uint32_t> 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<std::string> load_name("", "Load","Load",'L');
|
||||
eoValueParam<std::string> 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<eoRealVectorBounds> 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;
|
||||
}
|
||||
|
||||
}
|
||||
81
test/eo/t-eoSwapMutation.cpp
Executable file
81
test/eo/t-eoSwapMutation.cpp
Executable file
|
|
@ -0,0 +1,81 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoSwapMutation.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <set>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/eoInt.h>
|
||||
#include <paradiseo/eo/eoSwapMutation.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoInt<double> 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<unsigned> 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 <Chrom> random(CHROM_SIZE);
|
||||
|
||||
// the population:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Chrom> 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 <Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
299
test/eo/t-eoSymreg.cpp
Executable file
299
test/eo/t-eoSymreg.cpp
Executable file
|
|
@ -0,0 +1,299 @@
|
|||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <paradiseo/eo/gp/eoParseTree.h>
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
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 <class Children>
|
||||
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 <class Children>
|
||||
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<Node> in eoParseTreeDepthInit
|
||||
// without this specialization ...
|
||||
// 2 months later, it seems it does not accept this definition ...
|
||||
// but dies accept the lt_arity<Node> 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<char>(eot.getOp());
|
||||
return os;
|
||||
}
|
||||
|
||||
std::istream& operator>>(std::istream& is, SymregNode& eot)
|
||||
{
|
||||
char type;
|
||||
type = (char) is.get();
|
||||
eot = SymregNode(static_cast<SymregNode::Operator>(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 <class FType, class Node> struct RMS: public eoEvalFunc< eoParseTree<FType, Node> >
|
||||
{
|
||||
public :
|
||||
|
||||
typedef eoParseTree<FType, Node> EoType;
|
||||
|
||||
typedef eoParseTree<FType, Node> argument_type;
|
||||
typedef double fitness_type;
|
||||
|
||||
RMS() : eoEvalFunc<EoType>()
|
||||
{
|
||||
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<double> 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<double> inputs;
|
||||
vector<double> target;
|
||||
};
|
||||
|
||||
template <class EOT, class FitnessType>
|
||||
void print_best(eoPop<EOT>& 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<FitnessType, GpNode> EoType;
|
||||
typedef eoPop<EoType> Pop;
|
||||
|
||||
const int MaxSize = 100;
|
||||
const int nGenerations = 10; // only a test, so few generations
|
||||
|
||||
// Initializor sequence, contains the allowable nodes
|
||||
vector<GpNode> init(init_sequence, init_sequence + 5);
|
||||
|
||||
// Depth Initializor, defaults to grow method.
|
||||
eoGpDepthInitializer<FitnessType, GpNode> initializer(10, init);
|
||||
|
||||
// Root Mean Squared Error Measure
|
||||
RMS<FitnessType, GpNode> eval;
|
||||
|
||||
Pop pop(50, initializer);
|
||||
|
||||
apply<EoType>(eval, pop);
|
||||
|
||||
eoSubtreeXOver<FitnessType, GpNode> xover(MaxSize);
|
||||
eoBranchMutation<FitnessType, GpNode> mutation(initializer, MaxSize);
|
||||
|
||||
// The operators are encapsulated into an eoTRansform object,
|
||||
// that performs sequentially crossover and mutation
|
||||
eoSGATransform<EoType> transform(xover, 0.75, mutation, 0.25);
|
||||
|
||||
// The robust tournament selection
|
||||
eoDetTournamentSelect<EoType> selectOne(2); // tSize in [2,POPSIZE]
|
||||
// is now encapsulated in a eoSelectMany: 2 at a time -> SteadyState
|
||||
eoSelectMany<EoType> select(selectOne,2, eo_is_an_integer);
|
||||
|
||||
// and the Steady-State replacement
|
||||
eoSSGAWorseReplacement<EoType> replace;
|
||||
|
||||
// Terminators
|
||||
eoGenContinue<EoType> term(nGenerations);
|
||||
|
||||
eoCheckPoint<EoType> checkPoint(term);
|
||||
|
||||
eoAverageStat<EoType> avg;
|
||||
eoBestFitnessStat<EoType> best;
|
||||
eoStdoutMonitor monitor;
|
||||
|
||||
checkPoint.add(monitor);
|
||||
checkPoint.add(avg);
|
||||
checkPoint.add(best);
|
||||
|
||||
monitor.add(avg);
|
||||
monitor.add(best);
|
||||
|
||||
// GP generation
|
||||
eoEasyEA<EoType> gp(checkPoint, eval, select, transform, replace);
|
||||
|
||||
std::cout << "Initialization done" << std::endl;
|
||||
|
||||
print_best<EoType, FitnessType>(pop);
|
||||
|
||||
try
|
||||
{
|
||||
gp(pop);
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cout << "exception: " << e.what() << std::endl;;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
print_best<EoType, FitnessType>(pop);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode: C++
|
||||
// c-file-offsets: ((c . 0))
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
104
test/eo/t-eoSyncEasyPSO.cpp
Executable file
104
test/eo/t-eoSyncEasyPSO.cpp
Executable file
|
|
@ -0,0 +1,104 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoEasySyncPSO.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef __GNUG__
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif // __GNUG__
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
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<Particle> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Particle, double, const Particle& > 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<Particle> topology(NEIGHBORHOOD_SIZE);
|
||||
|
||||
// the full initializer
|
||||
eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop);
|
||||
init();
|
||||
|
||||
|
||||
// bounds
|
||||
eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5);
|
||||
|
||||
// velocity
|
||||
eoStandardVelocity <Particle> velocity (topology,1,1.6,2,bnds);
|
||||
|
||||
// flight
|
||||
eoStandardFlight <Particle> flight;
|
||||
|
||||
// Terminators
|
||||
eoGenContinue <Particle> genCont1 (50);
|
||||
eoGenContinue <Particle> genCont2 (50);
|
||||
|
||||
// PS flight
|
||||
eoSyncEasyPSO<Particle> pso1(genCont1, eval, velocity, flight);
|
||||
|
||||
eoSyncEasyPSO<Particle> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
80
test/eo/t-eoTwoOptMutation.cpp
Executable file
80
test/eo/t-eoTwoOptMutation.cpp
Executable file
|
|
@ -0,0 +1,80 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eoTwoOptMutation.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <set>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/eoInt.h>
|
||||
#include <paradiseo/eo/eoTwoOptMutation.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoInt<double> 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<unsigned> 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 <Chrom> random(CHROM_SIZE);
|
||||
|
||||
// the population:
|
||||
eoPop<Chrom> pop;
|
||||
|
||||
// Evaluation
|
||||
eoEvalFuncPtr<Chrom> 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 <Chrom> 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
22
test/eo/t-eoUniform.cpp
Executable file
22
test/eo/t-eoUniform.cpp
Executable file
|
|
@ -0,0 +1,22 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eouniform
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream> // std::cout
|
||||
#include <strstream> // ostrstream, istrstream
|
||||
#include <paradiseo/eo/eoUniform.h> // eoBin
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
main() {
|
||||
eoUniform<float> u1(-2.5,3.5);
|
||||
eoUniform<double> u2(0.003, 0 );
|
||||
eoUniform<unsigned long> 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
74
test/eo/t-eoVector.cpp
Executable file
74
test/eo/t-eoVector.cpp
Executable file
|
|
@ -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 <config.h>
|
||||
#endif
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
#include <paradiseo/eo/utils/eoRndGenerators.h>
|
||||
#include <paradiseo/eo/eoVector.h> // eoVector
|
||||
#include <paradiseo/eo/eoInit.h>
|
||||
#include <paradiseo/eo/eoScalarFitness.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoVector<eoMaximizingFitness, int> Chrom1;
|
||||
typedef eoVector<eoMinimizingFitness, int> 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<Chrom1::AtomType> uniform(-1,1);
|
||||
eoInitFixedLength<Chrom1> init(SIZE, uniform);
|
||||
|
||||
init(chrom);
|
||||
|
||||
std::cout << chrom << std::endl;
|
||||
|
||||
Chrom2 chrom2(chrom);
|
||||
|
||||
std::cout << chrom2 << std::endl;
|
||||
|
||||
// eoInitVariableLength<Chrom1> initvar(
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
76
test/eo/t-eoVirus.cpp
Executable file
76
test/eo/t-eoVirus.cpp
Executable file
|
|
@ -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 <iostream> // std::cout
|
||||
#include <paradiseo/eo.h> // general EO
|
||||
#include "VirusOp.h"
|
||||
#include "eoVirus.h"
|
||||
#include "eoInitVirus.h"
|
||||
#include <paradiseo/eo/utils/eoRndGenerators.h>
|
||||
|
||||
#include "binary_value.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoVirus<float> 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<float> 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<float> vm;
|
||||
for ( i = 0; i < 10; i++ ) {
|
||||
vm( chrom );
|
||||
std::cout << chrom << std::endl;
|
||||
}
|
||||
|
||||
// Chrom Transmision
|
||||
std::cout << "Chrom transmission--------" << std::endl;
|
||||
VirusTransmission<float> vt;
|
||||
vt( chrom2, chrom );
|
||||
std::cout << chrom2 << std::endl;
|
||||
|
||||
return 0;
|
||||
|
||||
}
|
||||
219
test/eo/t-eobin.cpp
Executable file
219
test/eo/t-eobin.cpp
Executable file
|
|
@ -0,0 +1,219 @@
|
|||
/* -*- 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 <config.h>
|
||||
#endif
|
||||
|
||||
#include <iostream> // std::cout
|
||||
#include <sstream>
|
||||
|
||||
#include <paradiseo/eo.h> // general EO
|
||||
#include <paradiseo/eo/ga.h> // bitstring representation & operators
|
||||
#include <paradiseo/eo/utils/eoRndGenerators.h>
|
||||
#include "binary_value.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoBit<double> 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<Chrom>
|
||||
random(chrom.size(), gen);
|
||||
|
||||
random(chrom); chrom.fitness(binary_value(chrom));
|
||||
std::cout << "after eoBinRandom ............ " << chrom << std::endl;
|
||||
|
||||
eoOneBitFlip<Chrom> bitflip;
|
||||
bitflip(chrom); chrom.fitness(binary_value(chrom));
|
||||
std::cout << "after eoBitFlip .............. " << chrom << std::endl;
|
||||
|
||||
eoBitMutation<Chrom> mutation(0.5);
|
||||
mutation(chrom); chrom.fitness(binary_value(chrom));
|
||||
std::cout << "after eoBinMutation(0.5) ..... " << chrom << std::endl;
|
||||
|
||||
eoBitInversion<Chrom> inversion;
|
||||
inversion(chrom); chrom.fitness(binary_value(chrom));
|
||||
std::cout << "after eoBinInversion ......... " << chrom << std::endl;
|
||||
|
||||
eoBitNext<Chrom> next;
|
||||
next(chrom); chrom.fitness(binary_value(chrom));
|
||||
std::cout << "after eoBinNext .............. " << chrom << std::endl;
|
||||
|
||||
eoBitPrev<Chrom> 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<Chrom> 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<Chrom> 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<Chrom> 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<Chrom> continuator1(50);
|
||||
eoFitContinue<Chrom> continuator2(65535.f);
|
||||
|
||||
eoCombinedContinue<Chrom> continuator(continuator1);
|
||||
continuator.add( continuator2);
|
||||
|
||||
eoCheckPoint<Chrom> checkpoint(continuator);
|
||||
|
||||
eoStdoutMonitor monitor;
|
||||
|
||||
checkpoint.add(monitor);
|
||||
|
||||
eoSecondMomentStats<Chrom> stats;
|
||||
|
||||
monitor.add(stats);
|
||||
checkpoint.add(stats);
|
||||
|
||||
eoProportionalSelect<Chrom> select;
|
||||
eoEvalFuncPtr<Chrom> eval(binary_value);
|
||||
|
||||
eoSGA<Chrom> sga(select, xover, 0.8f, bitflip, 0.1f, eval, checkpoint);
|
||||
|
||||
eoInitFixedLength<Chrom> init(16, gen);
|
||||
eoPop<Chrom> pop(100, init);
|
||||
|
||||
apply<Chrom>(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<Chrom> mOp( &next );
|
||||
mOp.adOp( &bitflip );
|
||||
std::cout << "before multiMonOp............ " << chrom << std::endl;
|
||||
mOp( chrom );
|
||||
std::cout << "after multiMonOp .............. " << chrom << std::endl;
|
||||
|
||||
eoBinGxOver<Chrom> gxover(2, 4);
|
||||
eoMultiBinOp<Chrom> mbOp( &gxover );
|
||||
mOp.adOp( &bitflip );
|
||||
std::cout << "before multiBinOp............ " << chrom << " " << chrom2 << std::endl;
|
||||
mbOp( chrom, chrom2 );
|
||||
std::cout << "after multiBinOp .............. " << chrom << " " << chrom2 <<std::endl;
|
||||
*/
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// For MSVC memory lead detection
|
||||
#ifdef _MSC_VER
|
||||
#include <crtdbg.h>
|
||||
#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';
|
||||
}
|
||||
|
||||
}
|
||||
89
test/eo/t-eofitness.cpp
Executable file
89
test/eo/t-eofitness.cpp
Executable file
|
|
@ -0,0 +1,89 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// t-eofitness.cpp
|
||||
// (c) GeNeura Team 1998
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <time.h> // time
|
||||
#include <stdlib.h> // srand, rand
|
||||
#include <iostream> // std::cout
|
||||
|
||||
#include <paradiseo/eo/eoScalarFitness.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template <class Fitness>
|
||||
int test_fitness(Fitness a, Fitness b)
|
||||
{
|
||||
// srand(time(0));
|
||||
|
||||
// Fitness a = aval; //static_cast<double>(rand()) / RAND_MAX;
|
||||
// Fitness b = bval; //static_cast<double>(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" <<std::endl;
|
||||
|
||||
std::cout << "testing > ";
|
||||
if (a > b)
|
||||
std::cout << a << " > " << b << " is true" << std::endl;
|
||||
else
|
||||
std::cout << a << " > " << b << " is false" <<std::endl;
|
||||
|
||||
std::cout << "testing == ";
|
||||
if (a == b)
|
||||
std::cout << a << " == " << b << " is true" << std::endl;
|
||||
else
|
||||
std::cout << a << " == " << b << " is false" <<std::endl;
|
||||
|
||||
std::cout << "testing != ";
|
||||
if (a != b)
|
||||
std::cout << a << " != " << b << " is true" << std::endl;
|
||||
else
|
||||
std::cout << a << " != " << b << " is false" <<std::endl;
|
||||
|
||||
a = b;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "Testing minimizing fitness with 1 and 2" << std::endl;
|
||||
std::cout << "------------------------------------------------------" << std::endl;
|
||||
|
||||
eoMinimizingFitness a = 1;
|
||||
eoMinimizingFitness b = 2;
|
||||
|
||||
test_fitness(a, b);
|
||||
|
||||
std::cout << "Testing minimizing fitness with 2 and 1" << std::endl;
|
||||
std::cout << "------------------------------------------------------" << std::endl;
|
||||
|
||||
test_fitness(b, a);
|
||||
|
||||
std::cout << "Testing maximizing fitness with 1 and 2" << std::endl;
|
||||
std::cout << "------------------------------------------------------" << std::endl;
|
||||
|
||||
eoMaximizingFitness a1 = 1;
|
||||
eoMaximizingFitness b1 = 2;
|
||||
|
||||
test_fitness(a1,b1);
|
||||
|
||||
std::cout << "Testing maximizing fitness with 2 and 1" << std::endl;
|
||||
std::cout << "------------------------------------------------------" << std::endl;
|
||||
|
||||
test_fitness(b1,a1);
|
||||
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
224
test/eo/t-openmp.cpp
Executable file
224
test/eo/t-openmp.cpp
Executable file
|
|
@ -0,0 +1,224 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation;
|
||||
version 2 of the License.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// t-openmp.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <climits>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/es/make_real.h>
|
||||
|
||||
#include <paradiseo/eo/apply.h>
|
||||
|
||||
#include <omp.h>
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#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<double>&)
|
||||
{
|
||||
eoRng myrng( get_rdtsc() );
|
||||
::usleep( myrng.random( 10 ) );
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double measure_apply( size_t p,
|
||||
void (*fct)(eoUF<EOT&, void>&, std::vector<EOT>&),
|
||||
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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
161
test/eo/t-openmp.py
Executable file
161
test/eo/t-openmp.py
Executable file
|
|
@ -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 <caner.candan@thalesgroup.com>
|
||||
#
|
||||
|
||||
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 ###')
|
||||
88
test/eo/t-selectOne.cpp
Executable file
88
test/eo/t-selectOne.cpp
Executable file
|
|
@ -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 <paradiseo/eo/ga/eoBin.h> // eoBin, eoPop, eoBreeder
|
||||
#include <paradiseo/eo/eoPop.h>
|
||||
#include <paradiseo/eo/ga/eoBitOp.h>
|
||||
|
||||
#include <paradiseo/eo/eoUniformSelect.h>
|
||||
#include <paradiseo/eo/eoStochTournament.h>
|
||||
#include <paradiseo/eo/eoDetTournament.h>
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
typedef eoBin<float> Chrom;
|
||||
|
||||
#include "binary_value.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
main()
|
||||
{
|
||||
const unsigned POP_SIZE = 8, CHROM_SIZE = 4;
|
||||
unsigned i;
|
||||
|
||||
eoBinRandom<Chrom> random;
|
||||
eoPop<Chrom> 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<Chrom> uSelect;
|
||||
|
||||
Chrom aChrom;
|
||||
aChrom = uSelect( pop );
|
||||
std::cout << "Uniform Select " << aChrom << " " << aChrom.fitness() << std::endl;
|
||||
|
||||
eoStochTournament<Chrom> sSelect(0.7);
|
||||
aChrom = sSelect( pop );
|
||||
std::cout << "Stochastic Tournament " << aChrom << " " << aChrom.fitness() << std::endl;
|
||||
|
||||
eoDetTournament<Chrom> dSelect(3);
|
||||
aChrom = dSelect( pop );
|
||||
std::cout << "Deterministic Tournament " << aChrom << " " << aChrom.fitness() << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
53
test/eompi/CMakeLists.txt
Executable file
53
test/eompi/CMakeLists.txt
Executable file
|
|
@ -0,0 +1,53 @@
|
|||
###############################################################################
|
||||
##
|
||||
## CMakeLists file for eo/test/mpi
|
||||
##
|
||||
###############################################################################
|
||||
|
||||
######################################################################################
|
||||
### 1) Include the sources
|
||||
######################################################################################
|
||||
|
||||
#include_directories(${EOMPI_SRC_DIR}/src)
|
||||
#include_directories(${EOSERIAL_SRC_DIR}/src)
|
||||
#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(${EOMPI_BIN_DIR}/lib)
|
||||
link_directories(${EOSERIAL_BIN_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()
|
||||
|
||||
######################################################################################
|
||||
25
test/eompi/DISTRIB_XP_README.md
Executable file
25
test/eompi/DISTRIB_XP_README.md
Executable file
|
|
@ -0,0 +1,25 @@
|
|||
README
|
||||
------
|
||||
|
||||
To launch a set of experiments with t-mpi-distrib-exp:
|
||||
|
||||
0) Compile it:
|
||||
|
||||
mpic++ -o distrib-exp t-mpi-distrib-exp.cpp -I../../src/ -I../../src/mpi/ -DWITH_MPI -L ../../../build/eo/lib/ -leoutils -leo -leompi -leoserial
|
||||
|
||||
1) Generate the experiments, thanks to the script gen-xp.py
|
||||
This script will guide you and ask you for all experiments. The prefix is used in the results filenames.
|
||||
You may want to modify the name of the experiments file (default value: "experiments.json") or
|
||||
the pattern of the results files. However, you have to ensure that the pattern is an one-to-one
|
||||
function of the parameters, otherwise some results could be lost.
|
||||
|
||||
2) Launch the t-mpi-distrib-exp program with mpirun:
|
||||
For 4 cores (= 1 master + 3 workers)
|
||||
mpirun -np 4 ./t-mpi-distrib-exp --use-experiment-file=1 --experiment-file=/home/eodev/eo/test/mpi/experiments.json
|
||||
|
||||
For 16 cores (= 1 master + 15 workers)
|
||||
mpirun -np 5 ./t-mpi-distrib-exp --use-experiment-file=1 --experiment-file=/home/eodev/eo/test/mpi/experiments.json
|
||||
|
||||
3) The program will generate the results of the experiments, as txt files. There is one result file for each run of each
|
||||
experiment.
|
||||
|
||||
6
test/eompi/experiments.json
Executable file
6
test/eompi/experiments.json
Executable file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"experiments":[
|
||||
{"size":"10", "packet_size":"1", "seed":"1337", "distribution":{"name":"normal", "mean":"500", "stddev":"100"}, "worker_print_waiting_time":"1", "filename":"exp1.result.txt"},
|
||||
{"size":"10", "packet_size":"1", "seed":"1337", "distribution":{"name":"normal", "mean":"100", "stddev":"20"}, "worker_print_waiting_time":"1", "filename":"exp2.result.txt"}
|
||||
]
|
||||
}
|
||||
152
test/eompi/gen-xp.py
Executable file
152
test/eompi/gen-xp.py
Executable file
|
|
@ -0,0 +1,152 @@
|
|||
# -*- coding:utf-8 -*-
|
||||
"""
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Authors:
|
||||
Benjamin Bouvier <benjamin.bouvier@gmail.com>
|
||||
"""
|
||||
import json
|
||||
|
||||
# Where will be saved the experiments?
|
||||
EXPERIMENTS_FILENAME = "experiments.json"
|
||||
# What will be the pattern for experiments filenames?
|
||||
FILENAME_PATTERN = "%(prefix)s_%(distrib_name)s_%(size)s_%(packet_size)s_%(run)s.txt"
|
||||
|
||||
def input_number_at_least( min ):
|
||||
n = min - 1
|
||||
while n < min:
|
||||
try:
|
||||
n = int(raw_input("Enter a number greater or equal to %s: "% min))
|
||||
except Exception:
|
||||
print "Please enter an integer."
|
||||
return n
|
||||
|
||||
def input_number_between( min, max ):
|
||||
n = min - 1
|
||||
while n < min or n > max:
|
||||
try:
|
||||
n = int(raw_input("Enter a number between %s and %s: " % (min,max)))
|
||||
except Exception:
|
||||
print "Please enter a number."
|
||||
return n
|
||||
|
||||
def choose_continue():
|
||||
print """Do you want to continue?
|
||||
0. No
|
||||
1. Yes"""
|
||||
return bool( input_number_between(0,1) )
|
||||
|
||||
def choose_distribution_uniform():
|
||||
distribution = {}
|
||||
distribution["name"] = "uniform"
|
||||
print "Enter the minimum value (in milliseconds): "
|
||||
min = input_number_at_least( 0 )
|
||||
distribution["min"] = str(min)
|
||||
print "Enter the maximum value (in milliseconds): "
|
||||
distribution["max"] = str(input_number_at_least( min ))
|
||||
return distribution
|
||||
|
||||
def choose_distribution_normal():
|
||||
distribution = {}
|
||||
distribution["name"] = "normal"
|
||||
print "Enter the mean (in milliseconds): "
|
||||
distribution["mean"] = str(input_number_at_least( 0 ))
|
||||
print "Enter the standard deviation (in milliseconds): "
|
||||
distribution["stddev"] = str(input_number_at_least( 0 ))
|
||||
return distribution
|
||||
|
||||
def choose_distribution_power():
|
||||
distribution = {}
|
||||
distribution["name"] = "exponential"
|
||||
print "Enter the mean (in milliseconds): "
|
||||
distribution["mean"] = str(input_number_at_least( 0 ))
|
||||
return distribution
|
||||
|
||||
def choose_distribution():
|
||||
print """Choose your distribution:
|
||||
0. Uniform
|
||||
1. Normal
|
||||
2. Exponential"""
|
||||
choice = input_number_between( 0, 2 )
|
||||
choose_distrib_functions = [ choose_distribution_uniform, choose_distribution_normal, choose_distribution_power ]
|
||||
return choose_distrib_functions[ choice ]()
|
||||
|
||||
def choose_packet_size():
|
||||
print "Enter the size of a packet (group of elements):"
|
||||
return str(input_number_at_least( 0 ))
|
||||
|
||||
def choose_size():
|
||||
print "Enter the total size (size of population):"
|
||||
return str(input_number_at_least( 0 ))
|
||||
|
||||
def choose_worker_print():
|
||||
print """Should the workers print the time they sleep on stdout?
|
||||
0. No
|
||||
1. Yes"""
|
||||
return str(input_number_between( 0, 1 ))
|
||||
|
||||
def choose_nb_runs():
|
||||
print """How many runs should be launched for this configuration? Seeds will be automatically affected to the number
|
||||
of run+1 (for instance, the first run has a seed of 1, the second has a seed of 2, etc.)."""
|
||||
return input_number_at_least( 1 )
|
||||
|
||||
def choose_prefix():
|
||||
print """What is the name of the experiment? It will be used as the prefix of file names."""
|
||||
return raw_input("Enter the prefix name: ")
|
||||
|
||||
def main():
|
||||
|
||||
prefix = choose_prefix()
|
||||
exps = []
|
||||
|
||||
while True:
|
||||
exp = {}
|
||||
exp["distribution"] = choose_distribution()
|
||||
|
||||
exp["size"] = choose_size()
|
||||
exp["packet_size"] = choose_packet_size()
|
||||
exp["worker_print_waiting_time"] = choose_worker_print()
|
||||
runs = choose_nb_runs()
|
||||
for i in range( runs ):
|
||||
exp["seed"] = str(i+1)
|
||||
|
||||
filename_map = exp.copy()
|
||||
filename_map["run"] = exp["seed"]
|
||||
filename_map["distrib_name"] = exp["distribution"]["name"]
|
||||
filename_map["prefix"] = prefix
|
||||
filename = FILENAME_PATTERN % filename_map
|
||||
|
||||
exp["filename"] = filename
|
||||
copy = exp.copy()
|
||||
exps.append( copy )
|
||||
|
||||
if not choose_continue():
|
||||
break
|
||||
|
||||
# Write the experiments in a file
|
||||
f = file( EXPERIMENTS_FILENAME , 'wb')
|
||||
f.write("""{"experiments":[""")
|
||||
i = 0
|
||||
for exp in exps:
|
||||
if i > 0:
|
||||
f.write(",\n")
|
||||
i += 1
|
||||
f.write( json.dumps(exp) )
|
||||
f.write("]}")
|
||||
f.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
51
test/eompi/t-mpi-common.h
Executable file
51
test/eompi/t-mpi-common.h
Executable file
|
|
@ -0,0 +1,51 @@
|
|||
# ifndef __T_MPI_COMMON_H__
|
||||
# define __T_MPI_COMMON_H__
|
||||
|
||||
#include <paradiseo/eoserial.h>
|
||||
|
||||
/**
|
||||
* @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__
|
||||
556
test/eompi/t-mpi-distrib-exp.cpp
Executable file
556
test/eompi/t-mpi-distrib-exp.cpp
Executable file
|
|
@ -0,0 +1,556 @@
|
|||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
* Authors:
|
||||
* Benjamin Bouvier <benjamin.bouvier@gmail.com>
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file t-mpi-distrib-exp.cpp
|
||||
* @brief File for parallel experimentations.
|
||||
*
|
||||
* When using parallel evaluation, the individuals to evaluate are sent by packets (group),
|
||||
* so as to avoid that communication time be more important than worker's execution time.
|
||||
* However, the ideal size of packet depends on the problem and the time needed to carry out
|
||||
* the atomic operation on each individual. This experiment tries to find a relation between
|
||||
* the total number of elements to process (size), the execution time and the size of packet.
|
||||
* This could lead to an heuristic allowing to optimize the size of packet according to the
|
||||
* processing times.
|
||||
*/
|
||||
# include <unistd.h> // usleep
|
||||
|
||||
# include <iostream>
|
||||
# include <iomanip>
|
||||
# include <string>
|
||||
# include <sstream>
|
||||
# include <vector>
|
||||
|
||||
# include <paradiseo/eo.h>
|
||||
|
||||
# include <paradiseo/eompi.h>
|
||||
# include "t-mpi-common.h"
|
||||
|
||||
using namespace eo::mpi;
|
||||
|
||||
// Serializable int
|
||||
typedef SerializableBase<int> type;
|
||||
|
||||
/*
|
||||
* The task is the following: the worker receives a number of milliseconds to wait, which
|
||||
* simulates the process of one individual. This way, the sequences of processing times are
|
||||
* generated only by the master and are more easily reproductible.
|
||||
*/
|
||||
struct Wait : public eoUF< type &, void >
|
||||
{
|
||||
Wait( bool print ) : _print( print )
|
||||
{
|
||||
// empty
|
||||
}
|
||||
|
||||
void operator()( type & milliseconds )
|
||||
{
|
||||
if( _print )
|
||||
std::cout << "Sleeping for " << milliseconds << "ms..." << std::endl;
|
||||
// usleep takes an input in microseconds
|
||||
usleep( milliseconds * 1000 );
|
||||
}
|
||||
|
||||
private:
|
||||
bool _print;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Represents a distribution of processing times.
|
||||
*/
|
||||
class Distribution : public std::vector< type >, public eoserial::Persistent
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Really fills the vector with the distribution values.
|
||||
*/
|
||||
void fill( unsigned size )
|
||||
{
|
||||
for( unsigned i = 0; i < size; ++i )
|
||||
{
|
||||
int next = next_element();
|
||||
if( next < 0 ) next = 0;
|
||||
push_back( next );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns the next element of the distribution to put in the
|
||||
* vector.
|
||||
*
|
||||
* @returns Number of milliseconds to wait. Can be negative ; in this case,
|
||||
* the number will be truncated to 0ms.
|
||||
*/
|
||||
virtual int next_element() = 0;
|
||||
|
||||
/**
|
||||
* @brief Creates params and retrieves values from parser
|
||||
*
|
||||
* Parser's params should take milliseconds as inputs.
|
||||
*/
|
||||
virtual void make_parser( eoParser & parser ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Returns true if this distribution has been activated by the
|
||||
* command line.
|
||||
*
|
||||
* Used by the main program so as to check if at least one distribution has been
|
||||
* activated.
|
||||
*/
|
||||
bool isActive() { return _active; }
|
||||
|
||||
/**
|
||||
* @brief Prints the name and the parameters of the distribution
|
||||
*/
|
||||
virtual std::string toString() const = 0;
|
||||
|
||||
protected:
|
||||
|
||||
bool _active;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Uniform distribution.
|
||||
*
|
||||
* This is an uniform distribution, defined by a minimum value and a maximum value.
|
||||
* In the uniform distribution, every number from min to max has the same probability
|
||||
* to appear.
|
||||
*
|
||||
* The 3 parameters activable from a parser are the following:
|
||||
* - uniform=1 : if we want to use the uniform distribution
|
||||
* - uniform-min=x : use x milliseconds as the minimum value of waiting time.
|
||||
* - uniform-max=y : use y milliseconds as the maximum value of waiting time.
|
||||
* Ensure that x < y, or the results are unpredictable.
|
||||
*/
|
||||
class UniformDistribution : public Distribution
|
||||
{
|
||||
public:
|
||||
|
||||
UniformDistribution()
|
||||
{
|
||||
// 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, in ms.", '\0', "Uniform").value();
|
||||
_max = parser.createParam( 1.0, "uniform-max", "Maximum for uniform distribution, in ms.", '\0', "Uniform").value();
|
||||
}
|
||||
|
||||
int next_element()
|
||||
{
|
||||
return std::floor( eo::rng.uniform( _min, _max ) );
|
||||
}
|
||||
|
||||
eoserial::Object* pack( void ) const
|
||||
{
|
||||
eoserial::Object* obj = new eoserial::Object;
|
||||
obj->add( "name", eoserial::make( "uniform" ) );
|
||||
obj->add( "min", eoserial::make( _min ) );
|
||||
obj->add( "max", eoserial::make( _max ) );
|
||||
return obj;
|
||||
}
|
||||
|
||||
void unpack( const eoserial::Object* obj )
|
||||
{
|
||||
eoserial::unpack( *obj, "min", _min );
|
||||
eoserial::unpack( *obj, "max", _max );
|
||||
}
|
||||
|
||||
std::string toString() const
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "uniform" << '\n'
|
||||
<< "min: " << _min << '\n'
|
||||
<< "max: " << _max << '\n';
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
double _min;
|
||||
double _max;
|
||||
|
||||
} uniformDistribution;
|
||||
|
||||
/**
|
||||
* @brief Normal (gaussian) distribution of times.
|
||||
*
|
||||
* A normal distribution is defined by a mean and a standard deviation.
|
||||
* The 3 parameters activable from the parser are the following:
|
||||
* - normal=1: activates the gaussian distribution.
|
||||
* - normal-mean=50: use 50ms as the mean of the distribution.
|
||||
* - normal-stddev=10: use 10ms as the standard deviation of the distribution.
|
||||
*/
|
||||
class NormalDistribution : public Distribution
|
||||
{
|
||||
public:
|
||||
|
||||
NormalDistribution()
|
||||
{
|
||||
// empty
|
||||
}
|
||||
|
||||
void make_parser( eoParser & parser )
|
||||
{
|
||||
_active = parser.createParam( false, "normal", "Normal distribution", '\0', "Normal").value();
|
||||
_mean = parser.createParam( 0.0, "normal-mean", "Mean for the normal distribution (0 by default), in ms.", '\0', "Normal").value();
|
||||
_stddev = parser.createParam( 1.0, "normal-stddev", "Standard deviation for the normal distribution (1ms by default), 0 isn't acceptable.", '\0', "Normal").value();
|
||||
}
|
||||
|
||||
int next_element()
|
||||
{
|
||||
return std::floor( eo::rng.normal( _mean, _stddev ) );
|
||||
}
|
||||
|
||||
eoserial::Object* pack( void ) const
|
||||
{
|
||||
eoserial::Object* obj = new eoserial::Object;
|
||||
obj->add( "name", eoserial::make( "normal" ) );
|
||||
obj->add( "mean", eoserial::make( _mean ) );
|
||||
obj->add( "stddev", eoserial::make( _stddev ) );
|
||||
return obj;
|
||||
}
|
||||
|
||||
void unpack( const eoserial::Object* obj )
|
||||
{
|
||||
eoserial::unpack( *obj, "mean", _mean );
|
||||
eoserial::unpack( *obj, "stddev", _stddev );
|
||||
}
|
||||
|
||||
std::string toString() const
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "normal" << '\n'
|
||||
<< "mean: " << _mean << '\n'
|
||||
<< "stddev: " << _stddev << '\n';
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
double _mean;
|
||||
double _stddev;
|
||||
} normalDistribution;
|
||||
|
||||
/**
|
||||
* @brief Exponential distribution.
|
||||
*
|
||||
* This distribution belongs to the category of the decreasing power laws and are affected by long trails
|
||||
* phenomenons.
|
||||
* An exponential distribution is only defined by its mean.
|
||||
*
|
||||
* The 2 parameters activable from the parser are the following:
|
||||
* - exponential=1: to activate the exponential distribution.
|
||||
* - exponential-mean=50: indicates that the mean must be 50ms.
|
||||
*/
|
||||
class ExponentialDistribution : public Distribution
|
||||
{
|
||||
public:
|
||||
|
||||
ExponentialDistribution()
|
||||
{
|
||||
// empty
|
||||
}
|
||||
|
||||
void make_parser( eoParser & parser )
|
||||
{
|
||||
_active = parser.createParam( false, "exponential", "Exponential distribution", '\0', "Exponential").value();
|
||||
_mean = parser.createParam( 0.0, "exponential-mean", "Mean for the exponential distribution (0 by default), in ms.", '\0', "Exponential").value();
|
||||
}
|
||||
|
||||
int next_element()
|
||||
{
|
||||
return std::floor( eo::rng.negexp( _mean ) );
|
||||
}
|
||||
|
||||
eoserial::Object* pack( void ) const
|
||||
{
|
||||
eoserial::Object* obj = new eoserial::Object;
|
||||
obj->add( "name", eoserial::make( "exponential" ) );
|
||||
obj->add( "mean", eoserial::make( _mean ) );
|
||||
return obj;
|
||||
}
|
||||
|
||||
void unpack( const eoserial::Object* obj )
|
||||
{
|
||||
eoserial::unpack( *obj, "mean", _mean );
|
||||
}
|
||||
|
||||
std::string toString() const
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "exponential" << '\n'
|
||||
<< "mean: " << _mean << '\n';
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
double _mean;
|
||||
|
||||
} exponentialDistribution;
|
||||
|
||||
/**
|
||||
* @brief Serializable experiment.
|
||||
*
|
||||
* Allows an experiment to be saved and loaded via a file, using eoserial.
|
||||
*
|
||||
* Construct the experiment with the good parameters from the command line or load experiments from a file. Then call run() to launch the parallel job.
|
||||
*
|
||||
* If a filename is given to the constructor (or during the loading), the results of the experiments (time series) will
|
||||
* be redirected to the file with the given file name. Otherwise (filename == ""), the output will just be shown on the
|
||||
* standard output.
|
||||
*/
|
||||
class Experiment : public eoserial::Persistent
|
||||
{
|
||||
public:
|
||||
|
||||
Experiment() : _distribution(0), _worker_print_waiting_time( false ), _fileName("")
|
||||
{
|
||||
// empty
|
||||
}
|
||||
|
||||
Experiment( Distribution* distrib, unsigned size, unsigned packet_size, bool print_waiting_time, unsigned seed, const std::string& fileName = "" ) :
|
||||
_distribution( distrib ),
|
||||
_size( size ),
|
||||
_packet_size( packet_size ),
|
||||
_worker_print_waiting_time( print_waiting_time ),
|
||||
_seed( seed ),
|
||||
_fileName( fileName )
|
||||
{
|
||||
// empty
|
||||
}
|
||||
|
||||
eoserial::Object* pack( void ) const
|
||||
{
|
||||
eoserial::Object* obj = new eoserial::Object;
|
||||
obj->add( "size", eoserial::make( _size ) );
|
||||
obj->add( "packet_size", eoserial::make( _packet_size ) );
|
||||
obj->add( "worker_print_waiting_time", eoserial::make( _worker_print_waiting_time ) );
|
||||
obj->add( "seed", eoserial::make( _seed ) );
|
||||
if( _distribution )
|
||||
{
|
||||
obj->add( "distribution", _distribution );
|
||||
}
|
||||
obj->add( "filename", eoserial::make( _fileName ) );
|
||||
return obj;
|
||||
}
|
||||
|
||||
void unpack( const eoserial::Object* obj )
|
||||
{
|
||||
eoserial::unpack( *obj, "size", _size );
|
||||
eoserial::unpack( *obj, "packet_size", _packet_size );
|
||||
eoserial::unpack( *obj, "worker_print_waiting_time", _worker_print_waiting_time );
|
||||
eoserial::unpack( *obj, "seed", _seed );
|
||||
eoserial::unpack( *obj, "filename", _fileName );
|
||||
|
||||
eoserial::Object* distribObject = static_cast<eoserial::Object*>( obj->find("distribution")->second );
|
||||
std::string distribName = *static_cast<eoserial::String*>( distribObject->find("name")->second );
|
||||
|
||||
// TODO find a better design...
|
||||
if( distribName == "normal" ) {
|
||||
_distribution = & normalDistribution;
|
||||
} else if( distribName == "uniform" ) {
|
||||
_distribution = & uniformDistribution;
|
||||
} else if( distribName == "exponential" ) {
|
||||
_distribution = & exponentialDistribution;
|
||||
} else {
|
||||
throw std::runtime_error("When unpacking experience, no distribution found.");
|
||||
}
|
||||
|
||||
eoserial::unpackObject( *obj, "distribution", *_distribution );
|
||||
}
|
||||
|
||||
void run()
|
||||
{
|
||||
mpi::communicator& comm = eo::mpi::Node::comm();
|
||||
// reinits every objects
|
||||
eo::rng.reseed( _seed );
|
||||
eo::rng.clearCache(); // trick for repeatable sequences of normal numbers, cf eo::rng
|
||||
_distribution->clear();
|
||||
_distribution->fill( _size );
|
||||
|
||||
eo::mpi::timerStat.start("run");
|
||||
Wait wait( _worker_print_waiting_time );
|
||||
ParallelApplyStore< type > store( wait, DEFAULT_MASTER, _packet_size );
|
||||
store.data( *_distribution );
|
||||
DynamicAssignmentAlgorithm scheduling;
|
||||
ParallelApply< type > job( scheduling, DEFAULT_MASTER, store );
|
||||
|
||||
job.run();
|
||||
eo::mpi::timerStat.stop("run");
|
||||
if( job.isMaster() )
|
||||
{
|
||||
EmptyJob( scheduling, DEFAULT_MASTER ); // to terminate parallel apply
|
||||
// Receive statistics
|
||||
typedef std::map< std::string, eoTimerStat::Stat > typeStats;
|
||||
|
||||
std::ostream* pout;
|
||||
std::ofstream file;
|
||||
bool fileSaveActivated = false;
|
||||
if( _fileName == "" ) {
|
||||
pout = & std::cout;
|
||||
} else {
|
||||
pout = & file;
|
||||
file.open( _fileName.c_str() );
|
||||
fileSaveActivated = true;
|
||||
}
|
||||
std::ostream& out = *pout;
|
||||
|
||||
// Reminder of the parameters
|
||||
out << "size: " << _size << '\n'
|
||||
<< "packet_size: " << _packet_size << '\n'
|
||||
<< "distribution: " << _distribution->toString()
|
||||
<< "seed: " << _seed << '\n' << std::endl;
|
||||
|
||||
// Results
|
||||
out << std::fixed << std::setprecision( 5 );
|
||||
for( int i = 1, s = comm.size(); i < s; ++i )
|
||||
{
|
||||
eoTimerStat timerStat;
|
||||
comm.recv( i, eo::mpi::Channel::Commands, timerStat );
|
||||
typeStats stats = timerStat.stats();
|
||||
for( typeStats::iterator it = stats.begin(),
|
||||
end = stats.end();
|
||||
it != end;
|
||||
++it )
|
||||
{
|
||||
out << i << " " << it->first << std::endl;
|
||||
for( int j = 0, t = it->second.wtime.size(); j < t; ++j )
|
||||
{
|
||||
out << it->second.wtime[j] << " ";
|
||||
}
|
||||
out << std::endl;
|
||||
}
|
||||
out << std::endl;
|
||||
}
|
||||
|
||||
if( fileSaveActivated ) {
|
||||
file.close();
|
||||
}
|
||||
} else
|
||||
{
|
||||
// Send statistics
|
||||
comm.send( DEFAULT_MASTER, eo::mpi::Channel::Commands, eo::mpi::timerStat );
|
||||
}
|
||||
timerStat.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Distribution* _distribution;
|
||||
unsigned _size;
|
||||
unsigned _packet_size;
|
||||
bool _worker_print_waiting_time;
|
||||
unsigned _seed;
|
||||
std::string _fileName;
|
||||
};
|
||||
|
||||
int main( int argc, char** argv )
|
||||
{
|
||||
Node::init( argc, argv );
|
||||
eoParser parser( argc, argv );
|
||||
|
||||
// forces the statistics to be retrieved
|
||||
eo::mpi::timerStat.forceDoMeasure();
|
||||
|
||||
// General parameters for the experimentation
|
||||
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();
|
||||
bool worker_print_waiting_time = parser.createParam( false, "print-waiting-time", "Do the workers need to print the time they wait?", '\0', "Parallelization").value();
|
||||
unsigned seed = parser.createParam( 0U, "seed", "Seed of random generator", '\0', "General").value();
|
||||
std::string fileName = parser.createParam( std::string(""), "filename", "File name to which redirect the results (for a single experiment)", '\0', "General").value();
|
||||
|
||||
bool useExperimentFile = parser.createParam( false, "use-experiment-file", "Put to true if you want to launch experiments from a file formatted in JSON (see experiment-file).", '\0', "General").value();
|
||||
std::string experimentFile = parser.createParam( std::string("experiments.json"), "experiment-file", "File name of experiments to provide, in format JSON.", '\0', "General").value();
|
||||
|
||||
if( !useExperimentFile )
|
||||
{
|
||||
std::vector<Distribution*> distribs;
|
||||
distribs.push_back( &uniformDistribution );
|
||||
distribs.push_back( &normalDistribution );
|
||||
distribs.push_back( &exponentialDistribution );
|
||||
|
||||
// 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
|
||||
bool isChosenDistrib = false;
|
||||
Distribution* pdistrib = 0;
|
||||
for( int i = 0, s = distribs.size(); i < s; ++i )
|
||||
{
|
||||
distribs[i]->make_parser( parser );
|
||||
if( distribs[i]->isActive() )
|
||||
{
|
||||
if( isChosenDistrib )
|
||||
{
|
||||
throw std::runtime_error("Only one distribution can be chosen during a launch!");
|
||||
} else
|
||||
{
|
||||
isChosenDistrib = true;
|
||||
pdistrib = distribs[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
make_parallel( parser );
|
||||
make_help( parser );
|
||||
|
||||
if( !isChosenDistrib )
|
||||
{
|
||||
throw std::runtime_error("No distribution chosen. One distribution should be chosen.");
|
||||
}
|
||||
|
||||
Experiment e( pdistrib, size, packet_size, worker_print_waiting_time, seed, fileName );
|
||||
e.run();
|
||||
}
|
||||
else // use experiments file
|
||||
{
|
||||
// read content of file
|
||||
std::ifstream file( experimentFile.c_str() );
|
||||
std::string fileContent;
|
||||
while( file )
|
||||
{
|
||||
char temp[4096];
|
||||
file.getline( temp, 4096, '\n' );
|
||||
fileContent += temp;
|
||||
fileContent += '\n';
|
||||
}
|
||||
file.close();
|
||||
|
||||
// transform content into array of experiments
|
||||
eoserial::Object* wrapper = eoserial::Parser::parse( fileContent );
|
||||
eoserial::Array& experiments = *static_cast< eoserial::Array* >( wrapper->find("experiments")->second );
|
||||
|
||||
for( unsigned i = 0, s = experiments.size(); i < s; ++i )
|
||||
{
|
||||
std::cout << "Launching experiment " << (i+1) << "..." << std::endl;
|
||||
eoserial::Object* expObj = static_cast< eoserial::Object* >( experiments[i] );
|
||||
Experiment exp;
|
||||
exp.unpack( expObj );
|
||||
exp.run();
|
||||
}
|
||||
delete wrapper;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
206
test/eompi/t-mpi-eval.cpp
Executable file
206
test/eompi/t-mpi-eval.cpp
Executable file
|
|
@ -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 <benjamin.bouvier@gmail.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
* 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 <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/eoPopEvalFunc.h>
|
||||
|
||||
#include <paradiseo/eo/es/make_real.h>
|
||||
#include "../eo/real_value.h"
|
||||
|
||||
#include <paradiseo/eompi.h>
|
||||
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
class eoRealSerializable : public eoReal< eoMinimizingFitness >, public eoserial::Persistent
|
||||
{
|
||||
public:
|
||||
|
||||
eoRealSerializable(unsigned size = 0, double value = 0.0):
|
||||
eoReal<eoMinimizingFitness>(size, value) {}
|
||||
|
||||
eoserial::Object* pack() const
|
||||
{
|
||||
eoserial::Object* obj = new eoserial::Object;
|
||||
obj->add( "array",
|
||||
eoserial::makeArray< vector<double>, 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<double>, eoserial::Array::UnpackAlgorithm >
|
||||
( *obj, "array", *this );
|
||||
|
||||
bool invalidFitness;
|
||||
eoserial::unpack( *obj, "invalid", invalidFitness );
|
||||
if( invalidFitness ) {
|
||||
invalidate();
|
||||
} else {
|
||||
double fitnessVal;
|
||||
eoserial::unpack<double>( *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<EOT>
|
||||
{
|
||||
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<EOT>::_wrapped;
|
||||
// using eo::mpi::HandleResponseParallelApply<EOT>::d;
|
||||
|
||||
void operator()(int wrkRank)
|
||||
{
|
||||
eo::mpi::ParallelApplyData<EOT> * 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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
196
test/eompi/t-mpi-multipleRoles.cpp
Executable file
196
test/eompi/t-mpi-multipleRoles.cpp
Executable file
|
|
@ -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 <benjamin.bouvier@gmail.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
* 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 <paradiseo/eompi.h>
|
||||
# include <paradiseo/eompi/eoParallelApply.h>
|
||||
# include <paradiseo/eompi/eoTerminateJob.h>
|
||||
|
||||
# include "t-mpi-common.h"
|
||||
|
||||
# include <iostream>
|
||||
|
||||
# include <vector>
|
||||
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<int>, which is a serializable integer that can be used as an integer.
|
||||
*/
|
||||
template< class T >
|
||||
struct SerializableVector : public std::vector<T>, public eoserial::Persistent
|
||||
{
|
||||
public:
|
||||
|
||||
void unpack( const eoserial::Object* obj )
|
||||
{
|
||||
this->clear();
|
||||
eoserial::Array* vector = static_cast<eoserial::Array*>( obj->find("vector")->second );
|
||||
vector->deserialize< std::vector<T>, eoserial::Array::UnpackObjectAlgorithm >( *this );
|
||||
}
|
||||
|
||||
eoserial::Object* pack( void ) const
|
||||
{
|
||||
eoserial::Object* obj = new eoserial::Object;
|
||||
obj->add("vector", eoserial::makeArray< std::vector<T>, 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<int>&, void >
|
||||
{
|
||||
void operator() ( SerializableBase<int> & 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<int> >& 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<int> workers;
|
||||
workers.push_back( rank + 2 );
|
||||
workers.push_back( rank + 4 );
|
||||
DynamicAssignmentAlgorithm algo( workers );
|
||||
SubWork sw;
|
||||
|
||||
// Launch the job!
|
||||
ParallelApplyStore< SerializableBase<int> > store( sw, rank );
|
||||
store.data( v );
|
||||
ParallelApply< SerializableBase<int> > 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<int> >&, void >
|
||||
{
|
||||
void operator() ( SerializableVector< SerializableBase<int> >& 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<int> > 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<int> 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<int> > > 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<int> > > store( w, 0 );
|
||||
store.data( metaV );
|
||||
ParallelApply< SerializableVector< SerializableBase<int> > > 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;
|
||||
}
|
||||
169
test/eompi/t-mpi-multistart.cpp
Executable file
169
test/eompi/t-mpi-multistart.cpp
Executable file
|
|
@ -0,0 +1,169 @@
|
|||
# include <paradiseo/eompi/eoMultiStart.h>
|
||||
using namespace eo::mpi;
|
||||
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
#include <paradiseo/eo.h>
|
||||
#include <paradiseo/eo/es.h>
|
||||
|
||||
/*
|
||||
* 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<double>, public eoserial::Persistent
|
||||
{
|
||||
public:
|
||||
|
||||
SerializableEOReal(unsigned size = 0, double value = 0.0) :
|
||||
eoReal<double>(size, value)
|
||||
{
|
||||
// empty
|
||||
}
|
||||
|
||||
void unpack( const eoserial::Object* obj )
|
||||
{
|
||||
this->clear();
|
||||
eoserial::unpackArray
|
||||
< std::vector<double>, 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<double>, 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<Indi> eval( real_value );
|
||||
eoPop<Indi> pop;
|
||||
eoUniformGenerator< double > generator;
|
||||
eoInitFixedLength< Indi > init( VEC_SIZE, generator );
|
||||
pop = eoPop<Indi>( POP_SIZE, init );
|
||||
|
||||
eoDetTournamentSelect<Indi> select(T_SIZE);
|
||||
eoSegmentCrossover<Indi> xover;
|
||||
eoUniformMutation<Indi> mutation(EPSILON);
|
||||
|
||||
eoGenContinue<Indi> continuator(MAX_GEN);
|
||||
/* Does work too with a steady fit continuator. */
|
||||
// eoSteadyFitContinue< Indi > continuator( 10, 50 );
|
||||
|
||||
eoSGA<Indi> 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;
|
||||
}
|
||||
220
test/eompi/t-mpi-parallelApply.cpp
Executable file
220
test/eompi/t-mpi-parallelApply.cpp
Executable file
|
|
@ -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 <benjamin.bouvier@gmail.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
* 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<int> 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 <paradiseo/eompi.h>
|
||||
# include <paradiseo/eompi/eoParallelApply.h>
|
||||
# include <paradiseo/eompi/eoTerminateJob.h>
|
||||
|
||||
# include "t-mpi-common.h"
|
||||
|
||||
# include <iostream>
|
||||
# include <cstdlib>
|
||||
|
||||
# include <vector>
|
||||
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<int>&, void >
|
||||
{
|
||||
void operator() ( SerializableBase<int> & x )
|
||||
{
|
||||
++x; // implicit conversion of SerializableBase<int> 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<int> > 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<int> > 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<int> 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<int> > 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<int> > 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;
|
||||
}
|
||||
|
||||
133
test/eompi/t-mpi-wrapper.cpp
Executable file
133
test/eompi/t-mpi-wrapper.cpp
Executable file
|
|
@ -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 <benjamin.bouvier@gmail.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
* 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 <paradiseo/eompi.h>
|
||||
# include <paradiseo/eompi/eoParallelApply.h>
|
||||
# include <paradiseo/eompi/eoTerminateJob.h>
|
||||
|
||||
# include "t-mpi-common.h"
|
||||
|
||||
# include <iostream>
|
||||
# include <cstdlib>
|
||||
|
||||
# include <vector>
|
||||
using namespace std;
|
||||
|
||||
using namespace eo::mpi;
|
||||
|
||||
// Job functor.
|
||||
struct plusOne : public eoUF< SerializableBase<int>&, void >
|
||||
{
|
||||
void operator() ( SerializableBase<int>& 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<EOT>
|
||||
{
|
||||
using IsFinishedParallelApply<EOT>::_wrapped;
|
||||
|
||||
ShowWrappedResult ( IsFinishedParallelApply<EOT> * w = 0 ) : IsFinishedParallelApply<EOT>( 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<int> > v;
|
||||
for( int i = 0; i < 1000; ++i )
|
||||
{
|
||||
v.push_back( rand() );
|
||||
}
|
||||
|
||||
int offset = 0;
|
||||
vector< SerializableBase<int> > originalV = v;
|
||||
|
||||
plusOne plusOneInstance;
|
||||
|
||||
StaticAssignmentAlgorithm assign( v.size() );
|
||||
|
||||
ParallelApplyStore< SerializableBase<int> > 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<int> > wrapper;
|
||||
store.wrapIsFinished( &wrapper );
|
||||
|
||||
ParallelApply< SerializableBase<int> > job( assign, eo::mpi::DEFAULT_MASTER, store );
|
||||
// Equivalent to:
|
||||
// Job< ParallelApplyData<int> > 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;
|
||||
}
|
||||
|
||||
104
test/eompi/template-job.cpp
Executable file
104
test/eompi/template-job.cpp
Executable file
|
|
@ -0,0 +1,104 @@
|
|||
# include <paradiseo/eompi.h>
|
||||
|
||||
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<EOT> >::_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<EOT>* 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<int> store;
|
||||
__TEMPLATE__<int> job( assignmentAlgo, DEFAULT_MASTER, store );
|
||||
}
|
||||
*/
|
||||
112
test/mo/CMakeLists.txt
Executable file
112
test/mo/CMakeLists.txt
Executable file
|
|
@ -0,0 +1,112 @@
|
|||
######################################################################################
|
||||
### 0) Include headers
|
||||
######################################################################################
|
||||
|
||||
#include_directories(${EO_SRC_DIR}/src)
|
||||
#include_directories(${MO_SRC_DIR}/src)
|
||||
#include_directories(${PROBLEMS_SRC_DIR})
|
||||
#include_directories(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
######################################################################################
|
||||
### 1) Define test list
|
||||
######################################################################################
|
||||
|
||||
set (TEST_LIST
|
||||
t-moAdaptiveWalkSampling
|
||||
t-moNeighbor
|
||||
t-moBitNeighbor
|
||||
t-moOrderNeighborhood
|
||||
t-moFullEvalByCopy
|
||||
t-moFullEvalByModif
|
||||
t-moNeighborComparator
|
||||
t-moSolNeighborComparator
|
||||
t-moTrueContinuator
|
||||
t-moRndWithoutReplNeighborhood
|
||||
t-moRndWithReplNeighborhood
|
||||
t-moFitnessStat
|
||||
t-moDistanceStat
|
||||
t-moNeighborhoodStat
|
||||
t-moCounterMonitorSaver
|
||||
t-moSolutionStat
|
||||
t-moCheckpoint
|
||||
t-moDummyMemory
|
||||
t-moSolVectorTabuList
|
||||
t-moBestImprAspiration
|
||||
t-moSimpleHCexplorer
|
||||
t-moRandomBestHCexplorer
|
||||
t-moNeutralHCexplorer
|
||||
t-moFirstImprHCexplorer
|
||||
t-moRandomWalkExplorer
|
||||
t-moMetropolisHastingExplorer
|
||||
t-moRandomNeutralWalkExplorer
|
||||
t-moTSexplorer
|
||||
t-moSolComparator
|
||||
t-moDummyEval
|
||||
t-moDummyNeighbor
|
||||
t-moDummyNeighborhood
|
||||
t-moSimpleCoolingSchedule
|
||||
t-moAlwaysAcceptCrit
|
||||
t-moBetterAcceptCrit
|
||||
t-moCountMoveMemory
|
||||
t-moMonOpPerturb
|
||||
t-moRestartPerturb
|
||||
t-moNeighborhoodPerturb
|
||||
t-moSAexplorer
|
||||
t-moSA
|
||||
t-moLocalSearch
|
||||
t-moILSexplorer
|
||||
t-moSimpleHC
|
||||
t-moFirstImprHC
|
||||
t-moRandomBestHC
|
||||
t-moNeighborVectorTabuList
|
||||
t-moMonOpDiversification
|
||||
t-moTS
|
||||
t-moILS
|
||||
t-moDummyLS
|
||||
t-moRandomSearch
|
||||
t-moMetropolisHasting
|
||||
t-moNeutralHC
|
||||
t-moRandomWalk
|
||||
t-moRandomNeutralWalk
|
||||
t-moIterContinuator
|
||||
t-moFitContinuator
|
||||
t-moCombinedContinuator
|
||||
t-moFullEvalContinuator
|
||||
t-moNeighborEvalContinuator
|
||||
t-moTimeContinuator
|
||||
t-moDummyExplorer
|
||||
t-moLocalSearchInit
|
||||
t-moSolInit
|
||||
t-moEvalCounter
|
||||
t-moNeighborBestStat
|
||||
t-moCounterStat
|
||||
t-moMinusOneCounterStat
|
||||
t-moVectorMonitor
|
||||
t-moRandomSearchExplorer
|
||||
t-moSampling
|
||||
t-moDensityOfStatesSampling
|
||||
t-moAutocorrelationSampling
|
||||
t-moHillClimberSampling
|
||||
t-moFDCsampling
|
||||
t-moNeutralDegreeSampling
|
||||
t-moFitnessCloudSampling
|
||||
t-moNeutralWalkSampling
|
||||
t-moStatistics
|
||||
t-moIndexedVectorTabuList
|
||||
# t-moRndIndexedVectorTabuList
|
||||
t-moDynSpanCoolingSchedule
|
||||
)
|
||||
|
||||
######################################################################################
|
||||
### 3) Create each test
|
||||
######################################################################################
|
||||
|
||||
foreach (test ${TEST_LIST})
|
||||
set ("T_${test}_SOURCES" "${test}.cpp")
|
||||
add_executable(${test} ${T_${test}_SOURCES})
|
||||
add_test(${test} ${test})
|
||||
target_link_libraries(${test} ga es eoutils eo)
|
||||
install(TARGETS ${test} RUNTIME DESTINATION share/${PROJECT_TAG}/mo/test COMPONENT tests)
|
||||
endforeach (test)
|
||||
|
||||
|
||||
251
test/mo/moTestClass.h
Executable file
251
test/mo/moTestClass.h
Executable file
|
|
@ -0,0 +1,251 @@
|
|||
/*
|
||||
<moTestClass.h>
|
||||
Copyright (C) DOLPHIN Project-Team, INRIA Lille - Nord Europe, 2006-2010
|
||||
|
||||
Sébastien Verel, Arnaud Liefooghe, Jérémie Humeau
|
||||
|
||||
This software is governed by the CeCILL license under French law and
|
||||
abiding by the rules of distribution of free software. You can use,
|
||||
modify and/ or redistribute the software under the terms of the CeCILL
|
||||
license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
"http://www.cecill.info".
|
||||
|
||||
As a counterpart to the access to the source code and rights to copy,
|
||||
modify and redistribute granted by the license, users are provided only
|
||||
with a limited warranty and the software's author, the holder of the
|
||||
economic rights, and the successive licensors have only limited liability.
|
||||
|
||||
In this respect, the user's attention is drawn to the risks associated
|
||||
with loading, using, modifying and/or developing or reproducing the
|
||||
software by the user in light of its specific status of free software,
|
||||
that may mean that it is complicated to manipulate, and that also
|
||||
therefore means that it is reserved for developers and experienced
|
||||
professionals having in-depth computer knowledge. Users are therefore
|
||||
encouraged to load and test the software's suitability as regards their
|
||||
requirements in conditions enabling the security of their systems and/or
|
||||
data to be ensured and, more generally, to use and operate it in the
|
||||
same conditions as regards security.
|
||||
The fact that you are presently reading this means that you have had
|
||||
knowledge of the CeCILL license and that you accept its terms.
|
||||
|
||||
ParadisEO WebSite : http://paradiseo.gforge.inria.fr
|
||||
Contact: paradiseo-help@lists.gforge.inria.fr
|
||||
*/
|
||||
|
||||
#ifndef _moTestClass_h
|
||||
#define _moTestClass_h
|
||||
|
||||
#include <paradiseo/eo/EO.h>
|
||||
#include <paradiseo/eo/eoEvalFunc.h>
|
||||
#include <paradiseo/mo/neighborhood/moNeighbor.h>
|
||||
#include <paradiseo/mo/neighborhood/moBackableNeighbor.h>
|
||||
#include <paradiseo/mo/neighborhood/moNeighborhood.h>
|
||||
#include <paradiseo/mo/neighborhood/moRndNeighborhood.h>
|
||||
#include <paradiseo/mo/eval/moEval.h>
|
||||
|
||||
#include <paradiseo/eo/ga/eoBit.h>
|
||||
#include <paradiseo/eo/eoScalarFitness.h>
|
||||
#include <paradiseo/mo/neighborhood/moOrderNeighborhood.h>
|
||||
#include <paradiseo/mo/problems/bitString/moBitNeighbor.h>
|
||||
#include <paradiseo/mo/neighborhood/moIndexNeighbor.h>
|
||||
|
||||
#include <paradiseo/eo/utils/eoMonitor.h>
|
||||
#include <paradiseo/eo/utils/eoUpdater.h>
|
||||
|
||||
#include <paradiseo/eo/eoInit.h>
|
||||
|
||||
typedef eoBit<eoMinimizingFitness> bitVector;
|
||||
typedef moBitNeighbor<eoMinimizingFitness> bitNeighbor;
|
||||
|
||||
class moDummyRndNeighborhood: public moOrderNeighborhood<bitNeighbor> ,
|
||||
public moRndNeighborhood<bitNeighbor> {
|
||||
public:
|
||||
moDummyRndNeighborhood(unsigned int a) :
|
||||
moOrderNeighborhood<bitNeighbor> (a) {
|
||||
}
|
||||
};
|
||||
|
||||
typedef moDummyRndNeighborhood bitNeighborhood;
|
||||
|
||||
typedef EO<int> Solution;
|
||||
|
||||
class moDummyNeighborTest: public moNeighbor<Solution> {
|
||||
public:
|
||||
virtual void move(Solution & _solution) {
|
||||
}
|
||||
};
|
||||
|
||||
class moDummyBackableNeighbor: public moBackableNeighbor<Solution> {
|
||||
public:
|
||||
virtual void move(Solution & _solution) {
|
||||
}
|
||||
virtual void moveBack(Solution & _solution) {
|
||||
}
|
||||
};
|
||||
|
||||
class moDummyNeighborhoodTest: public moNeighborhood<moDummyNeighborTest> {
|
||||
public:
|
||||
typedef moDummyNeighborTest Neighbor;
|
||||
|
||||
moDummyNeighborhoodTest() :
|
||||
i(0), j(0) {
|
||||
}
|
||||
|
||||
virtual bool hasNeighbor(EOT & _solution) {
|
||||
bool res;
|
||||
if (i % 3 == 0 || i == 1)
|
||||
res = false;
|
||||
else
|
||||
res = true;
|
||||
i++;
|
||||
return res;
|
||||
}
|
||||
virtual void init(EOT & _solution, Neighbor & _current) {
|
||||
}
|
||||
virtual void next(EOT & _solution, Neighbor & _current) {
|
||||
}
|
||||
virtual bool cont(EOT & _solution) {
|
||||
j++;
|
||||
return (j % 10 != 0);
|
||||
}
|
||||
|
||||
private:
|
||||
int i, j;
|
||||
};
|
||||
|
||||
class moDummyEvalTest: public eoEvalFunc<Solution> {
|
||||
public:
|
||||
void operator()(Solution& _sol) {
|
||||
if (_sol.invalid())
|
||||
_sol.fitness(100);
|
||||
else
|
||||
_sol.fitness(_sol.fitness() + 50);
|
||||
}
|
||||
};
|
||||
|
||||
class evalOneMax: public moEval<bitNeighbor> {
|
||||
private:
|
||||
unsigned size;
|
||||
|
||||
public:
|
||||
evalOneMax(unsigned _size) :
|
||||
size(_size) {
|
||||
}
|
||||
;
|
||||
|
||||
~evalOneMax(void) {
|
||||
}
|
||||
;
|
||||
|
||||
void operator()(bitVector& _sol, bitNeighbor& _n) {
|
||||
unsigned int fit = _sol.fitness();
|
||||
if (_sol[_n.index()])
|
||||
fit--;
|
||||
else
|
||||
fit++;
|
||||
_n.fitness(fit);
|
||||
}
|
||||
};
|
||||
|
||||
class dummyEvalOneMax: public moEval<bitNeighbor> {
|
||||
private:
|
||||
unsigned size;
|
||||
|
||||
public:
|
||||
dummyEvalOneMax(unsigned _size) :
|
||||
size(_size) {
|
||||
}
|
||||
;
|
||||
|
||||
~dummyEvalOneMax(void) {
|
||||
}
|
||||
;
|
||||
|
||||
void operator()(bitVector& _sol, bitNeighbor& _n) {
|
||||
unsigned int fit = _sol.fitness();
|
||||
_n.fitness(fit);
|
||||
}
|
||||
};
|
||||
|
||||
class monitor1: public eoMonitor {
|
||||
public:
|
||||
|
||||
monitor1(unsigned int& _a) :
|
||||
a(_a) {
|
||||
}
|
||||
|
||||
eoMonitor& operator()() {
|
||||
a++;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void lastCall() {
|
||||
a++;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned int& a;
|
||||
};
|
||||
|
||||
class monitor2: public eoMonitor {
|
||||
public:
|
||||
|
||||
monitor2(unsigned int& _a) :
|
||||
a(_a) {
|
||||
}
|
||||
|
||||
eoMonitor& operator()() {
|
||||
a++;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void lastCall() {
|
||||
a++;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned int& a;
|
||||
};
|
||||
|
||||
class updater1: public eoUpdater {
|
||||
public:
|
||||
updater1(unsigned int& _a) :
|
||||
a(_a) {
|
||||
}
|
||||
|
||||
void operator()() {
|
||||
a++;
|
||||
}
|
||||
|
||||
void lastCall() {
|
||||
a++;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned int& a;
|
||||
};
|
||||
|
||||
class dummyInit: public eoInit<bitVector> {
|
||||
public:
|
||||
void operator()(bitVector& sol) {
|
||||
}
|
||||
};
|
||||
|
||||
class dummyInit2: public eoInit<bitVector> {
|
||||
|
||||
public:
|
||||
dummyInit2(unsigned int _size) :
|
||||
size(_size) {
|
||||
}
|
||||
|
||||
void operator()(bitVector& sol) {
|
||||
sol.resize(0);
|
||||
for (unsigned int i = 0; i < size; i++)
|
||||
sol.push_back(true);
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned int size;
|
||||
};
|
||||
|
||||
#endif
|
||||
77
test/mo/t-moAdaptiveWalkSampling.cpp
Executable file
77
test/mo/t-moAdaptiveWalkSampling.cpp
Executable file
|
|
@ -0,0 +1,77 @@
|
|||
/*
|
||||
<t-moAdaptiveWalkSampling.cpp>
|
||||
Copyright (C) DOLPHIN Project-Team, INRIA Lille - Nord Europe, 2006-2010
|
||||
|
||||
Boufaras Karima
|
||||
|
||||
This software is governed by the CeCILL license under French law and
|
||||
abiding by the rules of distribution of free software. You can ue,
|
||||
modify and/ or redistribute the software under the terms of the CeCILL
|
||||
license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
"http://www.cecill.info".
|
||||
|
||||
In this respect, the user's attention is drawn to the risks associated
|
||||
with loading, using, modifying and/or developing or reproducing the
|
||||
software by the user in light of its specific status of free software,
|
||||
that may mean that it is complicated to manipulate, and that also
|
||||
therefore means that it is reserved for developers and experienced
|
||||
professionals having in-depth computer knowledge. Users are therefore
|
||||
encouraged to load and test the software's suitability as regards their
|
||||
requirements in conditions enabling the security of their systems and/or
|
||||
data to be ensured and, more generally, to use and operate it in the
|
||||
same conditions as regards security.
|
||||
The fact that you are presently reading this means that you have had
|
||||
knowledge of the CeCILL license and that you accept its terms.
|
||||
|
||||
ParadisEO WebSite : http://paradiseo.gforge.inria.fr
|
||||
Contact: paradiseo-help@lists.gforge.inria.fr
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cassert>
|
||||
|
||||
#include <paradiseo/mo/sampling/moAdaptiveWalkSampling.h>
|
||||
#include "moTestClass.h"
|
||||
#include <paradiseo/mo/algo/moFirstImprHC.h>
|
||||
#include <paradiseo/problems/eval/oneMaxEval.h>
|
||||
#include <paradiseo/mo/continuator/moSolutionStat.h>
|
||||
#include <paradiseo/mo/continuator/moCounterStat.h>
|
||||
#include <paradiseo/mo/continuator/moIterContinuator.h>
|
||||
|
||||
int main() {
|
||||
|
||||
std::cout << "[t-moAdaptiveWalkSampling] => START" << std::endl;
|
||||
|
||||
bitNeighborhood nh(5);
|
||||
oneMaxEval<bitVector> fullEval;
|
||||
evalOneMax eval(5);
|
||||
dummyInit2 init(5);
|
||||
moIterContinuator<bitNeighbor> cont(2);
|
||||
|
||||
moAdaptiveWalkSampling<bitNeighbor> test(init,nh,fullEval,eval,3);
|
||||
moCounterStat<bitVector> stat2;
|
||||
test.add(stat2);
|
||||
|
||||
test();
|
||||
|
||||
std::vector<double> res;
|
||||
std::vector<bitVector> res2;
|
||||
res = test.getValues(1);
|
||||
res2= test.getSolutions(0);
|
||||
|
||||
for (unsigned int i=0; i<res2.size(); i++)
|
||||
assert(res2[i].fitness()==5-i);
|
||||
|
||||
for (unsigned int i=0; i<res.size(); i++)
|
||||
assert(res[i]==i);
|
||||
|
||||
test.fileExport("outputTestAdaptativeWalkSampling1");
|
||||
test.fileExport(1, "outputTestAdaptativeWalkSampling2");
|
||||
|
||||
|
||||
std::cout << "[t-moAdaptiveWalkSampling] => OK" << std::endl;
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
51
test/mo/t-moAlwaysAcceptCrit.cpp
Executable file
51
test/mo/t-moAlwaysAcceptCrit.cpp
Executable file
|
|
@ -0,0 +1,51 @@
|
|||
/*
|
||||
<t-moAlwaysAcceptCrit.cpp>
|
||||
Copyright (C) DOLPHIN Project-Team, INRIA Lille - Nord Europe, 2006-2010
|
||||
|
||||
Sébastien Verel, Arnaud Liefooghe, Jérémie Humeau
|
||||
|
||||
This software is governed by the CeCILL license under French law and
|
||||
abiding by the rules of distribution of free software. You can ue,
|
||||
modify and/ or redistribute the software under the terms of the CeCILL
|
||||
license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
"http://www.cecill.info".
|
||||
|
||||
In this respect, the user's attention is drawn to the risks associated
|
||||
with loading, using, modifying and/or developing or reproducing the
|
||||
software by the user in light of its specific status of free software,
|
||||
that may mean that it is complicated to manipulate, and that also
|
||||
therefore means that it is reserved for developers and experienced
|
||||
professionals having in-depth computer knowledge. Users are therefore
|
||||
encouraged to load and test the software's suitability as regards their
|
||||
requirements in conditions enabling the security of their systems and/or
|
||||
data to be ensured and, more generally, to use and operate it in the
|
||||
same conditions as regards security.
|
||||
The fact that you are presently reading this means that you have had
|
||||
knowledge of the CeCILL license and that you accept its terms.
|
||||
|
||||
ParadisEO WebSite : http://paradiseo.gforge.inria.fr
|
||||
Contact: paradiseo-help@lists.gforge.inria.fr
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cassert>
|
||||
|
||||
#include <paradiseo/mo/acceptCrit/moAlwaysAcceptCrit.h>
|
||||
#include "moTestClass.h"
|
||||
|
||||
int main() {
|
||||
|
||||
std::cout << "[t-moAlwaysAcceptCrit] => START" << std::endl;
|
||||
|
||||
bitVector sol1, sol2;
|
||||
|
||||
moAlwaysAcceptCrit<bitNeighbor> test;
|
||||
|
||||
assert(test(sol1,sol2));
|
||||
|
||||
std::cout << "[t-moAlwaysAcceptCrit] => OK" << std::endl;
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
58
test/mo/t-moAutocorrelationSampling.cpp
Executable file
58
test/mo/t-moAutocorrelationSampling.cpp
Executable file
|
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
<t-moAutocorrelationSampling.cpp>
|
||||
Copyright (C) DOLPHIN Project-Team, INRIA Lille - Nord Europe, 2006-2010
|
||||
|
||||
Sébastien Verel, Arnaud Liefooghe, Jérémie Humeau
|
||||
|
||||
This software is governed by the CeCILL license under French law and
|
||||
abiding by the rules of distribution of free software. You can ue,
|
||||
modify and/ or redistribute the software under the terms of the CeCILL
|
||||
license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
"http://www.cecill.info".
|
||||
|
||||
In this respect, the user's attention is drawn to the risks associated
|
||||
with loading, using, modifying and/or developing or reproducing the
|
||||
software by the user in light of its specific status of free software,
|
||||
that may mean that it is complicated to manipulate, and that also
|
||||
therefore means that it is reserved for developers and experienced
|
||||
professionals having in-depth computer knowledge. Users are therefore
|
||||
encouraged to load and test the software's suitability as regards their
|
||||
requirements in conditions enabling the security of their systems and/or
|
||||
data to be ensured and, more generally, to use and operate it in the
|
||||
same conditions as regards security.
|
||||
The fact that you are presently reading this means that you have had
|
||||
knowledge of the CeCILL license and that you accept its terms.
|
||||
|
||||
ParadisEO WebSite : http://paradiseo.gforge.inria.fr
|
||||
Contact: paradiseo-help@lists.gforge.inria.fr
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cassert>
|
||||
|
||||
#include <paradiseo/mo/sampling/moAutocorrelationSampling.h>
|
||||
#include "moTestClass.h"
|
||||
#include <paradiseo/problems/eval/oneMaxEval.h>
|
||||
|
||||
int main() {
|
||||
|
||||
std::cout << "[t-moAutocorrelationSampling] => START" << std::endl;
|
||||
|
||||
bitNeighborhood nh(4);
|
||||
oneMaxEval<bitVector> fullEval;
|
||||
evalOneMax eval(4);
|
||||
dummyInit2 init(4);
|
||||
|
||||
moAutocorrelationSampling<bitNeighbor> test(init, nh, fullEval, eval, 3);
|
||||
|
||||
test();
|
||||
|
||||
test.fileExport("outputTestAutocorrelationSampling");
|
||||
|
||||
|
||||
std::cout << "[t-moAutocorrelationSampling] => OK" << std::endl;
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
78
test/mo/t-moBestImprAspiration.cpp
Executable file
78
test/mo/t-moBestImprAspiration.cpp
Executable file
|
|
@ -0,0 +1,78 @@
|
|||
/*
|
||||
<t-moBestImprAspiration.cpp>
|
||||
Copyright (C) DOLPHIN Project-Team, INRIA Lille - Nord Europe, 2006-2010
|
||||
|
||||
Sébastien Verel, Arnaud Liefooghe, Jérémie Humeau
|
||||
|
||||
This software is governed by the CeCILL license under French law and
|
||||
abiding by the rules of distribution of free software. You can ue,
|
||||
modify and/ or redistribute the software under the terms of the CeCILL
|
||||
license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
"http://www.cecill.info".
|
||||
|
||||
In this respect, the user's attention is drawn to the risks associated
|
||||
with loading, using, modifying and/or developing or reproducing the
|
||||
software by the user in light of its specific status of free software,
|
||||
that may mean that it is complicated to manipulate, and that also
|
||||
therefore means that it is reserved for developers and experienced
|
||||
professionals having in-depth computer knowledge. Users are therefore
|
||||
encouraged to load and test the software's suitability as regards their
|
||||
requirements in conditions enabling the security of their systems and/or
|
||||
data to be ensured and, more generally, to use and operate it in the
|
||||
same conditions as regards security.
|
||||
The fact that you are presently reading this means that you have had
|
||||
knowledge of the CeCILL license and that you accept its terms.
|
||||
|
||||
ParadisEO WebSite : http://paradiseo.gforge.inria.fr
|
||||
Contact: paradiseo-help@lists.gforge.inria.fr
|
||||
*/
|
||||
#include <paradiseo/mo/memory/moBestImprAspiration.h>
|
||||
#include "moTestClass.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cassert>
|
||||
|
||||
int main() {
|
||||
|
||||
std::cout << "[t-moBestImprAspiration] => START" << std::endl;
|
||||
|
||||
moBestImprAspiration<bitNeighbor> test;
|
||||
eoBit<eoMinimizingFitness> sol1(4);
|
||||
eoBit<eoMinimizingFitness> sol2(4);
|
||||
eoBit<eoMinimizingFitness> sol3(4);
|
||||
eoBit<eoMinimizingFitness> sol4(4);
|
||||
bitNeighbor n1;
|
||||
bitNeighbor n2;
|
||||
bitNeighbor n3;
|
||||
bitNeighbor n4;
|
||||
|
||||
sol3[0]=true;
|
||||
sol4[3]=true;
|
||||
|
||||
sol1.fitness(4);
|
||||
sol2.fitness(5);
|
||||
sol3.fitness(3);
|
||||
sol4.fitness(3);
|
||||
n1.fitness(4);
|
||||
n2.fitness(5);
|
||||
n3.fitness(3);
|
||||
n4.fitness(3);
|
||||
|
||||
|
||||
//verification qu'on update bien le best so far quand il faut
|
||||
test.init(sol1);
|
||||
assert(test.getBest()==sol1);
|
||||
assert(!test(sol2,n2));
|
||||
assert(test(sol3,n3));
|
||||
test.update(sol3,n3);
|
||||
assert(test.getBest()==sol3);
|
||||
assert(!test(sol4,n4));
|
||||
test.update(sol4,n4);
|
||||
assert(test.getBest()==sol3);
|
||||
|
||||
std::cout << "[t-moBestImprAspiration] => OK" << std::endl;
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
61
test/mo/t-moBetterAcceptCrit.cpp
Executable file
61
test/mo/t-moBetterAcceptCrit.cpp
Executable file
|
|
@ -0,0 +1,61 @@
|
|||
/*
|
||||
<t-moBetterAcceptCrit.cpp>
|
||||
Copyright (C) DOLPHIN Project-Team, INRIA Lille - Nord Europe, 2006-2010
|
||||
|
||||
Sébastien Verel, Arnaud Liefooghe, Jérémie Humeau
|
||||
|
||||
This software is governed by the CeCILL license under French law and
|
||||
abiding by the rules of distribution of free software. You can ue,
|
||||
modify and/ or redistribute the software under the terms of the CeCILL
|
||||
license as circulated by CEA, CNRS and INRIA at the following URL
|
||||
"http://www.cecill.info".
|
||||
|
||||
In this respect, the user's attention is drawn to the risks associated
|
||||
with loading, using, modifying and/or developing or reproducing the
|
||||
software by the user in light of its specific status of free software,
|
||||
that may mean that it is complicated to manipulate, and that also
|
||||
therefore means that it is reserved for developers and experienced
|
||||
professionals having in-depth computer knowledge. Users are therefore
|
||||
encouraged to load and test the software's suitability as regards their
|
||||
requirements in conditions enabling the security of their systems and/or
|
||||
data to be ensured and, more generally, to use and operate it in the
|
||||
same conditions as regards security.
|
||||
The fact that you are presently reading this means that you have had
|
||||
knowledge of the CeCILL license and that you accept its terms.
|
||||
|
||||
ParadisEO WebSite : http://paradiseo.gforge.inria.fr
|
||||
Contact: paradiseo-help@lists.gforge.inria.fr
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cassert>
|
||||
|
||||
#include <paradiseo/mo/comparator/moSolComparator.h>
|
||||
#include <paradiseo/mo/acceptCrit/moBetterAcceptCrit.h>
|
||||
#include "moTestClass.h"
|
||||
|
||||
int main() {
|
||||
|
||||
std::cout << "[t-moBetterAcceptCrit] => START" << std::endl;
|
||||
|
||||
bitVector sol1, sol2, sol3;
|
||||
|
||||
sol1.fitness(2);
|
||||
sol2.fitness(3);
|
||||
sol3.fitness(3);
|
||||
|
||||
moSolComparator<bitVector> comparator;
|
||||
|
||||
moBetterAcceptCrit<bitNeighbor> test(comparator);
|
||||
|
||||
assert(test(sol2, sol1));
|
||||
assert(!test(sol1, sol2));
|
||||
assert(!test(sol2, sol3));
|
||||
|
||||
|
||||
std::cout << "[t-moBetterAcceptCrit] => OK" << std::endl;
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue