* 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:
Adèle Harrissart 2014-08-04 13:40:28 +02:00
commit 490e837f7a
2359 changed files with 7688 additions and 16329 deletions

116
test/eo/CMakeLists.txt Executable file
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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;
}

View 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
View 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
View 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;
}

View 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
View 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
View 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
View 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
View 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
View 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;
}
//-----------------------------------------------------------------------------

View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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);
}

View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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;
}
//-----------------------------------------------------------------------------